Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep retired atoms' trust tier, stop retrying unparseable provider replies, and stop doctor recommending a refused sync (#9477)

Garry Tan55a679133179
diff --git a/behavior-changes.d/atom_retirement_keeps_tier_9456.md b/behavior-changes.d/atom_retirement_keeps_tier_9456.md
new file mode 100644
index 0000000000..02790cc2bd
--- /dev/null
+++ b/behavior-changes.d/atom_retirement_keeps_tier_9456.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+An atom a re-extraction retires now keeps the trust tier and write origin its extraction gave it, and an atom a later extraction produces again comes back at that tier. The retirement used to store the atom as unknown with no origin, so a revived atom stayed unknown. The same holds for every page a derived writer retires (chronicle events, synthesis outputs, gbrain repair stale-atoms). Atoms retired before this release keep the tier they were stored with.
diff --git a/behavior-changes.d/provider_response_unparseable_9466.md b/behavior-changes.d/provider_response_unparseable_9466.md
new file mode 100644
index 0000000000..e464a2830c
--- /dev/null
+++ b/behavior-changes.d/provider_response_unparseable_9466.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+A model provider that answers with a success status and a body that is not one JSON document (a route that streams when a request omits stream is the common cause) now fails with the non-retryable code provider_response_unparseable instead of a transient error. A facts job that hits it ends on its first attempt instead of retrying the same paid call, gbrain facts retry-dead does not resubmit it, and its recorded error reads cause=AIConfigError provider_response_unparseable. No response text is kept. Fix the route, for example with gbrain config set provider_chat_options.<provider>:<model> '{"stream": false}', then retry the job.
diff --git a/behavior-changes.d/sync_freshness_content_directory_9471.md b/behavior-changes.d/sync_freshness_content_directory_9471.md
new file mode 100644
index 0000000000..b8ab4ed657
--- /dev/null
+++ b/behavior-changes.d/sync_freshness_content_directory_9471.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+gbrain doctor's sync_freshness no longer fails a source whose folder sits inside gbrain's own content directory (for example one added beside the default source with gbrain sources add) and no longer tells you to run gbrain sync for it, a command that refuses such a source with sync_not_applicable. It counts the source as a content directory where sync does not apply and names gbrain import <dir> --source <id> for adding files instead.
diff --git a/changelog.d/capy-small-fix-wave-4.md b/changelog.d/capy-small-fix-wave-4.md
new file mode 100644
index 0000000000..6593f8c2f1
--- /dev/null
+++ b/changelog.d/capy-small-fix-wave-4.md
@@ -0,0 +1,10 @@
+**Three fixes from outside bug reports: retired atoms keep their trust tier, a provider answer that cannot be parsed is no longer retried, and doctor stops recommending a sync that refuses a source.**
+
+### Fixed
+- An atom a re-extraction retires keeps the trust tier and write origin its extraction gave it, and comes back at that tier when a later extraction produces it again. It used to be stored as `unknown` with no origin, and a revived atom stayed `unknown`. Every derived retirement (chronicle events, synthesis outputs, `gbrain repair stale-atoms`) now stamps its pages this way. Reported and first fixed by @howardpark (#9456).
+- A model provider that answers with a success status and a body that is not one JSON document now fails with the non-retryable code `provider_response_unparseable`. A facts job that hits it ends on its first attempt instead of paying for the same failing call again, `gbrain facts retry-dead` leaves it alone, and its recorded error names the parse failure without keeping any response text. Reported by @haumanto and first fixed by @Masashi-Ono0611 (#9466).
+- `gbrain doctor`'s `sync_freshness` no longer fails a source whose folder sits inside gbrain's own content directory, and no longer tells you to run `gbrain sync` for it, which refuses such a source with `sync_not_applicable`. It counts the source as a content directory and names `gbrain import <dir> --source <id>` instead. Reported by @railsloes and first fixed by @Masashi-Ono0611 (#9471).
+
+<!-- behavior-change: atom_retirement_keeps_tier_9456 -->
+<!-- behavior-change: provider_response_unparseable_9466 -->
+<!-- behavior-change: sync_freshness_content_directory_9471 -->
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index ab0914decd..d92b4cf6ac 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -43,7 +43,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json` (+ receipt `.mcp.json`), Codex `config.toml` (the user config, then the receipt workspace's `.codex/config.toml`) and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. #6453: with no PGLite lock, an HTTP registration gets a credential-free 3 s GET of `/health` (`probeHttpRegistration`): gbrain `ok` → `wired_running` + `mcp_access: 'unverified'`; refused loopback `http:` → `http_serve_missing` + fix; else `http_serve_unreachable`/`http_serve_unhealthy`, no fix. `redactRegistrationUrl` strips userinfo, query and fragment from every printed URL (`test/harness-wiring-redaction-6453.test.ts`). `agent_contract` reads the whole size-bounded log (`readAgentContractEvents(Infinity)`, 7-day window) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops each detected harness a plugin lane covers (`enabledPluginLanes`; all → `ok` `plugin_lane_enabled`, not smoke-tested) or whose receipt-recorded config it cannot read (#7422; all → `info` `registration_recorded`); the warning names the rest. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.
- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 126 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. GBRA-541: the entries that emit `LOST_WRITE_CHECKS` (`git_index_lag`, `db_ahead_of_git`, `strict_facts_outside_git`, `owner_host_stale`, `uncommitted_sync_deletions`) sit right after the privacy check, before the full scans, so slow scans on a large brain cannot use up the budget first (`test/doctor-entry-deadline-6803.test.ts`). `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` — a live serve owner warns with the exclusive two-step fix, a `pglite_busy` reason `legacy_owner_unverified` fails with details.reason and the refusal's ask_user preview fix, anything else is classified for `db-repair` — and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix; a grant missing only operations the owner approves by name stays `ok`, its message naming them with the by-name command); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
-- `src/commands/doctor/` — the doctor module directory behind the `doctor.ts` façade. `checks/` holds the check functions, grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, hashed over a file, with page liveness unresolvable by slug — count as their own `slug_unbound`, outside the drift total and the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run, cursor in config `doctor.timeline_history.scan:<sources>` so runs finish a pass (a clean pass stays `ok` until a newer row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts (lower bound past 10,000 found pages), non-round-trippable rows informational, repair `gbrain repair timeline`; segmented pages counted apart (`segmented_*`), no repair advice), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin (an origin a rename moved counts through `slug_rename_history`, GST-2687), one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). It drops every walked path sync would refuse (`unsyncableReason(prefix + relPath)`: metafiles such as root `AGENTS.md`/`CLAUDE.md`, pruned dirs, malformed names) before probing, so a same-slug page on `default` is not reported for a file sync never imports (#6681). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. `graph_coverage` and `orphan_ratio` count the entity types the active schema pack declares (#4772, `src/core/schema-pack/entity-types.ts`, resolved per source: brain-wide for `graph_coverage`, the asked source for `orphan_ratio --source`); a pack that does not load makes `graph_coverage` a warn naming the pack (never the old hardcoded list) and `orphan_ratio` answers with an "entity count unknown" caveat instead of a vacuous ok. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
+- `src/commands/doctor/` — the doctor module directory behind the `doctor.ts` façade. `checks/` holds the check functions, grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; a source whose root `syncContentDirectory` resolves to a gbrain content directory counts as `content_directory_count` (ok, hint `gbrain import <dir> --source <id>`), never a failing `gbrain sync` hint (#9471); `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, hashed over a file, with page liveness unresolvable by slug — count as their own `slug_unbound`, outside the drift total and the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run, cursor in config `doctor.timeline_history.scan:<sources>` so runs finish a pass (a clean pass stays `ok` until a newer row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts (lower bound past 10,000 found pages), non-round-trippable rows informational, repair `gbrain repair timeline`; segmented pages counted apart (`segmented_*`), no repair advice), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin (an origin a rename moved counts through `slug_rename_history`, GST-2687), one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). It drops every walked path sync would refuse (`unsyncableReason(prefix + relPath)`: metafiles such as root `AGENTS.md`/`CLAUDE.md`, pruned dirs, malformed names) before probing, so a same-slug page on `default` is not reported for a file sync never imports (#6681). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. `graph_coverage` and `orphan_ratio` count the entity types the active schema pack declares (#4772, `src/core/schema-pack/entity-types.ts`, resolved per source: brain-wide for `graph_coverage`, the asked source for `orphan_ratio --source`); a pack that does not load makes `graph_coverage` a warn naming the pack (never the old hardcoded list) and `orphan_ratio` answers with an "entity count unknown" caveat instead of a vacuous ok. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
- `src/commands/doctor/checks/default-source-path.ts` — the doctor-surface gathering wrapper: reads the `default` row, page counts (live + file-backed), `sync.repo_path`, the leak-guard collision and every other live source with a relative `local_path` (all named), then hands the verdict to `assessDefaultSourcePath`. Reads fallback inputs only for a null pointer; null on skip with no relative source.
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index dcff5c4ab8..c22f0319eb 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/engine-gateway.ts` + `src/core/engine-scope.ts` (GBRA-283 B2) — the AI gateway of an engine `openEngine` opened. `engineGatewayInput(settings)` builds its `AIGatewayConfig` from `settings.ai` (provider id → `apiKey`/`baseUrl`, folded into the recipe's key env name and `base_urls` or the native `*_BASE_URL`) and `settings.embedding`, never `process.env` or `~/.gbrain/config.json`; `scopedGatewayState` keeps one state (config, model clients, a query-cache tag, batch-shrink, no-key and structured-output memory) per held settings object, so a disconnect drops it; `settings.cache_namespace` tags that engine's cached query embeddings instead (B3a). `engineProviderProblem` refuses claude-cli and recipes with `resolveOpenAICompatConfig` (Azure). `gateway.ts` reads `gw()` (that state in an embedded engine's scope, else the process state `configureGateway` writes) and `configFor(recipe, touchpoint)` refuses `engine_scope_missing` before any call to a provider the engine lacks; a call with no scope while the process holds an open embedded engine refuses `engine_scope_required` (`refuseUnscoped`) whatever `configureGateway` set; discovery and `configureGatewayIfUninitialized` skip engine states, and `anthropic-key.ts` answers the scoped engine's own key. `withEngineScope(engine, fn)` (AsyncLocalStorage, `engine-scope-store.ts`; entered even before the first embedded engine opens) is entered by every operation handler (`operation-load.ts`), each persistence consumer (`persistence/service.ts`), minion jobs, `POST /mcp`, and `hybridSearch` and the import paths (`needsEngineScope`: once an embedded engine has opened, any engine other than the scoped one); `withLocalScope(fn)` marks a call for the process gateway (the CLI, `serve` and `jobs` enter it); `embeddedEngineInScope` resolves through `engineKey`. `engine-construct.ts` builds an engine without the process chat-usage sink (`createEngine` adds it), so `openEngine` registers a sink of its own. Pinned by `test/engine-gateway.test.ts` and `test/engine-scope-required.test.ts` (refusals, two engines, transaction/proxy/degraded sharing, a byte-identical process gateway for other engines, a canary key absent from errors, logs, doctor and read-back).
-- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`). #5304: `normalizeAIError(err, context, redact, routeHint)` appends `routeHint` to a 404's fix only; `src/core/ai/model-not-found-hint.ts` renders it from the gateway's recorded provenance (`gatewayModelNotFoundHint(touchpoint, model)` → `modelRouteHint`: "Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>"; env and config.json pins say what to clear; a deprecated key names the `models.*` key to set instead; the built-in default names the touchpoint's tier key; unrecorded or stale provenance adds nothing) and `embeddingModelNotFoundHint()` names `embedding_model` with the doctor route, never a bare `config set`. `gateway.ts` passes it at its `embed`, `expand` and `chat` 404 sites (`test/ai/model-not-found-hint-5304.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`). #6816: `providerContentBlockReason` also returns `claude_cli_usage_policy` for the claude-cli adapter's usage-policy refusal (`ClaudeCliProcessError`, no `apiErrorStatus`, `claude-cli reported error: API Error:` prefix, the AUP link and a refusal phrase: `CLAUDE_CLI_REFUSAL_RE`); `test/claude-cli-refusal-6816.test.ts`.
+- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`). #5304: `normalizeAIError(err, context, redact, routeHint)` appends `routeHint` to a 404's fix only; `src/core/ai/model-not-found-hint.ts` renders it from the gateway's recorded provenance (`gatewayModelNotFoundHint(touchpoint, model)` → `modelRouteHint`: "Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>"; env and config.json pins say what to clear; a deprecated key names the `models.*` key to set instead; the built-in default names the touchpoint's tier key; unrecorded or stale provenance adds nothing) and `embeddingModelNotFoundHint()` names `embedding_model` with the doctor route, never a bare `config set`. `gateway.ts` passes it at its `embed`, `expand` and `chat` 404 sites (`test/ai/model-not-found-hint-5304.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`). #6816: `providerContentBlockReason` also returns `claude_cli_usage_policy` for the claude-cli adapter's usage-policy refusal (`ClaudeCliProcessError`, no `apiErrorStatus`, `claude-cli reported error: API Error:` prefix, the AUP link and a refusal phrase: `CLAUDE_CLI_REFUSAL_RE`); `test/claude-cli-refusal-6816.test.ts`. #9466: `normalizeAIError` turns a success response whose body the AI SDK could not parse as one JSON document (`AI_JSONParseError`, alone or as the cause of a 2xx `AI_APICallError`) into a non-retryable `AIConfigError` with code `provider_response_unparseable` (`UNPARSEABLE_RESPONSE_CODE`) and fixed text that quotes no response body; `facts/extract.ts` puts that code in its cause label and `facts/dead-absorb-retry.ts` classifies it `not_retryable` (`test/ai/unparseable-success-response-9466.test.ts`).
- `src/core/ai/gateway.ts` — unified seam for every AI call. The `ai` SDK loads at the first provider call (lazy default transports), not on configure. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google too: `docs/ai-providers/google.md`). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish; and `'empty_response'` (#6448): a zero-tool-call clean stop whose text is empty or whitespace-only, so a refusal body or thinking-only turn is never reported as a finished answer (the subagent handler maps it to `error`). Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance. `embedQuery` caches query vectors per process (`src/core/ai/query-embed-cache.ts`: 512-entry LRU, 10-min TTL), keyed by recipe, model id, `base_urls` override, effective dims and the exact provider input (prefix + text). It stores only resolved vectors, as copies; the cache clears with `_modelCache` (configure, env refresh, engine re-stamp, reset, `__setEmbedTransportForTests`) and a generation counter drops an embed straddling a clear; an embed whose own engine closed mid-flight stores nothing. Document-side `embed()` is never cached; a caller under an AI invocation guard skips the cache read. **Prompt-cache breakpoints:** `cacheSystem: true` on a prompt-cache-capable route derives ONE `cacheControlValue` (config TTL override honoured) that marks the system block, the last tool def, the call-level auto marker and, since PR #6341, any user text `ChatBlock` flagged `cache: true` (`toModelMessages(messages, cacheControlValue)` merges `providerOptions.anthropic.cacheControl` onto that block); without a value the flag is dropped and the block is plain text, so non-caching routes and the claude-cli adapter (which joins text parts with `\n`) see the same prompt text. Pinned by `test/page-summary-prompt-cache.test.ts`.
- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line, and the first hop of a process queues one `chat_fallback_hop` safety notice in `fallback-hop-queue.ts`; with `chat_fallback_on_refusal: false` (`ChatFallbackOptions.onRefusal`, passed by `chat()` from the gateway config) a structural refusal is returned and a provider content block (`providerContentBlockReason`: a Gemini prompt block, or an HTTP 400 content-policy body such as OpenAI `invalid_prompt`, Azure `content_filter` or DeepSeek "Content Exists Risk") is thrown instead of being sent on, while provider errors still fall back; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`, including an unpriced chain entry under an explicit cap) or the caller's own abort stops the chain, and a cancel that lands while an attempt refuses returns that refusal instead of forwarding it; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, the edge_contradictions judge (apply mode defaults from a per-model certification), voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts` and `test/ai/chat-fallback-on-refusal.test.ts` (refusal switch through the real loader on every plane, the once-per-process hop notice).
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index b9810bfa9c..c536802f18 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -25,7 +25,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.) The refusal carries an additive `withdrawn` object (`factWithdrawnRefusal` in `facts/single-prepare.ts`, from `fact_withdrawals` only: the named entity's row over `all_entities`, then the newest, omitted when the caller cannot read the forgotten rows); `withdrawalFailureDetail`/`withdrawnFromDetail` in `facts/withdrawal.ts` keep it in the failed receipt's `error_detail` for `get_write_request` and replay. Tests: `test/withdrawn-detail.test.ts`, `test/e2e/withdrawn-detail-postgres.test.ts`.
- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete, after the belief-ledger expiry of recorded sources' tombstones: each is its own transaction and item (ItemRun site `purge.recorded_tombstones`), a run-scoped failure or a systemic run stops the purge, and any other failure lists the tombstone in `blocked` with its classified code, counts it in `failed` (no `error`, so the phase warns) and keeps it out of the bulk delete (`purgeDeletedPages` `excludeIds`); a content failure counts toward the same park as the managed purge, a transient one is retried next run, and parked tombstones are skipped as `purge_parked` unless `retryParked` (the unmanaged preview excludes them too). A managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (retention is not an owner purge; see [belief ledger](belief-ledger.md)). Writer state is read once per run (`writerOnboardingPreflight`): a source whose writer is `recovery_required` submits nothing and its tombstones are listed in `blocked` as `writer_not_active` (counted in `inactive`). Revision races are deferred to the next run; a parked tombstone (`purge-parks.ts`) is skipped as `purge_parked` (counted in `parked`) unless `retryParked`, and any other failure is listed in `blocked` and sets `error`. `selectPurgeCandidates` is the one eligibility selector (preview, consent, `purge_deleted_pages` op, run), and its holds are `purgeHoldsSql` (archived source, rename-identity, restorable-atom and derived-retirement holds), which doctor `embedding_state` also counts with; #6884: the run submits only while the writer has outstanding-request room (`readOutstandingRoom` in `journal.ts`, at `persistence.capacity.background_pause_pct` of the cap for a background run); the rest, and the rest after a `queue_capacity` refusal, is `blocked` as `write_capacity_deferred` and counted in `capacity_deferred`, never a failure or a park. `purgePhaseStatus`/`purgePhaseNote` shape the cycle purge phase (fail on `error`; warn on `writer_not_active`, parked, capacity-deferred or an unmanaged `failed` tombstone). The engine bulk delete (`engine-sql/pages.ts` `purgeDeletedPages`) also deletes, in its transaction, the purged pages' stagings (by source and slug) and the segment texts only their manifests referenced. GST-2689: every run first calls `repair/origin-carry.ts` `carryPrivateBeforePurge` (both branches); the origins it parks are listed in `blocked` as `derived_origin_parked` and counted in `origin_parked` (the phase warns), and `derivedOriginPurgeHold` is in `purgeHoldsSql`, the recorded-tombstone scan and delete, and the engine bulk delete. GST-2766: a page whose owner purge was held is owed that purge (`derived-origin-hold.ts` `recordOwedPurge`, op `owed-page-purge`, keyed by page id, no slug, live only while that tombstone exists); a managed run submits it as the owner purge, and an unmanaged run keeps it out of both bulk expiries and submits it through `purgeOwedPages` as an explicit `delete_page` purge, so the purge tombstones are written whichever run removes the page. The purge transaction (`page-purge.ts` `deletePurgedPage`), `engine-sql/pages.ts` `restorePage` and the `restore_page` apply clear the record. Tests: `test/managed-writers-w3.test.ts`, `test/purge-deleted-parks.test.ts`, `test/purge-deleted-capacity-6884.test.ts`, `test/pathological/a49-unmanaged-purge-tombstones.test.ts`, `test/derived-origin-carry-private.test.ts`.
-- `src/core/persistence/derived-retirement-hold.ts` — GBRA-161: the purge hold for every derived retirement. `DERIVED_RETIRED_BY` lists the `retired_by` stamps derived writers put on the pages they retire (extract-atoms, managed-reextract, stale-atoms, life-chronicle); `derivedRetirementPurgeHold(alias)` keeps a stamped page out of every purge route (engine bulk purge and its preview, the coordinated selection and delete) until `DERIVED_RETIREMENT_HOLD_DAYS` (30) after `deleted_at` (the database clock, never the `retired_at` text); `retireDerivedPages` versions, soft-deletes and stamps a batch in one attributed transaction (unmanaged extract_atoms). `assertRetirementStampUnchanged` is the page preparer's refusal (`reserved_frontmatter_key`) of a remote write that adds or changes one of `RESERVED_RETIREMENT_KEYS`. The hold length follows `generations.restore_days` (`RESTORE_DAYS_SQL`, read inside the purge statement; 30 by default) and `retireDerivedPagesInTransaction` is the in-transaction form generation adapters retire through. An explicit `gbrain delete --purge` is not held.
+- `src/core/persistence/derived-retirement-hold.ts` — GBRA-161: the purge hold for every derived retirement. `DERIVED_RETIRED_BY` lists the `retired_by` stamps derived writers put on the pages they retire (extract-atoms, managed-reextract, stale-atoms, life-chronicle); `derivedRetirementPurgeHold(alias)` keeps a stamped page out of every purge route (engine bulk purge and its preview, the coordinated selection and delete) until `DERIVED_RETIREMENT_HOLD_DAYS` (30) after `deleted_at` (the database clock, never the `retired_at` text); `retireDerivedPages` versions, soft-deletes and stamps a batch in one attributed transaction (unmanaged extract_atoms). `stampDerivedRetirement` is the one retirement stamp every derived writer calls inside its own write (managed atom and generation retirements, `gbrain repair stale-atoms`, a journaled chronicle retire); it runs under `withTrustKeep`, so the page keeps its stored trust tier and write origin (#9456, `test/atom-retirement-keeps-trust-9456.test.ts`). `assertRetirementStampUnchanged` is the page preparer's refusal (`reserved_frontmatter_key`) of a remote write that adds or changes one of `RESERVED_RETIREMENT_KEYS`. The hold length follows `generations.restore_days` (`RESTORE_DAYS_SQL`, read inside the purge statement; 30 by default) and `retireDerivedPagesInTransaction` is the in-transaction form generation adapters retire through. An explicit `gbrain delete --purge` is not held.
- `src/core/generations/ledger-scrub.ts` — GBRA-161: purge reaches the generation ledger. A page purge (`page-purge.ts`) nulls the purged item's preimages in `derived_generation_items` and every held proposal in `derived_generations` naming it, and deletes the page's fence holds (`FENCE_GENERATION_KINDS` under `page:<slug>`, whose rows the purge deletes; `test/generations-purge-fence-hold-7774.test.ts`); a fact purge (`facts/purge.ts`) nulls every preimage, proposal and held context carrying the claim. Both are `swept` (`generation_ledger`) in the deletion inventory, so the verification probes them; `gbrain repair generations` then refuses a scrubbed item with `no_preimage`.
- `src/core/persistence/purge-name-stores.ts` — #9068: `scrubPurgedNameStores(engine, sourceId, slugs)` deletes the source's `context_volunteer_events` rows (whose rationale quotes the matched name) and `mention_gazetteer_entries` rows (`name_norm -> target_slug`) for purged slugs. Every hard delete of a page calls it inside its transaction (`purgePageInTransaction`, `purgeDeletedPages`, `expireRecordedTombstones`, the restore purge replay in `belief/purge-mirror.ts`, and the engines' batch `deletePages`); removing a source deletes the source's volunteer rows (`removedSourceScrubCtes` in `source-delete.ts`) and its gazetteer rows by cascade; a soft delete keeps both. Both tables are `swept` (`page_names`) in the deletion inventory; the page receipt checks them by slug, and the fact receipt probes them (rationale, name_norm) and reports a match as `probed_reported`, because a fact purge sweeps neither.
- `src/core/persistence/purge-slug-stores.ts` — #9146: `scrubPurgedSlugStores(engine, sourceId, slugs, { ifPresent })` deletes the six stores keyed to a page by source and slug with no foreign key to pages (`take_proposals`, `open_loops`, `core_edit_notices`, `page_aliases`, `slug_aliases` by `canonical_slug`, `slug_rename_history` by `new_slug`) and returns rows removed per store; `scrubPurgedSlugHolds` deletes the slug's `write_gate_holds` and their `write_gate_receipts`, and on a tombstone expiry (`deletedAt` given) keeps a hold created or last seen after the soft delete. Every hard delete calls them inside its transaction (`purgePageInTransaction` for the stores, `expireRecordedTombstones`, the engines' batch `deletePages` and purge path, the restore purge replay in `belief/purge-mirror.ts` with `ifPresent`); a soft delete keeps them. Source removal deletes `core_edit_notices` and the holds with their receipts in `removedSourceScrubCtes`; the other five cascade from sources. Test: `test/purge-slug-stores-9146.test.ts`.
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 60307f3e5f..8e33c73c79 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -240,7 +240,6 @@ or a physical projection that leaves attribution untouched):
- `src/commands/sync/holds.ts` (1): a full sync's move of a held rename (`updateSlug` and its `source_path`) runs in one `maintenanceTransaction`; managed sources publish renames through the sync request preparer.
- `src/commands/sync/rename-collision.ts` (2): the legacy sync rename (`updateSlug`, and the tombstone re-key when the destination slug is a soft-deleted row, #5431) runs with its `source_path` repair in one `maintenanceTransaction`; managed sources publish renames through the sync request preparer.
- `src/core/calibration/undo-wave.ts` (1): the calibration wave undo of take resolutions runs in `maintenanceTransaction`.
-- `src/core/chronicle/publish.ts` (1): the retired stamp (and timeline row removal) of a `managed_maintenance_chronicle_retire` request an earlier release journaled, inside that request's coordinated write; every other chronicle event write moved to `generations/adapters/chronicle-events.ts` (GBRA-161 PR 3).
- `src/core/company-brain/profile.ts` (1): legacy sync soft deletes (`softDeleteSyncPages`) run in `maintenanceTransaction`, inside the company-brain source check when one is active.
- `src/core/cycle/dream-provenance.ts` (1): the dream provenance frontmatter stamp runs per page in `maintenanceTransaction`, or `derivedMaintenanceTransaction` at the child's derived tier when the ref carries its taint (unmanaged brains only; managed synthesis publishes through maintenance requests).
- `src/core/cycle/extract-facts.ts` (6): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication. Both reconcile paths write at the page's tier and gate new rows.
@@ -274,7 +273,6 @@ or a physical projection that leaves attribution untouched):
- `src/core/generations/adapters/atoms.ts` (1): the unmanaged atom completion stamp (`source_hash`) runs inside the generation activation's `maintenanceTransaction` (`publish.ts`, GBRA-161).
- `src/core/generations/adapters/chronicle-events.ts` (3): Life Chronicle event writes, their timeline projection rows and the retirement of dropped events run inside the generation activation's `maintenanceTransaction` (`publish.ts`) on unmanaged brains and inside the coordinated `managed_generation_activate` / `managed_generation_restore` requests on managed brains (GBRA-161 PR 3); a restore runs in the restore runner's (`repair.ts`).
- `src/core/generations/adapters/single-page.ts` (3): the unmanaged dream summary, saved `think` page and drift report (the page, its tags, and the page_versions copy of the live page it replaces) run inside the generation activation's `maintenanceTransaction` (`publish.ts`), attributed at the derivation's tier when the writer declares one (GBRA-161 PR 5); managed brains publish them through a maintenance request.
-- `src/core/generations/managed-retire.ts` (1): the retirement stamp (`retired_by`, `retired_at`) of one synthesis output a managed generation retires runs inside its `managed_generation_retire` request's coordinated write, after the versioned page delete (GBRA-161 PR 4).
- `src/core/generations/adapters/extracted-facts.ts` (2): the extracted-facts generation's row inserts and retirements (`publishExtractedFacts`, GBRA-161 PR 2) run inside the generation activation's `maintenanceTransaction` (`publish.ts`); its restore runs in the restore runner's (`repair.ts`).
- `src/core/generations/adapters/fact-rows.ts` (1): putting a fact's recorded before-state back (`restoreFactRow`) runs only inside a generation restore's `maintenanceTransaction` (`repair.ts`, GBRA-161 PR 2).
- `src/core/generations/fence-evidence.ts` (1): `moveKeptRows` renumbers a kept database-only fact whose row number a fence row now claims (#8819); it runs only inside the fence projection's request publication (`canonical-projections.ts`) and the extract_facts reconcile's write (`maintenanceTransaction` or the managed request's preparer).
@@ -286,13 +284,12 @@ or a physical projection that leaves attribution untouched):
- `src/core/page-state/materialize.ts` (1): coordinated maintenance.
- `src/core/page-state/rename-alias.ts` (5): the fact slug rewrite runs inside its caller's `updateSlug` transaction, and `movePageIdReferences` (#5431: page_versions, timeline_entries and links moved to the row that materialized under a fallback rename) runs inside `carryRenameIdentity`'s `maintenanceTransaction`; every caller is attributed.
- `src/core/page-state/versions.ts` (3): `createVersion` itself, its segmented-page twin and the pruned-history marks (`successor_pruned`, `version_history_gap_at`); the caller's scope supplies the actor.
-- `src/core/persistence/atom-maintenance.ts` (1): request preparer.
- `src/core/persistence/canonical-projections.ts` (8): fence projection inside the request's publication.
- `src/core/persistence/change-reason.ts` (1): stamps a page write's `reason` on the snapshot its publication archived, inside that request's publication apply.
- `src/core/persistence/connector-google-receipts.ts` (2): request preparer.
- `src/core/persistence/connector-sync.ts` (2): connector publication inside `withCoordinatedWrite`.
- `src/core/persistence/derived-facts.ts` (1): the gated conversation fact insert (`insertDerivedFacts`) on unmanaged brains, in `writeDerivedFacts`' `maintenanceTransaction` at the page's derived tier.
-- `src/core/persistence/derived-retirement-hold.ts` (3): `retireDerivedPages` versions, soft-deletes and stamps retired derived pages (unmanaged extract_atoms stale atoms) in 500-page `maintenanceTransaction` chunks.
+- `src/core/persistence/derived-retirement-hold.ts` (3): `retireDerivedPages` versions, soft-deletes and stamps retired derived pages (unmanaged extract_atoms stale atoms) in 500-page `maintenanceTransaction` chunks. `stampDerivedRetirement` is the one retirement stamp (`retired_by`, `retired_at`) every derived writer calls inside its own attributed or coordinated write (managed atom and generation retirements, `gbrain repair stale-atoms`, a journaled chronicle retire); it keeps the page's stored trust tier and write origin (#9456).
- `src/core/persistence/facts-prepare.ts` (3): managed `extract_facts` request preparer.
- `src/core/persistence/file-repair.ts` (3): `managed_file_repair` request preparer (#5988); a GST-1601 adoption tags the page_versions rows its import wrote with `change_reason = 'adopted_local_edit'` inside the same coordinated publication, attributed to the adoption request.
- `src/core/persistence/links-maintenance.ts` (1): coordinated maintenance.
@@ -326,7 +323,6 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/rename-identity.ts` (5): `gbrain repair rename-identity` carry, unmanaged brains only (a managed brain refuses `managed_remedy_unavailable` before writing); the fence-row merge, the provisional page's retirement, the slug move and the import run in one `maintenanceTransaction` under both page locks after the plan-hash recheck.
- `src/core/repair/secret-spans.ts` (1): `gbrain repair secret-spans` (GST-327) rewrites the credential spans of each preview-approved page under the page key: inside `withCoordinatedWrite` with maintenance attribution on managed brains, `withWriteAttribution` with maintenance attribution on unmanaged ones.
- `src/core/repair/segmented-tiling.ts` (1): `gbrain repair segmented-tiling` (GST-1209) versions each preview-approved damaged page (`createVersion`) before republishing it from the file Git holds at HEAD, under the page key: inside `withCoordinatedWrite` with maintenance attribution on managed brains, `withWriteAttribution` with maintenance attribution on unmanaged ones.
-- `src/core/repair/stale-atoms.ts` (1): the retirement stamp. On managed brains it runs in the `managed_maintenance_retire_stale_atoms` request's apply; on unmanaged brains the retirement is an approved atom generation (`publishGeneration`, one `maintenanceTransaction`) and the stamp runs in its `onRetired` callback inside that transaction.
- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: a receipted `managed_maintenance_take_reproject` request on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.
- `src/core/repair/timeline-comments.ts` (1): `gbrain repair timeline-comments` row cleanup: `withCoordinatedWrite` under the page key on managed brains, `maintenanceTransaction` otherwise.
- `src/core/repair/url-clone-fences.ts` (2): `gbrain repair url-clone-fences` (#6946), unmanaged brains only (a managed brain previews nothing); keeping the appended fence rows database-only (clearing `row_num`, inserting a row the database lost) runs in one `maintenanceTransaction` under the page lock after the preview recheck; HEAD's bytes then import through `importFromContent` (a HEAD that asks for private in a spelling page privacy does not read is held: not imported, and the apply reports `held`, #7897).
diff --git a/docs/contracts/public-surface.json b/docs/contracts/public-surface.json
index 2005eae934..fce55c2112 100644
--- a/docs/contracts/public-surface.json
+++ b/docs/contracts/public-surface.json
@@ -2817,6 +2817,7 @@
"proposal_expired": 1,
"proposals_pending_limit": 1,
"provenance_required": 1,
+ "provider_response_unparseable": 1,
"publication_pending": 1,
"publish_scan_unreadable": 1,
"publish_secret_found": 1,
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4ee82cde41..e4ae5b9dbe 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4074,6 +4074,14 @@ More: [docs/guides/qm.md#proposed-writes](../../docs/guides/qm.md#proposed-write
|---|---|---|---|---|---|---|
| provenance is required and must be non-empty. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### provider_response_unparseable
+
+<a id="provider_response_unparseable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A model provider answered with a success status, but its response body could not be parsed as one JSON document; no response text is kept. | The same request gets the same body, so retrying spends another paid call on the same failure. The common cause is a provider route that streams (Server-Sent Events) when a request omits `stream`; a job that hits it ends on its first attempt. | Ask the operator to make the route return one JSON body for a non-streaming request, for example with gbrain config set provider_chat_options.<provider>:<model> '{"stream": false}', then retry the job. | host_admin | `gbrain doctor --json` | 1 | no |
+
### publication_pending
<a id="publication_pending"></a>
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 29dfee71cd..ad6b2eabc9 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -30,6 +30,7 @@ import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts
import { quarantineFilterFragment } from '../../../core/quarantine.ts';
import { persistenceEnabledForHealth } from '../../../core/persistence/ownership.ts';
import { upstreamFreshness } from '../../../core/sync-upstream.ts';
+import { syncContentDirectory } from '../../../core/sync-applicability.ts';
import type { Check } from '../../doctor.ts';
import { isOwnedContentSchemaMissing, ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';
import { readOnlyCatalogPackSourceIds } from '../../../core/shared-skills/adopted-packs.ts';
@@ -1212,6 +1213,8 @@ export async function checkSyncFreshness(
// #6076: an adopted read-only catalog pack (no commit history) has nothing to sync.
const catalogPacks = await readOnlyCatalogPackSourceIds(engine, sources, localOnly);
let writer_owned_count = 0, read_only_pack_count = 0;
+ // #9471: roots inside gbrain's own content directory, which sync refuses (a receipt-claimed root stays writer-owned above).
+ const contentDirectories: Array<{ id: string; keyless: boolean }> = [];
// v0.41.27.0: D6 count math. Every source falls into
// EXACTLY ONE bucket per iteration. Invariant pinned by unit test:
// unchanged + synced_recently + stale + writer_owned + read_only_pack counts === sources.length
@@ -1268,6 +1271,8 @@ export async function checkSyncFreshness(
for (const source of sources) {
if (ownedContent.has(source.id)) { writer_owned_count++; continue; }
if (catalogPacks.ids.has(source.id)) { read_only_pack_count++; continue; }
+ const contentDirectory = await syncContentDirectory(engine, { sourceId: source.id, repoPath: source.local_path ?? undefined });
+ if (contentDirectory?.ownedBy === 'content_root') { contentDirectories.push({ id: source.id, keyless: contentDirectory.keyless }); continue; }
// Embed source.id in user-visible messages so `gbrain sync --source <id>`
// matches what the user copy-pastes. Show display name in parens when set.
const display = source.name && source.name !== source.id
@@ -1432,14 +1437,16 @@ export async function checkSyncFreshness(
// D6 invariant: every source incremented exactly one bucket.
const details = { unchanged_count, synced_recently_count, stale_count, ...(writer_owned_count ? { writer_owned_count } : {}),
- ...(read_only_pack_count ? { read_only_pack_count } : {}), ...(catalogPacks.note ? { read_only_pack_note: catalogPacks.note } : {}),
+ ...(read_only_pack_count ? { read_only_pack_count } : {}), ...(contentDirectories.length ? { content_directory_count: contentDirectories.length } : {}), ...(catalogPacks.note ? { read_only_pack_note: catalogPacks.note } : {}),
...(outcomes.length ? { code: outcomes[0]!.code, no_successful_sync: outcomes } : {}),
...(upstream_unknown_count ? { upstream_unknown_count } : {}), ...(upstream_behind_count ? { upstream_behind_count } : {}) };
// BUG 4: append in-progress context when any source is actively syncing.
// Empty otherwise, so steady-state messages are byte-for-byte unchanged.
const inProgressNote = (inProgress.length ? `. ${inProgress.join('; ')}` : '')
+ (writer_owned_count ? `. ${writer_owned_count} writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status` : '')
- + (read_only_pack_count ? `. ${read_only_pack_count} read-only skill-pack source(s): no commits to sync` : '') + (catalogPacks.note ? `. ${catalogPacks.note}` : '');
+ + (read_only_pack_count ? `. ${read_only_pack_count} read-only skill-pack source(s): no commits to sync` : '')
+ + (contentDirectories.length ? `. ${contentDirectories.length} gbrain-owned content director${contentDirectories.length === 1 ? 'y' : 'ies'}, where sync does not apply: add files with ${contentDirectories.map(dir => `\`gbrain import <dir>${dir.keyless ? ' --no-embed' : ''} --source ${dir.id}\``).join(', ')}` : '')
+ + (catalogPacks.note ? `. ${catalogPacks.note}` : '');
const remedy = issues.length > outcomes.length;
const moved = managed && localOnly && staleIds.length ? await checkpointMovedFix(engine, staleIds) : null;
@@ -1456,7 +1463,7 @@ export async function checkSyncFreshness(
name: 'sync_freshness', status: 'ok',
message: `${writer_owned_count} writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status.`, details,
};
- const upstreamCount = sources.length - writer_owned_count - read_only_pack_count;
+ const upstreamCount = sources.length - writer_owned_count - read_only_pack_count - contentDirectories.length;
if (upstreamCount === 0) return { name: 'sync_freshness', status: 'ok', message: `No upstream-synced sources${inProgressNote}.`, details };
// v0.41.27.0: D2 ok-message reshape. Three branches surface what the
// git short-circuit actually did so operators understand "unchanged
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index b925202d5a..dc40d27944 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -83,6 +83,23 @@ function scrubErrorChain(err: unknown, redact: (text: string) => string): void {
}
}
+/** #9466: the registry code of a success response whose body the AI SDK could not parse as one JSON document. */
+export const UNPARSEABLE_RESPONSE_CODE = 'provider_response_unparseable';
+
+/**
+ * #9466: the provider answered with a success status and a body that is not one JSON document. The AI SDK raises its
+ * JSON parse error, wrapped in an API call error that carries the 2xx status when it read a response. The same request
+ * gets the same body (the common case: a route that streams Server-Sent Events when `stream` is omitted), so retrying
+ * cannot help. A body that parsed but failed the response schema, and an error status whose body did not parse, are not
+ * this case.
+ */
+function unparseableSuccessResponse(err: unknown): boolean {
+ const e = err as { name?: unknown; statusCode?: unknown; cause?: unknown } | null;
+ if (e?.name === 'AI_JSONParseError') return true;
+ return e?.name === 'AI_APICallError' && typeof e.statusCode === 'number' && e.statusCode >= 200 && e.statusCode < 300
+ && (e.cause as { name?: unknown } | null)?.name === 'AI_JSONParseError';
+}
+
/** Model ids a provider renamed, mapped to the current id (B-N7: suggested on a 404). */
const KNOWN_MODEL_RENAMES: Readonly<Record<string, string>> = {
'deepseek:deepseek-v4-flash': 'deepseek:deepseek-flash',
@@ -146,6 +163,16 @@ export function normalizeAIError(err: unknown, context?: string, redact?: (text:
));
}
+ // #9466: fixed text only; the SDK's parse error quotes the response body, which must not reach a log or a job row.
+ if (unparseableSuccessResponse(err)) {
+ return Object.assign(carryStatusFields(err, new AIConfigError(
+ `${ctxPrefix}The provider answered with a success status, but the response body could not be parsed as one JSON document.`,
+ 'Check that this provider route returns one JSON body for a non-streaming request; a route that streams when `stream` is omitted is the common cause. '
+ + 'Send the field the route needs for that model with gbrain config set provider_chat_options.<provider>:<model> \'{"stream": false}\', or fix the route.',
+ err,
+ )), { code: UNPARSEABLE_RESPONSE_CODE, retryable: false });
+ }
+
// AI SDK named errors
if (name === 'LoadAPIKeyError' || name === 'InvalidArgumentError') {
return carryStatusFields(err, new AIConfigError(`${ctxPrefix}${msg}`, undefined, err));
diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.ts
index 07803ed8f4..d32bd8a39b 100644
--- a/src/core/chronicle/publish.ts
+++ b/src/core/chronicle/publish.ts
@@ -39,6 +39,7 @@ import { serializeMarkdown } from '../markdown.ts';
import { digest } from '../persistence/digest.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
+import { stampDerivedRetirement } from '../persistence/derived-retirement-hold.ts';
import type { Visibility } from '../search/private-visibility.ts';
import type { ChronicleEventProposal } from './extract-events.ts';
import { resolveChronicleEventSlugs } from './event-identity.ts';
@@ -295,8 +296,7 @@ export async function prepareChronicleMutation(engine: BrainEngine, row: WriteRe
/** A retirement journaled by an earlier release (`managed_maintenance_chronicle_retire`): the stamp, and its projection row goes with it (C-3). */
async function stampRetired(tx: BrainEngine, sourceId: string, slug: string): Promise<void> {
- await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
- WHERE source_id=$3 AND slug=$4 AND deleted_at IS NOT NULL`, [CHRONICLE_RETIRED_BY, new Date().toISOString(), sourceId, slug]);
+ await stampDerivedRetirement(tx, sourceId, [slug], CHRONICLE_RETIRED_BY);
await tx.executeRaw('DELETE FROM timeline_entries t USING pages p WHERE p.id=t.event_page_id AND p.source_id=$1 AND p.slug=$2', [sourceId, slug]);
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c2117cf548..5df942ee06 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -651,6 +651,7 @@ export const CODES = {
proposal_expired: { class: 'caller', summary: "The memory proposal passed its TTL (proposals.ttl_hours) before the owner decided, so nothing was written.", why: 'A held proposal is only as current as the page QM showed the person; an old one is closed rather than applied.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'The proposer sends a new proposal if the change is still wanted; the operator raises proposals.ttl_hours to give owners longer.' },
proposals_pending_limit: { class: 'retryable', summary: "Too many memory proposals already await the owner for this person (proposals.max_pending_per_actor) or this credential (proposals.max_pending_per_credential), so this one was not saved.", reasons: ['actor', 'credential'], why: 'The caps keep one system credential from flooding the owner with held text.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'Wait for the owner to decide or for a proposal to expire, or cancel one with cancel_write_request; the operator sets the caps.' },
provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
+ provider_response_unparseable: { class: 'host_only', retryable: false, summary: "A model provider answered with a success status, but its response body could not be parsed as one JSON document; no response text is kept.", why: "The same request gets the same body, so retrying spends another paid call on the same failure. The common cause is a provider route that streams (Server-Sent Events) when a request omits `stream`; a job that hits it ends on its first attempt.", suggestion: "Ask the operator to make the route return one JSON body for a non-streaming request, for example with gbrain config set provider_chat_options.<provider>:<model> '{\"stream\": false}', then retry the job." },
publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
pull_blocked_local_changes: { class: 'caller', retryable: false, actor: 'user',
summary: "A gbrain-owned clone (sources add --url) has local changes in its checkout, so git pull --ff-only cannot fast-forward it and every sync of the source stops at the pull.",
diff --git a/src/core/facts/dead-absorb-retry.ts b/src/core/facts/dead-absorb-retry.ts
index 562ea129b1..294a485540 100644
--- a/src/core/facts/dead-absorb-retry.ts
+++ b/src/core/facts/dead-absorb-retry.ts
@@ -36,7 +36,7 @@ export type DeadAbsorbClass = 'provider' | 'config' | 'not_retryable';
* Provider and configuration failures clear on their own or with an operator fix; everything else stays dead.
* Extraction failures carry `[facts-extract] <reason> (model=..) (cause=<class> <global llm class>)` (extract.ts):
* provider_error and chat_unavailable are retryable; refusal, content filter, malformed or truncated output fail the
- * same way on the same page text.
+ * same way on the same page text, and so does a provider_error whose success response could not be parsed (#9466).
*/
export function classifyDeadFactsAbsorb(errorText: string | null | undefined): DeadAbsorbClass {
const text = errorText ?? '';
@@ -45,6 +45,7 @@ export function classifyDeadFactsAbsorb(errorText: string | null | undefined): D
if (extract) {
if (extract[1] === 'chat_unavailable') return 'config';
if (extract[1] !== 'provider_error') return 'not_retryable';
+ if (/\(cause=[^)]*\bprovider_response_unparseable\b/.test(text)) return 'not_retryable';
return /\(cause=[^)]*\b(auth|billing|model_not_found)\b/.test(text) ? 'config' : 'provider';
}
if (/chat_unavailable|no usable provider key|not servable|model[_ ]not[_ ]found|billing|insufficient[_ ]quota|credit/i.test(text)) return 'config';
@@ -121,7 +122,11 @@ async function reconcile(engine: BrainEngine, opts: { apply: boolean; record?: b
if (row.status !== 'dead') continue;
const cls = classifyDeadFactsAbsorb(row.error_text);
const known = state.keys[row.idempotency_key];
- if (cls === 'not_retryable' && !known) { result.not_retryable.push({ job_id: Number(row.id), slug: row.slug }); continue; }
+ if (cls === 'not_retryable' && known?.class !== 'not_retryable') {
+ delete state.keys[row.idempotency_key];
+ result.not_retryable.push({ job_id: Number(row.id), slug: row.slug });
+ continue;
+ }
state.keys[row.idempotency_key] = known ?? newEntry(row, cls, opts.now);
}
const due: string[] = [];
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 2826ba2e04..77630b6ff6 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -25,7 +25,7 @@
import { observationDateLine, observationDateRule, parseExtractedEventDate, type ObservationDate } from '../ai/date-grounding.ts';
import { chat, embedOne, isAvailable, getEmbeddingModel } from '../ai/gateway.ts';
-import { classifyGlobalLlmError } from '../ai/errors.ts';
+import { classifyGlobalLlmError, UNPARSEABLE_RESPONSE_CODE } from '../ai/errors.ts';
import { stripReasoningBlocks } from '../llm-json.ts';
import type { ChatResult } from '../ai/gateway.ts';
import { INJECTION_PATTERNS, restoreNeutralized } from '../think/sanitize.ts';
@@ -543,7 +543,9 @@ export type ExtractFactsOutcome =
* Bounded diagnostic breadcrumb for the message: the cause's CONSTRUCTOR name
* (validated as a plain identifier — never `.name`, never `.message`) plus
* the whole-run class `classifyGlobalLlmError` derives from the cause chain
- * (`auth` / `billing` / `rate_limit` / `model_not_found`, the same vocabulary ingest_log uses).
+ * (`auth` / `billing` / `rate_limit` / `model_not_found`, the same vocabulary ingest_log uses), or instead
+ * `provider_response_unparseable` when the provider's success response could not be parsed (#9466; that class
+ * would read `auth`, which sends an operator to a valid key).
* Both are closed vocabularies with no interpolated provider text, so a 4xx
* body echoing a key / org id cannot ride through. Defense-in-depth, not a
* hard boundary: anything unexpected is dropped (never substituted), and a
@@ -557,7 +559,8 @@ function safeCauseLabel(cause: unknown): string | undefined {
const name: unknown = typeof ctor === 'function' ? ctor.name : undefined;
if (typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name)) ctorName = name;
}
- const label = [ctorName, classifyGlobalLlmError(cause)].filter(Boolean).join(' ');
+ const unparseable = (cause as { code?: unknown } | null)?.code === UNPARSEABLE_RESPONSE_CODE;
+ const label = [ctorName, unparseable ? UNPARSEABLE_RESPONSE_CODE : classifyGlobalLlmError(cause)].filter(Boolean).join(' ');
return label || undefined;
} catch {
return undefined;
diff --git a/src/core/generations/managed-retire.ts b/src/core/generations/managed-retire.ts
index 9fdbb8024c..61197da6e0 100644
--- a/src/core/generations/managed-retire.ts
+++ b/src/core/generations/managed-retire.ts
@@ -18,7 +18,7 @@ import { preparePageMutation } from '../persistence/page-prepare.ts';
import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import { waitForWrite, writeResponse } from '../persistence/service.ts';
import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
-import type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';
+import { stampDerivedRetirement, type DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';
import { generationAdapter } from './adapters/index.ts';
import type { GenerationKey } from './contract.ts';
import { assertMemberPending, GENERATION_ACTIVATE_SLUG, listPendingMembers, memberRequestId, recordActivation, settleMember,
@@ -84,8 +84,7 @@ export async function prepareGenerationRetireMember(engine: BrainEngine, row: Wr
}, apply: async tx => {
const result = await prepared.apply(tx);
if (!prepared.noop) {
- await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
- WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [p.retiredBy, new Date().toISOString(), row.page_id, row.source_id]);
+ await stampDerivedRetirement(tx, row.source_id, [row.slug], p.retiredBy);
await settleMember(tx, p.activationId, row.slug);
}
return { ...result, retired_by: p.retiredBy, activation_id: p.activationId };
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index b938ec2ab6..57c9d9186a 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -23,7 +23,7 @@ import type { WriteReceipt } from './types.ts';
import { MAX_DETERMINISTIC_FAILURES, writeAtomPageState } from '../cycle/extract-atoms-page-state.ts';
import { effectiveVisibility, withFolderRestricted } from '../search/private-visibility.ts';
import { declareDerivation, deriveTrust, lowerToDerivedTier, recordTaintEdges } from '../trust/taint.ts';
-import type { DerivedRetiredBy } from './derived-retirement-hold.ts';
+import { stampDerivedRetirement, type DerivedRetiredBy } from './derived-retirement-hold.ts';
import type { GenerationKey, HeldReason } from '../generations/contract.ts';
import { atomGenerationAdapter, atomPagePin, type AtomGenerationContext } from '../generations/adapters/atoms.ts';
import { markdownItem } from '../generations/adapters/page.ts';
@@ -751,8 +751,7 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
}, apply: async tx => {
const result = await prepared.apply(tx);
if (!prepared.noop) {
- await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
- WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [p.retiredBy ?? ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
+ await stampDerivedRetirement(tx, row.source_id, [row.slug], p.retiredBy ?? ATOM_RETIRED_BY_REEXTRACT);
if (p.activationId) await settleMember(tx, p.activationId, row.slug);
if (p.origin.kind === 'page' && p.origin.pageId !== null) {
await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash || null);
diff --git a/src/core/persistence/derived-retirement-hold.ts b/src/core/persistence/derived-retirement-hold.ts
index 22cc20e89c..cf20ae98e1 100644
--- a/src/core/persistence/derived-retirement-hold.ts
+++ b/src/core/persistence/derived-retirement-hold.ts
@@ -12,6 +12,7 @@
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { maintenanceTransaction } from './attribution.ts';
+import { withTrustKeep } from './context.ts';
import { GENERATION_BOUNDS, RESTORE_DAYS_SQL } from '../generations/config.ts';
/** The `retired_by` stamps derived writers put on the pages they retire. */
@@ -39,18 +40,23 @@ export function derivedRetirementPurgeHold(alias: string): string {
AND ${alias}.deleted_at > now() - interval '1 day' * ${RESTORE_DAYS_SQL})`;
}
-/** Stamps pages the caller soft-deleted in this transaction as retired by `retiredBy`. */
-async function stampDerivedRetirement(tx: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {
+/**
+ * Stamps pages the caller soft-deleted in this transaction as retired by `retiredBy`. A retirement authors no content, like
+ * the page delete it follows, so the stamp keeps each page's stored tier and write origin (#9456): written with no trust
+ * declaration it stored the page `unknown` with no origin, and the derived writer that later produced the page again
+ * could only keep or lower that tier, so the revived page stayed `unknown`.
+ */
+export async function stampDerivedRetirement(tx: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {
if (!slugs.length) return;
- await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
- WHERE source_id=$3 AND slug=ANY($4::text[]) AND deleted_at IS NOT NULL`, [retiredBy, new Date().toISOString(), sourceId, [...slugs]]);
+ await withTrustKeep(tx, ['pages'], () => tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+ WHERE source_id=$3 AND slug=ANY($4::text[]) AND deleted_at IS NOT NULL`, [retiredBy, new Date().toISOString(), sourceId, [...slugs]]));
}
/** Versions, soft-deletes and stamps `slugs` as retired by `retiredBy` inside the caller's attributed transaction. */
export async function retireDerivedPagesInTransaction(tx: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {
if (!slugs.length) return;
for (const slug of slugs) await tx.createVersion(slug, { sourceId });
- await tx.softDeletePages([...slugs], { sourceId });
+ await withTrustKeep(tx, ['pages'], () => tx.softDeletePages([...slugs], { sourceId }));
await stampDerivedRetirement(tx, sourceId, slugs, retiredBy);
}
diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.ts
index c700a961cd..464fc420b2 100644
--- a/src/core/repair/stale-atoms.ts
+++ b/src/core/repair/stale-atoms.ts
@@ -43,6 +43,7 @@ import { preparePageMutation } from '../persistence/page-prepare.ts';
import { bumpAtomGeneration, managedAtomCompletedSql, managedAtomSession, publishManagedAtomGeneration, type AtomOrigin } from '../persistence/atom-maintenance.ts';
import { atomGenerationAdapter, atomOwnerKey, readAtomInput } from '../generations/adapters/atoms.ts';
import { atomOriginSlugSql } from '../persistence/atom-origin.ts';
+import { stampDerivedRetirement } from '../persistence/derived-retirement-hold.ts';
import { publishGeneration } from '../generations/publish.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
@@ -209,8 +210,7 @@ async function retireStaleAtom(ctx: OperationContext, atom: StaleAtom): Promise<
}
async function stampRetirement(tx: BrainEngine, atom: StaleAtom, stamp = true): Promise<void> {
- if (stamp) await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
- WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [STALE_ATOMS_RETIRED_BY, new Date().toISOString(), atom.id, atom.source_id]);
+ if (stamp) await stampDerivedRetirement(tx, atom.source_id, [atom.slug], STALE_ATOMS_RETIRED_BY);
if (atom.origin_page_id === null) return;
const [{ incarnation }] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [atom.source_id]);
await bumpAtomGeneration(tx, atom.source_id, incarnation, atom.origin_page_id, atom.class === 'origin_changed' ? atom.origin_hash : null);
diff --git a/src/core/sync-applicability.ts b/src/core/sync-applicability.ts
index 2171f70f9f..82cd0af16c 100644
--- a/src/core/sync-applicability.ts
+++ b/src/core/sync-applicability.ts
@@ -28,6 +28,8 @@ export interface SyncContentDirectory {
sourceId: string;
root: string;
keyless: boolean;
+ /** Why gbrain owns it: the root sits inside gbrain's own content directory, or a content-setup receipt claims it. */
+ ownedBy: 'content_root' | 'receipt';
}
function canonical(path: string): string {
@@ -61,9 +63,10 @@ export async function syncContentDirectory(engine: BrainEngine, opts: { sourceId
const root = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');
if (!root || !existsSync(root) || existsSync(join(root, '.git'))) return null;
const sourceId = opts.sourceId ?? 'default';
- if (!underGbrainContent(root) && !(await ownedByContentReceipt(engine, sourceId, root))) return null;
+ const ownedBy = underGbrainContent(root) ? 'content_root' : await ownedByContentReceipt(engine, sourceId, root) ? 'receipt' : null;
+ if (!ownedBy) return null;
const keyless = loadConfig()?.embedding_disabled === true || (await engine.getConfig('embedding_disabled')) === 'true';
- return { sourceId, root, keyless };
+ return { sourceId, root, keyless, ownedBy };
} catch {
return null;
}
diff --git a/test/ai/unparseable-success-response-9466.test.ts b/test/ai/unparseable-success-response-9466.test.ts
new file mode 100644
index 0000000000..7287b2211d
--- /dev/null
+++ b/test/ai/unparseable-success-response-9466.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #9466: a provider that answers a non-streaming chat request with a success status and a body that is not one JSON
+ * document (a route that streams Server-Sent Events when `stream` is omitted) fails the same way on every call. It was
+ * classed as transient, so the job that made the call retried it and its recorded error said only
+ * `cause=AITransientError`. It is now a non-retryable configuration error with a registry code: the call is made once,
+ * the job ends on its first attempt, and the recorded text says the response could not be parsed without carrying any of
+ * the response body.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { chat, configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { AIConfigError, AITransientError, normalizeAIError } from '../../src/core/ai/errors.ts';
+import { getRecipe } from '../../src/core/ai/recipes/index.ts';
+import { FactsExtractionError } from '../../src/core/facts/extract.ts';
+import { FACTS_ABSORB_RETRY_STATE_KEY, classifyDeadFactsAbsorb, factsAbsorbWriteKey, readDeadFactsAbsorbRetry } from '../../src/core/facts/dead-absorb-retry.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { jobRefusal } from '../../src/core/minions/refusal.ts';
+
+const BODY_MARKER = 'streamed-body-text-9466';
+let server: ReturnType<typeof Bun.serve>;
+let requests = 0;
+
+beforeAll(() => {
+ server = Bun.serve({
+ port: 0,
+ hostname: '127.0.0.1',
+ fetch() {
+ requests++;
+ const chunk = { id: 'chatcmpl-stub', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: BODY_MARKER } }] };
+ return new Response(`data: ${JSON.stringify(chunk)}\n\ndata: [DONE]\n\n`, { status: 200, headers: { 'content-type': 'text/event-stream' } });
+ },
+ });
+});
+
+afterAll(() => {
+ server.stop(true);
+ resetGateway();
+});
+
+beforeEach(() => {
+ requests = 0;
+ resetGateway();
+});
+
+const model = () => `groq:${getRecipe('groq')!.touchpoints.chat!.models[0]}`;
+
+async function streamedChat(): Promise<Error> {
+ configureGateway({ chat_model: model(), env: { GROQ_API_KEY: 'stub' }, base_urls: { groq: `http://127.0.0.1:${server.port}/v1` } });
+ return chat({ model: model(), system: 'Reply.', messages: [{ role: 'user', content: 'hello' }], maxTokens: 50 }).then(
+ () => { throw new Error('chat resolved on an unparseable body'); }, (error: Error) => error);
+}
+
+describe('#9466 a success response whose body is not JSON', () => {
+ test('is one request, classed as a non-retryable configuration error that names the parse failure and no body text', async () => {
+ const error = await streamedChat();
+ expect(requests).toBe(1);
+ expect(error).toBeInstanceOf(AIConfigError);
+ expect(error).toMatchObject({ code: 'provider_response_unparseable', retryable: false });
+ expect(error.message).toContain('could not be parsed');
+ expect(error.message).not.toContain(BODY_MARKER);
+ expect((error as AIConfigError).fix).toContain('provider_chat_options');
+ });
+
+ test('a facts job that hits it is refused on its first attempt, and its recorded error says why without the body', async () => {
+ const extraction = new FactsExtractionError('provider_error', model(), await streamedChat());
+ expect(extraction.message).toContain('(cause=AIConfigError provider_response_unparseable)');
+ expect(extraction.message).not.toContain(BODY_MARKER);
+ const refusal = jobRefusal(extraction);
+ expect(refusal).toMatchObject({ code: 'provider_response_unparseable' });
+ expect(refusal!.message).not.toContain(BODY_MARKER);
+ expect(classifyDeadFactsAbsorb(extraction.message)).toBe('not_retryable');
+ });
+
+ test('a page-write job the retry set already tracks is not re-submitted once it dies on an unparseable response', async () => {
+ const key = factsAbsorbWriteKey('request-9466');
+ const extraction = new FactsExtractionError('provider_error', model(), await streamedChat());
+ const tracked = { job_id: 7, slug: 'notes/alpha', source_id: 'default', class: 'provider', first_dead_at: '2026-01-01T00:00:00.000Z',
+ resubmits: 1, last_resubmit_at: null, cleared_at: null };
+ const config: Record<string, string> = { [FACTS_ABSORB_RETRY_STATE_KEY]: JSON.stringify({ version: 1, keys: { [key]: tracked } }) };
+ const engine = {
+ getConfig: async (name: string) => config[name] ?? null,
+ setConfig: async (name: string, value: string) => { config[name] = value; },
+ executeRaw: async () => [{ id: 7, idempotency_key: key, status: 'dead', error_text: extraction.message, slug: 'notes/alpha',
+ source_id: 'default', finished_at: '2026-01-01T00:00:00.000Z' }],
+ } as unknown as BrainEngine;
+ const result = await readDeadFactsAbsorbRetry(engine);
+ expect(result.pending).toBe(0);
+ expect(result.not_retryable).toEqual([{ job_id: 7, slug: 'notes/alpha' }]);
+ });
+
+ test('a bare SDK parse error is classed the same way, and its text is not carried', () => {
+ const parse = Object.assign(new Error(`JSON parsing failed: Text: data: {"content":"${BODY_MARKER}"}.`), { name: 'AI_JSONParseError', text: `data: ${BODY_MARKER}` });
+ const error = normalizeAIError(parse, 'chat(groq:x)');
+ expect(error).toBeInstanceOf(AIConfigError);
+ expect(error).toMatchObject({ code: 'provider_response_unparseable', retryable: false });
+ expect(error.message).not.toContain(BODY_MARKER);
+ });
+
+ test('a parsed body that fails the schema, and a 5xx whose error body did not parse, stay transient', () => {
+ const schema = Object.assign(new Error('Invalid JSON response'), { name: 'AI_APICallError', statusCode: 200,
+ cause: Object.assign(new Error('Type validation failed'), { name: 'AI_TypeValidationError' }) });
+ const upstream = Object.assign(new Error('Failed to process error response'), { name: 'AI_APICallError', statusCode: 502,
+ cause: Object.assign(new Error('JSON parsing failed'), { name: 'AI_JSONParseError' }) });
+ for (const err of [schema, upstream]) expect(normalizeAIError(err, 'chat(groq:x)')).toBeInstanceOf(AITransientError);
+ });
+});
diff --git a/test/atom-retirement-keeps-trust-9456.test.ts b/test/atom-retirement-keeps-trust-9456.test.ts
new file mode 100644
index 0000000000..a68876234f
--- /dev/null
+++ b/test/atom-retirement-keeps-trust-9456.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #9456: retiring an atom authors no content, so the atom keeps the trust tier and write origin its extraction gave it,
+ * and an atom a later extraction produces again comes back at that tier. The retirement used to stamp `retired_by`
+ * with no trust declaration in force, which the tier trigger stores as `unknown` with no origin; a derived write can
+ * only keep or lower a tier, so the revived atom stayed `unknown`.
+ *
+ * Managed brain, PGLite and, with DATABASE_URL, Postgres: three extractions of one transcript, where the second no longer
+ * yields one atom (retired) and the third yields it again (revived). Unmanaged brain, PGLite: the shared retirement every
+ * derived writer uses (`retireDerivedPages`) on a page written at a derived tier. Synthetic data only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { withWriteTrust } from '../src/core/persistence/context.ts';
+import { retireDerivedPages } from '../src/core/persistence/derived-retirement-hold.ts';
+import { disposePersistenceConsumer, waitForWrites } from '../src/core/persistence/service.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const KEPT = ['Write the decision down', 'Name one owner'];
+const CYCLED = 'Close the loop on Friday';
+const EXTRACT_TIMEOUT_MS = 240_000;
+
+interface AtomTrust { slug: string; live: boolean; trust_tier: string; channel: string | null; retired_by: string | null }
+
+const cycledAtom = async (engine: BrainEngine): Promise<AtomTrust> => {
+ const rows = await engine.executeRaw<AtomTrust>(`SELECT slug, deleted_at IS NULL AS live, trust_tier, write_origin->>'channel' AS channel,
+ frontmatter->>'retired_by' AS retired_by FROM pages WHERE source_id='default' AND type='atom' AND slug LIKE '%close-the-loop-on-friday%'`);
+ expect(rows).toHaveLength(1);
+ return rows[0]!;
+};
+
+const transcript = (round: number) => `Round ${round} of the planning notes. The group agreed on how decisions get recorded and owned. `.repeat(10);
+
+async function extractRound(engine: BrainEngine, file: string, round: number, titles: string[]): Promise<void> {
+ const content = transcript(round);
+ writeFileSync(file, content);
+ const chat = async (): Promise<ChatResult> => {
+ const text = JSON.stringify(titles.map(title => ({ title, body: `${title}.`, atom_type: 'insight' })));
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ };
+ await runPhaseExtractAtoms(engine, { sourceId: 'default', _pages: [], _chat: chat, _transcripts: [{ filePath: file, content, contentHash: sha256(content) }] });
+ const pending = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id='default' AND state IN ('queued','running','recovering')");
+ if (pending.length) await waitForWrites(engine, pending, { engine: engine.kind } as GBrainConfig, 60_000);
+ await disposePersistenceConsumer(engine);
+}
+
+async function retireAndRevive(engine: BrainEngine, file: string, settle: () => Promise<void>, retiredBy: string): Promise<void> {
+ await extractRound(engine, file, 1, [...KEPT, CYCLED]);
+ await settle();
+ const extracted = await cycledAtom(engine);
+ expect(extracted).toMatchObject({ live: true, trust_tier: 'agent_written', channel: 'derive:atoms' });
+
+ await extractRound(engine, file, 2, KEPT);
+ await settle();
+ expect(await cycledAtom(engine)).toMatchObject({ live: false, retired_by: retiredBy, trust_tier: 'agent_written', channel: 'derive:atoms' });
+
+ await extractRound(engine, file, 3, [...KEPT, CYCLED]);
+ await settle();
+ expect(await cycledAtom(engine)).toMatchObject({ live: true, trust_tier: 'agent_written', channel: 'derive:atoms' });
+}
+
+describe('#9456 unmanaged derived retirement keeps the tier and origin (pglite)', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ test('a retired page and its saved version keep agent_written and the derive:atoms origin', async () => {
+ const slug = 'atoms/undated/close-the-loop-on-friday-0f0f0f';
+ await engine.transaction(tx => withWriteTrust(tx, { tier: 'agent_written', origin: { channel: 'derive:atoms' } }, () => tx.putPage(slug,
+ { type: 'atom', title: CYCLED, compiled_truth: `${CYCLED}.`, frontmatter: { type: 'atom', source_slug: 'notes/planning' } })));
+ expect(await cycledAtom(engine)).toMatchObject({ live: true, trust_tier: 'agent_written', channel: 'derive:atoms' });
+
+ await retireDerivedPages(engine, 'default', [slug], 'extract-atoms');
+ expect(await cycledAtom(engine)).toMatchObject({ live: false, retired_by: 'extract-atoms', trust_tier: 'agent_written', channel: 'derive:atoms' });
+ const versions = await engine.executeRaw<{ trust_tier: string; channel: string | null }>(
+ `SELECT v.trust_tier, v.write_origin->>'channel' AS channel FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.slug=$1`, [slug]);
+ expect(versions).toEqual([{ trust_tier: 'agent_written', channel: 'derive:atoms' }]);
+ });
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe(`#9456 managed atom retirement keeps the tier and origin (${backend})`, () => {
+ test('an atom a managed re-extraction retires stays agent_written with its origin, and comes back at agent_written', async () => {
+ await managedBrain(async ({ engine, root }) => {
+ const corpus = join(dirname(root), 'corpus-9456');
+ mkdirSync(corpus);
+ await retireAndRevive(engine, join(corpus, 'notes.md'), () => settleManagedGitEffects(engine), 'managed-reextract');
+ }, { databaseUrl });
+ }, EXTRACT_TIMEOUT_MS);
+ });
+}
diff --git a/test/doctor-sync-freshness-content-directory-9471.test.ts b/test/doctor-sync-freshness-content-directory-9471.test.ts
new file mode 100644
index 0000000000..9a38a62907
--- /dev/null
+++ b/test/doctor-sync-freshness-content-directory-9471.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #9471: a second source registered on a plain folder inside gbrain's own content directory (beside the default
+ * source's root) is one sync refuses with `sync_not_applicable`: gbrain owns that directory, there are no Git commits
+ * to sync, and the refusal names `gbrain import` instead. `gbrain sources add` writes no content-setup record for it
+ * (only `gbrain init` does, for the root it creates), so doctor's writer-owned exemption never covered it and
+ * sync_freshness failed it with "no successful sync recorded; run gbrain sync --source <id>" - a command that refuses
+ * that source. Doctor now asks the same question sync and the automatic sync schedulers ask, so the source is counted
+ * as one where sync does not apply and no sync is recommended for it. A plain folder outside the content directory is
+ * still judged, because sync imports it.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';
+import { assertSyncApplicable } from '../src/core/sync-applicability.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ home = mkdtempSync(join(tmpdir(), 'gbrain-content-dir-9471-'));
+});
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+
+async function addSource(id: string, root: string): Promise<void> {
+ mkdirSync(root, { recursive: true });
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, '{"federated":false}'::jsonb)`, [id, root]);
+}
+
+async function syncRefusal(id: string): Promise<string | null> {
+ return assertSyncApplicable(engine, { sourceId: id }).then(() => null, (error: unknown) => error instanceof OperationError ? error.code : String(error));
+}
+
+describe('#9471 a source inside gbrain\'s content directory', () => {
+ test('sync refuses it, and doctor neither fails it nor recommends that sync, locally or for a remote caller', () => inHome(async () => {
+ await addSource('hr-example', join(home, '.gbrain', 'content', 'brain-example', 'hr-example'));
+ expect(await syncRefusal('hr-example')).toBe('sync_not_applicable');
+ for (const localOnly of [true, false]) {
+ const check = await checkSyncFreshness(engine, { localOnly, sourceIds: ['hr-example'] });
+ expect(check.status).toBe('ok');
+ expect(check.message).not.toContain('gbrain sync');
+ expect(check.message).toContain('gbrain import <dir> --source hr-example');
+ expect(check.fix).toBeUndefined();
+ expect(check.details).toMatchObject({ stale_count: 0, content_directory_count: 1 });
+ }
+ }));
+
+ test('a plain folder outside the content directory is still judged, and sync applies to it', () => inHome(async () => {
+ await addSource('notes-example', join(home, 'notes-example'));
+ expect(await syncRefusal('notes-example')).toBeNull();
+ const check = await checkSyncFreshness(engine, { localOnly: true, sourceIds: ['notes-example'] });
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('gbrain sync --source notes-example');
+ expect(check.details).toMatchObject({ stale_count: 1 });
+ }));
+});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index f1a8af4b71..27b7ec6d11 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6875,7 +6875,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"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\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"archive_audience_unproven\" | \"archive_gateway_unreachable\" | \"archive_gateway_auth\" | \"archive_gateway_failed\" | \"archive_owner_unset\" | \"archive_redaction_failed\" | \"archive_run_busy\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"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\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"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_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"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\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"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\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"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_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"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\" | \"grant_scope\" | \"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_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"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\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"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\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"purge_replay_incomplete\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"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\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"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\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"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\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"archive_audience_unproven\" | \"archive_gateway_unreachable\" | \"archive_gateway_auth\" | \"archive_gateway_failed\" | \"archive_owner_unset\" | \"archive_redaction_failed\" | \"archive_run_busy\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"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\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"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_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"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\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"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\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"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_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"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\" | \"grant_scope\" | \"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_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"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\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"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\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"provider_response_unparseable\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"purge_replay_incomplete\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"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\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"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",
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 786a457bab..f839b0c171 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -43,6 +43,7 @@ test/access-writes.test.ts
test/activation-unbound-rooted-6449.test.ts
test/adopt-local-edit.test.ts
test/alias-source-cascade-5094.test.ts
+test/atom-retirement-keeps-trust-9456.test.ts
test/attribution-backfill-history.test.ts
test/backlinks-type-exists-gbra449.test.ts
test/backstop-same-page-shadow-managed-6333.test.ts
diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.ts
index 35b054e430..bd6f76b19e 100644
--- a/test/trust-write-gate-drift.test.ts
+++ b/test/trust-write-gate-drift.test.ts
@@ -56,7 +56,6 @@ const EXEMPT: Record<string, string> = {
'src/core/repair/agent-session-facts.ts': 'owner repair of existing rows',
'src/core/repair/consolidate-ties.ts': 'owner repair reopening the validity of existing facts (lifecycle)',
'src/core/repair/duplicate-facts.ts': 'owner repair behind a preview hash: supersedes exact copies of an existing fact with its oldest row (expired_at, superseded_by; lifecycle, no new text); fenced copies are struck through put_page, which runs the gate',
- 'src/core/generations/managed-retire.ts': 'versioned delete of a synthesis output a managed generation retires, plus its retired_by/retired_at stamp (lifecycle); no new text',
'src/core/generations/adapters/extracted-facts.ts': 'callers gate first and pass only rows the gate inserts or flags (the conversation lane and the backstop decide in conversation-publication.ts and backstop.ts); restore puts back a row\'s own recorded state',
'src/core/generations/adapters/fact-rows.ts': 'generation restore puts back a fact row\'s own recorded before-state (lifecycle); no new text',
'src/core/repair/fact-claim-dates.ts': 'owner repair moving the valid_from of existing database-only facts to the date their claim states (lifecycle)',
@@ -72,7 +71,6 @@ const EXEMPT: Record<string, string> = {
'src/core/repair/ghost-pages.ts': 'retires an owner-approved ghost page (version + soft delete, lifecycle); no new text',
'src/core/repair/moved-pages.ts': 'owner repair behind a preview hash: folds a page whose file provably moved into the moved page (twin merge of stored rows, its versions re-pointed, then soft delete); no new text',
'src/core/repair/ontology-facts.ts': 'owner repair restoring existing ontology rows',
- 'src/core/repair/stale-atoms.ts': 'retires stale atoms (lifecycle)',
'src/core/persistence/derived-retirement-hold.ts': 'versions, soft-deletes and stamps derived pages a writer retires (lifecycle); writes no content',
'src/core/repair/atoms-restore.ts': 'restores an owner-approved retired atom to its own earlier version (lifecycle); no new text',
'src/core/repair/take-supersession.ts': 'owner repair of take supersession pointers',
@@ -97,7 +95,6 @@ const EXEMPT: Record<string, string> = {
'src/core/facts/fence-write.ts': 'callers decide the gate (backstop, loops-extract) and pass the decision; it records the flag receipt on the new row',
'src/core/facts/write-single.ts': 'callers gate first (loops-extract decides; remember gates in memory-prepare); it records a passed decision\'s flag receipt',
'src/core/output/writer.ts': 'gbrain integrity auto-repair (owner-run local CLI) rewrites citations and back-links of existing pages',
- 'src/core/persistence/atom-maintenance.ts': 'pending: the managed atom page carries intent.derivation; the page gate runs in page-prepare once it reads that declaration',
'src/core/persistence/prepared-maintenance.ts': 'consolidation takes gate in takes-prepare; pending: derived maintenance pages carry intent.derivation for the page-prepare gate',
};