Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts,persistence): fence step counts only submitting pages; /metrics aggregate cache; older-build spike attribution (#6650)
garrytan4e499d25a7e3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 82878081e2..0787ff3b24 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.219.0] - 2026-10-14++**Writes that ended without committing are now summarized and explained, and the few that block work are named (#6650).** Every write leaves a receipt, and receipts that ended `failed`, `conflict` or `cancelled` used to pile up with no summary: an agent couldn't tell the one that holds a root from hundreds a later write already superseded or an older build left behind. gbrain now classifies each such receipt at read time (category, class, safe actions, whether a person decides, a structured fix) and stores nothing new. A new doctor check, `persistence_terminal_failures`, warns when a receipt blocks work now (a publication recovery record or a sync checkpoint blocker) or when an unresolved receipt is a gbrain-defect class. A 24-hour spike warns only when nothing else does, and a spike written by builds older than the fix says so, names the build and points at the write owner to upgrade or restart. Superseded rows and rows from builds older than their fixing release count as historical and never warn.++### Itemized changes++- **Classifier** (`src/core/persistence/terminal-classify.ts`): `classifyTerminal` routes each receipt by its recovery record, its typed knock-on marker, and the origin or cause it recorded. A receipt whose code and origin don't say what happened is `diagnosis_required`, and its fix is read-only writer status, never a guess. It also owns the supersession rule `gbrain repair failed-writes` uses.+- **Bounded readers** (`src/core/persistence/terminal-failures.ts`): one set-based aggregate with a 5 s statement deadline and a 2 s connection deadline; past either the result is `unknown`, never an empty pile. The drill-down scans at most 2,000 receipts per call and pages with a cursor. Thresholds: `persistence.terminal_failures.window_days` (default 7, clamped to `persistence.receipt_retention_days`), `spike_factor` (3) and `spike_min` (25).+- **`gbrain write-request <id>`** adds `write_error_reason`, `suggestion` and a `diagnosis` with a rendered `fix` for such receipts.+- **`gbrain sync status`** adds `terminal_failures` (active blockers, unresolved, historical, the drill-down command) and names a recovery record as `next` when nothing else is.+- **`gbrain sources writer failures <source>`** (read-only) lists the receipts or groups them (`--group-by category`), each group with an exact drill-down filter; a table by default, JSON with `--json`. A resident owner advertises the operation in a new `administration_extensions` capability key, so older clients and owners interoperate.+- **`/metrics`** (admin only) adds per-source gauges `gbrain_writer_terminal_failures_{active_blockers,unresolved,historical,new_24h,defects}` and `_known`, from one aggregate shared by every scrape for 60 s. `/health` is unchanged.+- **Fact-fence step** (`src/core/facts/unfenced-facts.ts`): the up-front lifetime-ID check counts only pages that will submit, so a page suppressed by a recent identical refusal, or one with nothing adoptable, no longer pushes the whole step to the cap and refuses it.+- Docs: [terminal write failures](docs/guides/troubleshooting.md#terminal-write-failures), the troubleshooting row, write-refusals and the maintain skill.+## [0.60.218.0] - 2026-10-14**Fencing legacy facts no longer leaks, loops or blocks.** When a legacy fact is adopted into a fence row that an earlier, interrupted run left behind, the row is now rebuilt from the stored fact, so the fact's own kind, dates, confidence, visibility and speaker attribution are kept. Before, a leftover row with a different visibility made the adoption refuse every time, and one with the same visibility overwrote the fact's metadata. A managed adoption that gbrain refused as a planning defect is no longer resubmitted every cycle, so the writer stops collecting one identical failed request per page per cycle. And one fact that can't be fenced now holds up only its own page: the phantom-redirect pass runs for the rest of the source.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 5f701e3e8b..135d3fc00a 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -25,7 +25,7 @@- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them).-- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.+- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).- `src/core/cycle/connector-extract.ts` — the extract phase of a cycle with no on-disk checkout (connector sources, Postgres brains without `--dir`; #5875): `runPhaseExtractDatabaseOnly` runs the bounded, source-scoped `extractStaleFromDB` drain (`CYCLE_STALE_DRAIN_BUDGET_MS`; brain-wide when the cycle has no source id; managed brains route to `extractManagedStaleLinks`) and reports `extract: ok` with `database_only: true` and the stale counters; a dry run reports `skipped`. Tests: `test/connector-cycle-extract.test.ts` (+ Postgres twin), no `runCycle` mock.diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 48b7cabc55..e44bba4ede 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -21,5 +21,5 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/sync-knock-on.ts` — #6643: a sync page request that ended without committing only because another request of its sync did not commit (a knock-on). Cancellers stamp `error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }` (survives compaction); pre-#6643 receipts match only their producers' exact messages (`LEGACY_KNOCK_ON_CANCEL_MESSAGES`, the never-admitted patterns, `EARLIER_PAGE_REFUSAL_MESSAGE`), never an operator cancel. `isSyncKnockOn` and `syncKnockOnSql` are one predicate (the SQL is never NULL, so `NOT` of it is safe in clause 3). `cursorFenceCause` reads the three causes of "cursor changed" (`run_replaced`, `window_dropped` only for a request the cursor recorded in `Cursor.dropped`, else `outside_fence`). `sync-run.ts` `recoverKnockOn` re-freezes the entry through `holdUnderGate` (budgets `sync.knock_on_refreeze_limit` per index, `sync.knock_on_run_limit` per invocation; past them `knock_on_exhausted` with `root_cause`), `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end, and `checkpoint-validation.ts` skips knock-ons of pre-#6643 cursors and the cursor's settled index ranges. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`).- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included).-- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`; never `/health`). Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.+- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 0cde5d3667..5cd5d815e0 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -194,7 +194,7 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries.- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.-A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.+A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.```bashgbrain doctor --only persistence_terminal_failures --json # blockers, unresolved, historical, the fix@@ -204,7 +204,7 @@ gbrain sources writer failures <id> --category owner_exception --code storage_ergbrain write-request <request> --json # one receipt: write_error_reason, suggestion, diagnosis.fix```-All five are read-only. `sources writer failures` prints a table, or one JSON document with `--json`; a full page ends with `truncated` and the exact next command (`--before <cursor>`), and `--state all` adds the resolved and historical rows. A receipt whose code and origin do not say what happened (most often an old `storage_error` compacted without its message) is `diagnosis_required`: its fix is the read-only `gbrain sources writer status --source <id> --json`, and nothing is guessed. With `gbrain serve --http`, the admin-only `/metrics` carries the same counts per source (`gbrain_writer_terminal_failures_active_blockers`, `_unresolved`, `_historical`, `_new_24h`, `_defects`, and `_known 0` when the read timed out); the public `/health` never does. To tune the thresholds:+All five are read-only. `sources writer failures` prints a table, or one JSON document with `--json`; a full page ends with `truncated` and the exact next command (`--before <cursor>`), and `--state all` adds the resolved and historical rows. A receipt whose code and origin do not say what happened (most often an old `storage_error` compacted without its message) is `diagnosis_required`: its fix is the read-only `gbrain sources writer status --source <id> --json`, and nothing is guessed. With `gbrain serve --http`, the admin-only `/metrics` carries the same counts per source (`gbrain_writer_terminal_failures_active_blockers`, `_unresolved`, `_historical`, `_new_24h`, `_defects`, and `_known 0` when the read timed out), from one aggregate shared by every scrape for 60 s; the public `/health` never does. To tune the thresholds:```bashgbrain config set persistence.terminal_failures.window_days 14diff --git a/llms-full.txt b/llms-full.txtindex 2dd7cce0a2..d652b39b1c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10347,7 +10347,7 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries.- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.-A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.+A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.```bashgbrain doctor --only persistence_terminal_failures --json # blockers, unresolved, historical, the fix@@ -10357,7 +10357,7 @@ gbrain sources writer failures <id> --category owner_exception --code storage_ergbrain write-request <request> --json # one receipt: write_error_reason, suggestion, diagnosis.fix```-All five are read-only. `sources writer failures` prints a table, or one JSON document with `--json`; a full page ends with `truncated` and the exact next command (`--before <cursor>`), and `--state all` adds the resolved and historical rows. A receipt whose code and origin do not say what happened (most often an old `storage_error` compacted without its message) is `diagnosis_required`: its fix is the read-only `gbrain sources writer status --source <id> --json`, and nothing is guessed. With `gbrain serve --http`, the admin-only `/metrics` carries the same counts per source (`gbrain_writer_terminal_failures_active_blockers`, `_unresolved`, `_historical`, `_new_24h`, `_defects`, and `_known 0` when the read timed out); the public `/health` never does. To tune the thresholds:+All five are read-only. `sources writer failures` prints a table, or one JSON document with `--json`; a full page ends with `truncated` and the exact next command (`--before <cursor>`), and `--state all` adds the resolved and historical rows. A receipt whose code and origin do not say what happened (most often an old `storage_error` compacted without its message) is `diagnosis_required`: its fix is the read-only `gbrain sources writer status --source <id> --json`, and nothing is guessed. With `gbrain serve --http`, the admin-only `/metrics` carries the same counts per source (`gbrain_writer_terminal_failures_active_blockers`, `_unresolved`, `_historical`, `_new_24h`, `_defects`, and `_known 0` when the read timed out), from one aggregate shared by every scrape for 60 s; the public `/health` never does. To tune the thresholds:```bashgbrain config set persistence.terminal_failures.window_days 14diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.tsindex 608712c965..8c6fc73aa5 100644--- a/src/commands/doctor/checks/persistence-requests.ts+++ b/src/commands/doctor/checks/persistence-requests.ts@@ -287,6 +287,16 @@ export async function terminalFailuresCheck(engine: BrainEngine | null, sourceIdconst drill = (sourceId: string) => ['gbrain', 'sources', 'writer', 'failures', sourceId, '--group-by', 'category', '--json'];if (spike) {const busiest = [...sources].sort((a, b) => b.new_last_24h - a.new_last_24h)[0]!;+ // Rows a build older than their class's fix wrote are an old owner still running, not a new defect: say so and name it.+ const older = sources.reduce((n, s) => n + s.new_last_24h_older_builds.rows, 0);+ if (older * 2 > last24h) {+ const builds = [...new Set(sources.flatMap(s => s.new_last_24h_older_builds.builds))].sort();+ const owner = [...sources].sort((a, b) => b.new_last_24h_older_builds.rows - a.new_last_24h_older_builds.rows)[0]!.source_id;+ return { name, status: 'warn', details: { ...details, spike: { ...details.spike, older_builds: { rows: older, builds } } },+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', owner, '--json'], 'Read-only: names the write owner of the source, its process and the gbrain version it runs.', name, { docs }),+ message: `${last24h} write receipt(s) ended without committing in the last 24 h, above ${thresholds.spikeFactor}× the 7-day median (${sevenDayMedian(daily)}/day), but ${older} of them `+ + `were written by gbrain ${builds.join(', ') || 'an older build'}, older than the release that fixed their class: an older write owner is still producing these; upgrade or restart it. ${counts}.` };+ }return { name, status: 'warn', details,fix: agentFix(drill(busiest.source_id), 'Read-only: groups the source\'s unresolved receipts by code, origin and category, each with its fix and drill-down filter.', name, { docs }),message: `${last24h} write receipt(s) ended without committing in the last 24 h, above ${thresholds.spikeFactor}× the 7-day median (${sevenDayMedian(daily)}/day; `diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.tsindex c32e7da305..8b029c5a5d 100644--- a/src/commands/serve-http-metrics.ts+++ b/src/commands/serve-http-metrics.ts@@ -102,6 +102,25 @@ export function renderTerminalFailureMetrics(summary: TerminalSummary): string {return lines.join('\n');}+/** #6650: how long one terminal-failure aggregate serves /metrics scrapes (a 15 s scrape cadence runs the query once a minute). */+export const TERMINAL_METRICS_TTL_MS = 60_000;+const terminalSummaries = new WeakMap<BrainEngine, { at: number; summary: Promise<TerminalSummary> }>();++/**+ * The aggregate for /metrics, shared by every scrape within `TERMINAL_METRICS_TTL_MS` (in flight included). One query covers+ * every source, so the cache is the whole summary per engine; an `unknown` result is cached too, so a database that is+ * timing out is not asked again on every scrape.+ */+export function cachedTerminalSummary(engine: BrainEngine, now: number = Date.now()): Promise<TerminalSummary> {+ const hit = terminalSummaries.get(engine);+ if (hit && now - hit.at < TERMINAL_METRICS_TTL_MS) return hit.summary;+ const summary = readCheckpointBlockerMap(engine)+ .then(checkpointBlockers => readTerminalFailureSummary(engine, { checkpointBlockers }))+ .catch((error): TerminalSummary => ({ status: 'unknown', window_days: 0, reason: error instanceof Error ? error.message : String(error) }));+ terminalSummaries.set(engine, { at: now, summary });+ return summary;+}+export function renderPrometheusMetrics(counters: MetricsCounters,now: number = Date.now(),@@ -347,9 +366,7 @@ export function mountMetrics(app: Express, ctx: ServeHttpContext): void {// request/error/latency series profile a personal brain's usage, so this// is not a public surface (the original PR served it unauthenticated).app.get('/metrics', requireAdmin, async (_req: Request, res: Response) => {- const summary: TerminalSummary = await readCheckpointBlockerMap(ctx.engine)- .then(checkpointBlockers => readTerminalFailureSummary(ctx.engine, { checkpointBlockers }))- .catch(error => ({ status: 'unknown' as const, window_days: 0, reason: error instanceof Error ? error.message : String(error) }));+ const summary = await cachedTerminalSummary(ctx.engine);res.set('Content-Type', 'text/plain; version=0.0.4');res.send(renderPrometheusMetrics(metricsCounters) + renderTerminalFailureMetrics(summary));});diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ff2f3dcc87..e96c7490a8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -551,7 +551,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.218.0', text: 'A managed fact-fence adoption refused as a planning defect (`fence_unrenderable`) is no longer resubmitted every cycle: for a day after the refusal the page is reported as unadoptable (`prior_refusal`), then it gets one more try, or right away once the adoption planner changes. The writer stops collecting one identical failed request per page per cycle.' },{ since: '0.60.218.0', text: 'The `extract_facts` phantom-redirect pass no longer waits for the whole source to have no unfenced legacy fact rows: it holds only the top-level pages that own such rows or are the provenance page of an ontology observation (`phantoms_held_legacy_rows` in the cycle report), and redirects the rest.' },// #6650 (writer terminal-state visibility). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.- { since: '0.60.218.0', text: 'Writes that ended `failed`, `conflict` or `cancelled` are now summarized instead of only piling up as receipts. A new doctor check, `persistence_terminal_failures`, warns when a receipt blocks work now (a publication recovery record or a sync checkpoint blocker) or when an unresolved receipt is a gbrain-defect class, and on a 24-hour spike only secondarily (`persistence.terminal_failures.window_days`, `spike_factor`, `spike_min`; defaults 7, 3, 25); rows a later write superseded, or from a build older than the release that fixed their cause, count as historical and never warn. `gbrain sync status` adds `terminal_failures` and names a recovery record as `next` when nothing else is. `gbrain write-request` adds `write_error_reason`, `suggestion` and a `diagnosis` with a structured fix for such receipts. New read-only `gbrain sources writer failures <source>` lists or groups them (`--group-by category`). The admin-only `/metrics` adds per-source counts; `/health` does not change. Nothing new is stored.' },+ { since: '0.60.218.0', text: 'Writes that ended `failed`, `conflict` or `cancelled` are now summarized instead of only piling up as receipts. A new doctor check, `persistence_terminal_failures`, warns when a receipt blocks work now (a publication recovery record or a sync checkpoint blocker) or when an unresolved receipt is a gbrain-defect class, and on a 24-hour spike only secondarily, naming the build when an older write owner is producing them (`persistence.terminal_failures.window_days`, `spike_factor`, `spike_min`; defaults 7, 3, 25); rows a later write superseded, or from a build older than the release that fixed their cause, count as historical and never warn. `gbrain sync status` adds `terminal_failures` and names a recovery record as `next` when nothing else is. `gbrain write-request` adds `write_error_reason`, `suggestion` and a `diagnosis` with a structured fix for such receipts. New read-only `gbrain sources writer failures <source>` lists or groups them (`--group-by category`). The admin-only `/metrics` adds per-source counts; `/health` does not change. Nothing new is stored.' },+ { since: '0.60.218.0', text: 'The managed fact-fence step (`extract_facts`, the v0.32.2 adoption) now checks the permanent request-ID caps against only the pages that will submit an adoption. A page suppressed by an identical refusal in the last day, or one with nothing adoptable, no longer counts, so it can no longer push the whole step to the cap and get it refused.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex f71b27f79e..b6af635f62 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -373,6 +373,31 @@ function recordUnadoptable(outcome: UnfencedFactsOutcome, slug: string, records:outcome.failed_pages.push(unadoptableRowsToken(slug, records));}+/** One managed page, planned read-only: what the adoption would do with it right now. */+type ManagedPagePlan =+ | { kind: 'no_page' }+ | { kind: 'warnings'; warnings: string[] }+ | { kind: 'unadoptable'; records: UnadoptableFactRecord[] }+ | { kind: 'submit'; snapshot: NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>; fence: { body: string; assignments: Array<{ id: string; row_num: number }>; rejected: UnadoptableFactRecord[] };+ request: Extract<Awaited<ReturnType<typeof planFactFenceAdoption>>, { kind: 'submit' }> };++async function planManagedPage(engine: BrainEngine, authority: MaintenanceAuthority, sourceId: string, entitySlug: string, group: UnfencedFactRow[]): Promise<ManagedPagePlan> {+ const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });+ if (!snapshot) return { kind: 'no_page' };+ const fence = await planFence(engine, sourceId, entitySlug, serializePageToMarkdown(snapshot.page, snapshot.tags), group);+ if ('warnings' in fence) return { kind: 'warnings', warnings: fence.warnings };+ if (fence.assignments.length === 0) return { kind: 'unadoptable', records: fence.rejected };+ const request = await planFactFenceAdoption(engine, authority, entitySlug, {+ content: fence.body, expectedRevision: snapshot.revision,+ assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })),+ });+ if (request.kind === 'suppressed') {+ return { kind: 'unadoptable', records: [...fence.rejected, ...fence.assignments.map(a => ({ source_id: sourceId, slug: entitySlug,+ fact_id: Number(a.id), reason: 'fence_unrenderable' as const, class: 'prior_refusal' as const, request_id: request.prior.request_id }))] };+ }+ return { kind: 'submit', snapshot, fence, request };+}+/*** Managed brains (#5728 class): the managed writer guard refuses direct fence* writes into the canonical worktree and any raw `UPDATE facts`. Each page@@ -388,31 +413,30 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promiconst sourceId = key.split('\0')[0];if (!authorities.has(sourceId)) authorities.set(sourceId, (await maintenancePreflight(engine, sourceId))!);}- // One admission per page: refuse up front, before any page publishes,- // when the permanent request-ID caps cannot cover them all.+ // One admission per page that will submit: refuse up front, before any page publishes, when the permanent+ // request-ID caps cannot cover them. A read-only pre-pass counts them, so a page that is suppressed (an+ // identical adoption was refused within the day), unadoptable or gone never pushes the step over the cap.+ // The submit loop below plans each page again right before it submits, so the plan it publishes is never+ // older than its own read (the facts-changed-since-planning guard keeps its short window).const [first] = authorities.values();- if (first) await assertLifetimeIdHeadroom(engine, first.writer.principal, groups.size);+ if (first) {+ let submitting = 0;+ for (const [key, group] of groups) {+ const [sourceId, entitySlug] = key.split('\0');+ try { if ((await planManagedPage(engine, authorities.get(sourceId)!, sourceId, entitySlug, group)).kind === 'submit') submitting++; }+ catch { submitting++; }+ }+ await assertLifetimeIdHeadroom(engine, first.writer.principal, submitting);+ }for (const [key, group] of groups) {const [sourceId, entitySlug] = key.split('\0');try {const authority = authorities.get(sourceId)!;- const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });- if (!snapshot) { outcome.skipped_no_page += group.length; continue; }- const fence = await planFence(engine, sourceId, entitySlug, serializePageToMarkdown(snapshot.page, snapshot.tags), group);- if ('warnings' in fence) {- outcome.failed_pages.push(`${entitySlug} (${fence.warnings.join('; ')})`);- continue;- }- if (fence.assignments.length === 0) { recordUnadoptable(outcome, entitySlug, fence.rejected); continue; }- const request = await planFactFenceAdoption(engine, authority, entitySlug, {- content: fence.body, expectedRevision: snapshot.revision,- assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })),- });- if (request.kind === 'suppressed') {- recordUnadoptable(outcome, entitySlug, [...fence.rejected, ...fence.assignments.map(a => ({ source_id: sourceId, slug: entitySlug,- fact_id: Number(a.id), reason: 'fence_unrenderable' as const, class: 'prior_refusal' as const, request_id: request.prior.request_id }))]);- continue;- }+ const page = await planManagedPage(engine, authority, sourceId, entitySlug, group);+ if (page.kind === 'no_page') { outcome.skipped_no_page += group.length; continue; }+ if (page.kind === 'warnings') { outcome.failed_pages.push(`${entitySlug} (${page.warnings.join('; ')})`); continue; }+ if (page.kind === 'unadoptable') { recordUnadoptable(outcome, entitySlug, page.records); continue; }+ const { snapshot, fence, request } = page;if (factsChangedSincePlanning(fence.body, fence.assignments, request.facts)) {outcome.failed_pages.push(`${entitySlug} (a legacy fact changed after its fence row was planned; nothing was submitted and the next run replans it)`);continue;diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.tsindex effec8694f..6b4650926a 100644--- a/src/core/persistence/terminal-failures.ts+++ b/src/core/persistence/terminal-failures.ts@@ -107,6 +107,8 @@ export interface TerminalSourceSummary {unresolved: { rows: number; distinct_slugs: number; distinct_intents: number; oldest_at: string | null; oldest_age_seconds: number | null };historical_rows: number;new_last_24h: number;+ /** Of `new_last_24h`, the receipts a build older than its class's fixing release wrote (`TERMINAL_FIXED_IN`), by build. */+ new_last_24h_older_builds: { rows: number; builds: string[] };daily_7d: number[];defects: Array<{ category: TerminalCategory; code: string; origin: string | null; rows: number; human_reason?: string; action: Action }>;categories: Array<{ category: TerminalCategory; code: string; origin: string | null; rows: number; unresolved: number; historical: number; class: string; needs_human: boolean }>;@@ -156,7 +158,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { soconst summaryOf = (sourceId: string) => {let s = bySource.get(sourceId);if (!s) bySource.set(sourceId, s = { source_id: sourceId, active_blockers: [], unresolved: { rows: 0, distinct_slugs: 0, distinct_intents: 0, oldest_at: null, oldest_age_seconds: null },- historical_rows: 0, new_last_24h: 0, daily_7d: [0, 0, 0, 0, 0, 0, 0], defects: [], categories: [] });+ historical_rows: 0, new_last_24h: 0, new_last_24h_older_builds: { rows: 0, builds: [] }, daily_7d: [0, 0, 0, 0, 0, 0, 0], defects: [], categories: [] });return s;};// Per-group oldest unresolved: the GROUPING SETS total row's oldest covers every row, so the unresolved one is taken from groups.@@ -170,6 +172,10 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so}const verdict = verdictOf(row);const n = Number(row.rows);+ if (verdict.historical && Number(row.n_24h) > 0) {+ s.new_last_24h_older_builds.rows += Number(row.n_24h);+ if (row.build && !s.new_last_24h_older_builds.builds.includes(row.build)) s.new_last_24h_older_builds.builds.push(row.build);+ }if (row.has_recovery) {(row.recovery_ids ?? []).forEach((id, i) => {const v = verdictOf({ ...row, request_id: id, slug: row.recovery_slugs?.[i] });diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.tsindex 54746edc0e..459b6731b1 100644--- a/test/fact-fence-adoption-exits.test.ts+++ b/test/fact-fence-adoption-exits.test.ts@@ -10,6 +10,8 @@* - A deterministic refusal of the same intent is not resubmitted within a* day, so cycles stop minting identical failed requests; a day later, or a* changed adoption planner, retries once.+ * - A suppressed page does not count against the request-ID cap: only pages+ * that will submit are checked before the fence step admits anything.* - One unadoptable legacy row no longer stops the phantom-redirect pass for* the whole source; only a phantom that owns legacy rows is held.* Seams: planFence against an engine stub, the managed-brain helper for the@@ -24,7 +26,8 @@ import { fenceCellReadBackProblem, parseFactsFence, renderFactsTable, replaceOrIimport { fenceUnfencedFacts, planFence, planUnfencedFacts, type UnfencedFactRow } from '../src/core/facts/unfenced-facts.ts';import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';-import { FACT_FENCE_PLANNER, maintenancePreflight, submitFactFenceAdoption } from '../src/core/persistence/prepared-maintenance.ts';+import { FACT_FENCE_PLANNER, maintenancePreflight, planFactFenceAdoption, submitFactFenceAdoption } from '../src/core/persistence/prepared-maintenance.ts';+import { principalKey } from '../src/core/persistence/model.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { managedBrain } from './helpers/managed-brain.ts';@@ -127,6 +130,43 @@ for (const backend of testBackends()) {}, { databaseUrl, setup: async ({ engine, root }) => { seed = await seedLegacyManagedContent(engine, root); } });}, 120_000);+ test(`${backend}: a suppressed page does not count against the request-ID cap, so it never refuses the fence step`, async () => {+ await managedBrain(async ({ engine }) => {+ const plan = await planUnfencedFacts(engine, { sourceId: 'default' });+ for (const key of [...plan.groups.keys()]) if (key !== `default\0${LEGACY_FILE_SLUG}`) plan.groups.delete(key);+ const group = plan.groups.get(`default\0${LEGACY_FILE_SLUG}`)!;+ const authority = (await maintenancePreflight(engine, 'default'))!;+ const snapshot = (await engine.readPageSnapshot(LEGACY_FILE_SLUG, { sourceId: 'default' }))!;+ const fence = await planFence(engine, 'default', LEGACY_FILE_SLUG, serializePageToMarkdown(snapshot.page, snapshot.tags), group);+ if ('warnings' in fence) throw new Error(fence.warnings.join('; '));+ const planned = await planFactFenceAdoption(engine, authority, LEGACY_FILE_SLUG, { content: fence.body, expectedRevision: snapshot.revision,+ assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })) });+ if (planned.kind !== 'submit') throw new Error('expected a fresh plan');+ const principal = authority.writer.principal;+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ // The identical adoption was refused as a planning defect an hour ago, and the principal sits exactly at its lifetime-ID cap.+ await tx.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,+ terminal_reservation,state,error_code,error_message,completed_at,updated_at)+ VALUES($1,$2,$3::uuid,'submit_job','default',(SELECT incarnation FROM sources WHERE id='default'),$4,'refused','{}'::jsonb,0,0,'failed','fence_unrenderable',+ 'The adopted fence row does not render its legacy fact.',now()-interval '1 hour',now()-interval '1 hour')`,+ [principal.kind, principal.id, planned.requestId, LEGACY_FILE_SLUG]);+ await tx.executeRaw(`INSERT INTO persistence_counters(key) VALUES($1) ON CONFLICT DO NOTHING`, [principalKey(principal)]);+ await tx.executeRaw(`UPDATE persistence_counters SET lifetime_ids=1000 WHERE key=$1`, [principalKey(principal)]);+ });+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ const outcome = await fenceUnfencedFacts(engine, plan);+ expect(outcome.unadoptable_rows.filter(r => r.slug === LEGACY_FILE_SLUG && r.class === 'prior_refusal').length).toBe(fence.assignments.length);+ expect(outcome.fenced).toBe(0);+ // A page that would submit still needs its ID: the same cap refuses once the refusal no longer suppresses it.+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_requests SET completed_at=now()-interval '25 hours' WHERE request_id=$1::uuid`, [planned.requestId]);+ });+ await expect(fenceUnfencedFacts(engine, await planUnfencedFacts(engine, { sourceId: 'default' }))).rejects.toMatchObject({ code: 'queue_capacity' });+ }, { databaseUrl, setup: async ({ engine, root }) => { await seedLegacyManagedContent(engine, root); } });+ }, 120_000);+test(`${backend}: a legacy fact that changes after planning is not overwritten by the older plan`, async () => {let seed!: LegacySeed;await managedBrain(async ({ engine }) => {diff --git a/test/sync-status-terminal-6650.test.ts b/test/sync-status-terminal-6650.test.tsindex 8f1eff645b..2817f106e6 100644--- a/test/sync-status-terminal-6650.test.ts+++ b/test/sync-status-terminal-6650.test.ts@@ -4,7 +4,8 @@* Protects: the status carries `terminal_failures` (active blockers apart from the unresolved pile and the historical* rows, with the drill-down command); a receipt still holding a recovery record is an active blocker and becomes* `next` when nothing else is; the human output prints the counts, each BLOCKING receipt and the drill-down; another- * source's receipts never leak in. PGLite in-memory.+ * source's receipts never leak in. A managed-sync cursor waiting at its checkpoint step behind a failed page receipt+ * is an active blocker in the aggregate, in doctor and in sync status. PGLite in-memory.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -12,6 +13,15 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { runSyncStatus } from '../src/commands/sync/operator.ts';import { withEnv } from './helpers/with-env.ts';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { readCheckpointBlockerMap, readTerminalFailureSummary } from '../src/core/persistence/terminal-failures.ts';+import { terminalFailuresCheck } from '../src/commands/doctor/checks/persistence-requests.ts';const SOURCE = 'status-src';const OTHER = 'status-other';@@ -79,3 +89,56 @@ describe('sync status terminal_failures', () => {expect(out).not.toContain('notes/elsewhere');});});++describe('a cursor waiting at its checkpoint step', () => {+ const MANAGED = 'status-managed';+ test('its blocking receipt is an active checkpoint blocker in the aggregate, doctor and sync status', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6650-checkpoint-'));+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {+ const root = join(home, MANAGED);+ mkdirSync(root);+ execFileSync('git', ['-C', root, 'init', '-q']);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [MANAGED, root]);+ await claimWorktree(engine, MANAGED, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const binding = (await getWorktreeBinding(engine, MANAGED))!;+ const runId = randomUUID(), blocker = randomUUID();+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ // Page 2 of the run failed and nothing committed at its index, so the run's checkpoint cannot commit.+ await tx.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,+ terminal_reservation,state,error_code,error_message,error_detail,intent,completed_at,updated_at,admitter_version,worktree_id)+ VALUES('local_cli','fixture',$1::uuid,'submit_job',$2,(SELECT incarnation FROM sources WHERE id=$2),'notes/two',$3,'{}'::jsonb,0,0,'failed','storage_error','x',+ '{"origin":"owner_exception"}'::jsonb,$4::text::jsonb,now()-interval '1 hour',now()-interval '1 hour','0.60.218.0',$5::uuid)`,+ [blocker, MANAGED, randomUUID(), JSON.stringify({ kind: 'managed_sync_import', runId, index: 2 }), binding.worktree_id]);+ });+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [MANAGED]);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`, [`fp-${runId}`, JSON.stringify([{+ runId, sourceId: MANAGED, incarnation: source!.incarnation, index: 3, total: 3, target: 'a'.repeat(40), binding: { worktree_id: binding.worktree_id },+ pending: { requestId: randomUUID(), intent: { kind: 'managed_sync_checkpoint' } } }])]);++ const map = await readCheckpointBlockerMap(engine, [MANAGED]);+ expect(map.get(MANAGED)?.map(b => b.request_id)).toEqual([blocker]);+ const summary = await readTerminalFailureSummary(engine, { sourceIds: [MANAGED], checkpointBlockers: map });+ if (summary.status !== 'ok') throw new Error('unknown');+ expect(summary.sources[0]!.active_blockers).toEqual([expect.objectContaining({ kind: 'checkpoint', request_id: blocker, slug: 'notes/two', category: 'checkpoint_blocker' })]);++ const check = (await terminalFailuresCheck(engine, [MANAGED]))!;+ expect(check.status).toBe('warn');+ expect(check.message).toContain(`checkpoint blocker ${blocker} (notes/two) on source ${MANAGED}`);++ const status = await readSyncStatus(engine, MANAGED);+ expect(status.checkpoint_blockers?.map(b => b.request_id)).toEqual([blocker]);+ if (status.terminal_failures.status !== 'ok') throw new Error('unknown');+ expect(status.terminal_failures.active_blockers).toEqual([{ kind: 'checkpoint', request_id: blocker, slug: 'notes/two', category: 'checkpoint_blocker' }]);+ expect(await human(MANAGED)).toContain(`BLOCKING checkpoint: request ${blocker} (notes/two) [checkpoint_blocker]`);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(home, { recursive: true, force: true });+ }+ }, 60_000);+});diff --git a/test/terminal-failure-metrics-6650.test.ts b/test/terminal-failure-metrics-6650.test.tsindex a84ac582cc..d0fac33e33 100644--- a/test/terminal-failure-metrics-6650.test.ts+++ b/test/terminal-failure-metrics-6650.test.ts@@ -3,7 +3,8 @@** Protects: the real `mountMetrics` handler appends per-source gauges (active blockers, unresolved, historical, new in* 24 h, defects) read from the same bounded aggregate doctor uses; the counts stay behind requireAdmin and never reach- * the public `/health`; an aggregate that did not finish reports `known 0` with no per-source series, never zeros.+ * the public `/health`; an aggregate that did not finish reports `known 0` with no per-source series, never zeros; scrapes+ * within `TERMINAL_METRICS_TTL_MS` (60 s) share one aggregate query.* PGLite in-memory, a bare Express app wired with the real mount functions.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';@@ -11,7 +12,8 @@ import express from 'express';import type { Server } from 'http';import { randomUUID } from 'node:crypto';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { createMetricsCounters, mountHealth, mountMetrics, renderTerminalFailureMetrics } from '../src/commands/serve-http-metrics.ts';+import { cachedTerminalSummary, createMetricsCounters, mountHealth, mountMetrics, renderTerminalFailureMetrics, TERMINAL_METRICS_TTL_MS } from '../src/commands/serve-http-metrics.ts';+import type { BrainEngine } from '../src/core/engine.ts';import type { ServeHttpContext } from '../src/commands/serve-http.ts';const SOURCE = 'metrics-src';@@ -29,13 +31,13 @@ beforeAll(async () => {}, 60_000);afterAll(async () => { await engine.disconnect(); });-async function withApp<T>(authed: boolean, fn: (base: string) => Promise<T>): Promise<T> {+async function withApp<T>(authed: boolean, fn: (base: string) => Promise<T>, brain: BrainEngine = engine): Promise<T> {const app = express();const requireAdmin = (_req: express.Request, res: express.Response, next: express.NextFunction) => {if (authed) { next(); return; }res.status(401).json({ error: 'Admin authentication required' });};- const ctx = { engine, config: { engine: 'pglite' }, requireAdmin, metricsCounters: createMetricsCounters() } as unknown as ServeHttpContext;+ const ctx = { engine: brain, config: { engine: 'pglite' }, requireAdmin, metricsCounters: createMetricsCounters() } as unknown as ServeHttpContext;mountHealth(app, ctx);mountMetrics(app, ctx);const server: Server = app.listen(0);@@ -73,6 +75,27 @@ describe('terminal-failure gauges on /metrics', () => {});});+ test('scrapes inside the TTL share one aggregate query; the next one after it reads again', async () => {+ let queries = 0;+ const counted = new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: unknown) => {+ if (sql.includes('GROUPING SETS')) queries++;+ return target.executeRaw(sql, params, opts as never);+ };+ return Reflect.get(target, key);+ } }) as BrainEngine;+ await withApp(true, async base => {+ const [a, b] = await Promise.all([fetch(`${base}/metrics`), fetch(`${base}/metrics`)]);+ const c = await fetch(`${base}/metrics`);+ for (const res of [a, b, c]) expect(await res.text()).toContain(`gbrain_writer_terminal_failures_unresolved{source="${SOURCE}"} 3`);+ }, counted);+ expect(queries).toBe(1);+ await cachedTerminalSummary(counted, Date.now() + TERMINAL_METRICS_TTL_MS - 1_000);+ expect(queries).toBe(1);+ await cachedTerminalSummary(counted, Date.now() + TERMINAL_METRICS_TTL_MS + 1);+ expect(queries).toBe(2);+ });+test('an unknown aggregate is known 0 with no per-source zeros', () => {const text = renderTerminalFailureMetrics({ status: 'unknown', window_days: 7, reason: 'deadline' });expect(text).toContain('gbrain_writer_terminal_failures_known 0');@@ -81,7 +104,7 @@ describe('terminal-failure gauges on /metrics', () => {test('a source label is escaped for the exposition format', () => {const empty = { active_blockers: [], unresolved: { rows: 1, distinct_slugs: 1, distinct_intents: 1, oldest_at: null, oldest_age_seconds: null }, historical_rows: 0,- new_last_24h: 0, daily_7d: [0, 0, 0, 0, 0, 0, 0], defects: [], categories: [] };+ new_last_24h: 0, new_last_24h_older_builds: { rows: 0, builds: [] }, daily_7d: [0, 0, 0, 0, 0, 0, 0], defects: [], categories: [] };const text = renderTerminalFailureMetrics({ status: 'ok', window_days: 7, window_clamped: false, retention_days: 30, sources: [{ source_id: 'a"b\\c', ...empty }] });expect(text).toContain('gbrain_writer_terminal_failures_unresolved{source="a\\"b\\\\c"} 1');});diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.tsindex edf3245dfa..9d6a0c1afb 100644--- a/test/terminal-failures-6650.test.ts+++ b/test/terminal-failures-6650.test.ts@@ -185,6 +185,26 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drillexpect(validateTerminalConfigValue('persistence.terminal_failures.spike_factor', '2.5')).toBeNull();});+ test('a spike an older write owner drives says so and names its build, instead of reading as a new defect', async () => {+ await engine.setConfig('persistence.terminal_failures.spike_min', '3');+ for (let i = 0; i < 4; i++) await seed({ slug: `notes/k${i}`, operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knockOnDetail('window_predecessor', null), build: '0.60.200.0', hoursAgo: 1 });+ await seed({ slug: 'notes/c', state: 'conflict', code: 'revision_conflict', hoursAgo: 1 });+ const summary = await readTerminalFailureSummary(engine);+ if (summary.status !== 'ok') throw new Error('unknown');+ expect(summary.sources[0]!.new_last_24h_older_builds).toEqual({ rows: 4, builds: ['0.60.200.0'] });+ const check = (await terminalFailuresCheck(engine))!;+ expect(check.status).toBe('warn');+ expect(check.message).toContain('4 of them were written by gbrain 0.60.200.0, older than the release that fixed their class: an older write owner is still producing these; upgrade or restart it.');+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', SOURCE, '--json']);+ expect(check.details).toMatchObject({ spike: { spiking: true, older_builds: { rows: 4, builds: ['0.60.200.0'] } } });+ // The same spike from the current build stays the generic drill-down.+ await engine.executeRaw('DELETE FROM persistence_requests');+ for (let i = 0; i < 4; i++) await seed({ slug: `notes/k${i}`, operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knockOnDetail('window_predecessor', null), hoursAgo: 1 });+ const current = (await terminalFailuresCheck(engine))!;+ expect(current.message).not.toContain('older write owner');+ expect((current.fix as { argv: string[] }).argv.slice(0, 4)).toEqual(['gbrain', 'sources', 'writer', 'failures']);+ });+test('the window is clamped to receipt retention', async () => {await engine.setConfig('persistence.receipt_retention_days', '3');expect(await readTerminalThresholds(engine, 7)).toMatchObject({ windowDays: 3, clamped: true, retentionDays: 3 });