Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): writer terminal-state visibility and read-time exits (#6650)

garrytand22c1d1c0c25
diff --git a/AGENTS.md b/AGENTS.md
index b584f77970..37c16f052d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -197,6 +197,16 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
the sync it prints; when `needs_human` is true, relay `next.user_message`
with the slug. Decision table:
[`docs/guides/sync-unblock-runbook.md`](./docs/guides/sync-unblock-runbook.md).
+- **Writes that ended without committing** (doctor
+ `persistence_terminal_failures`, `terminal write failures` in
+ `gbrain sync status`): the check separates active blockers (a recovery
+ record or a sync checkpoint blocker: run its `fix.command`) from the
+ unresolved pile and from historical rows that need nothing. Group the pile
+ with `gbrain sources writer failures <id> --group-by category` (read-only;
+ each group has a fix and an exact drill-down), read one receipt's
+ `diagnosis.fix` with `gbrain write-request <request> --json`, and relay a
+ group whose `needs_human` is true. Runbook:
+ [terminal write failures](docs/guides/troubleshooting.md#terminal-write-failures).
- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),
[`docs/UPGRADING_DOWNSTREAM_AGENTS.md`](./docs/UPGRADING_DOWNSTREAM_AGENTS.md),
[`skills/migrations/`](./skills/migrations/), `gbrain apply-migrations --yes --no-autopilot-install` (manual migration orchestration without service installation).
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 6ce8d033df..5f8907a79b 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -9,7 +9,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/behavior-changes.ts` — `behavior_changes` (META, after `chat_fallback_chain`): the `behavior_changes` disclosure read again (`src/core/behavior-change-notice.ts`): every change newer than the brain's baseline, labeled by release, whether or not the notice was shown; always `ok`; reads the baseline and markers without recording either, and reports which channels were shown.
- `src/commands/doctor/checks/ranking-extraction.ts` — informational BRAIN check `extraction_date_grounding`, registered after `timeline_history`: fact extraction, synthesis, atoms and takes grounded by default, all off when the setting is false, and whether the chronicle prompt is opted in. Pinned by `test/doctor-ranking-extraction.test.ts` and the doctor registry/JSON goldens.
- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).
-- `src/commands/doctor/checks/persistence-requests.ts` — four wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. `persistence_write_stall` (#6176, host-only) reads running requests and warns when one has held its claim longer than `persistence.max_claim_ms` (`claim-phase.ts`; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with `gbrain sources writer status --source <id> --json` as the fix. `persistence_session_timeouts` (#6278, host-only) reads `SHOW statement_timeout` through the configured URL and warns `session_timeouts_not_applied` when it is `0` while `resolveSessionTimeouts()` configured one (a transaction-mode pooler dropped the startup parameter), naming the role-level fix. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`, `test/persistence-write-stall.test.ts`, `test/persistence-session-timeouts-check.test.ts`.
+- `src/commands/doctor/checks/persistence-requests.ts` — wave checks (OPS, registered in `wave-checks.ts`); `persistence_terminal_failures` (#6650) is in [Managed sync bookkeeping](managed-sync-bookkeeping.md). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. `persistence_write_stall` (#6176, host-only) reads running requests and warns when one has held its claim longer than `persistence.max_claim_ms` (`claim-phase.ts`; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with `gbrain sources writer status --source <id> --json` as the fix. `persistence_session_timeouts` (#6278, host-only) reads `SHOW statement_timeout` through the configured URL and warns `session_timeouts_not_applied` when it is `0` while `resolveSessionTimeouts()` configured one (a transaction-mode pooler dropped the startup parameter), naming the role-level fix. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`, `test/persistence-write-stall.test.ts`, `test/persistence-session-timeouts-check.test.ts`.
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 6a38888e69..a349f922d0 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -38,7 +38,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
-- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|claim|transfer` and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts.
+- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts.
- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`. #6255: a pending receipt's envelope carries the receipt fix, and `poll_command` plus the `Poll:` line are that same argv.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index b786906488..4344ccd504 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -44,7 +44,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`.
- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.
-- `src/core/ops/persistence.ts` — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds `write_error_message`, the same allowlisted `writeFailureDiagnostic` message managed sync prints, never raw journal error text (`test/sync-frontmatter-slug-conflict.test.ts`). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers; frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: `test/persistence-receipt-operations.test.ts`, `test/client-grants.test.ts`, `test/mcp-surface.test.ts`.
+- `src/core/ops/persistence.ts` — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds `write_error_message`, the same allowlisted `writeFailureDiagnostic` message managed sync prints, never raw journal error text (`test/sync-frontmatter-slug-conflict.test.ts`). A terminal or recovery-holding receipt also returns `write_error_reason`, `suggestion` and a `diagnosis` from `classifyTerminal` with a rendered `fix` (#6650, `test/write-request-diagnosis-6650.test.ts`). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers; frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: `test/persistence-receipt-operations.test.ts`, `test/client-grants.test.ts`, `test/mcp-surface.test.ts`.
- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 8729ee37ae..97056ac6fd 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
-- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969).
+- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.
- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist.
- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index b3cb5b621a..48b7cabc55 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -20,3 +20,6 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-checkpoint-replaced.ts` — wave 16 (GBRA-79, #6513 comments): a managed-sync checkpoint whose cursor another run of the source replaced is superseded, not failed. `checkpointCursorReplaced` is the classification the shared validator (`sync-prepare.ts` `sourceSyncChecks` consumer) and the checkpoint's final locked compare-and-swap both apply before their own checks: a checkpoint intent whose durable cursor names another `runId` refuses `sync_cursor_replaced` (receipt state `conflict`, through `coordinator.ts` `conflictCode`); a page request whose cursor moved keeps `revision_conflict` (its run re-admits from the current cursor), a same-run index lag keeps `revision_conflict`, a missing manifest keeps `storage_error`. `checkpointSuperseded` recognizes that receipt in `sync-run.ts`: `settleFailedRequest` records no managed-sync failure for it and continues with the winning cursor as it stands (`currentCursor`, the same move the ENG-A7 admission guard makes when the cursor moves under it; the winner's run id, index and manifest are kept, nothing of it is cleared or advanced), and `retryFailedStart` never treats a checkpoint receipt as a page fault. Before, the loser's run recorded the conflict as a `managed-sync-failure` row, doctor reported it, and `--retry-failed` rediscovered from HEAD. Test: `test/managed-sync-checkpoint-replaced.test.ts` (replacement before validation on both engines; replacement from a second Postgres session between validation and the CAS; `--retry-failed` afterwards converts nothing; controls: index lag, missing manifest).
- `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/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.md
index 0055588806..03cf1a0379 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -32,6 +32,7 @@
| [Sync held a file with `worktree_dirty`](#worktree-dirty-hold) | commit (or restore) the file, then `gbrain sync unblock --source <id> --apply` and the sync it prints | agent; whoever edits the file commits it | none | `gbrain sources status <id> --json` |
| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or `sliced catch-up: committed the <phase> slice of <commit> through <path>` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. A first sync, a `--full` sync or one commit that alone exceeds the bound is cut into path slices instead (#6349): every import slice, then bounded deletion slices, pinned at one target; `last_commit` moves only when the last slice settles, and the same command resumes an unfinished target at its stored slice. Only one file whose manifest entry alone exceeds the byte bound still refuses `request_too_large`, naming it; exclude it (`--exclude`, or `gbrain config set sync.exclude`) and rerun | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) |
| A write, sync, connector run or activation refuses `storage_error` with `requires exactly one known boolean persistence state` (`detail: persistence_mode_unknown`) | The `persistence_brain` singleton is missing, duplicated or malformed, so gbrain cannot tell whether the brain is managed and refuses instead of writing around the owner (#6482). Run `gbrain sources writer status --probe --json` on the brain host (it reports `mode: unknown` and the problem instead of refusing), restore the one row (`gbrain doctor --json` names the repair), then rerun the command | host operator | none | `gbrain doctor --json` |
+| [Doctor warns `persistence_terminal_failures`, or `gbrain sync status` shows `terminal write failures` with BLOCKING or unresolved rows](#terminal-write-failures) | run the check's `fix.command`; for the pile, `gbrain sources writer failures <id> --group-by category` and each group's drill-down; `gbrain write-request <request> --json` names one receipt's `diagnosis.fix` | agent; a group whose `needs_human` is true after the user decides | none to inspect; as the fix's `consent` | `gbrain doctor --only persistence_terminal_failures --json` is ok |
| The drain stopped `connection_lost` | check the database and pooler (`gbrain doctor --json`), then rerun the same sync; it resumes at the stored cursor | agent | none | `gbrain sync status --source <id> --json` |
| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
| [The catch-up is parked: `data_moving: false`, doctor `managed_sync_not_moving`, or `gbrain sources writer movement` exited 1](#managed-sync-not-moving) | `gbrain sources status <id> --json` prints the exact writer-status command; run it: `gbrain sources writer status --source <id> --json` ends each running claim in a `claim.next` (`claim_running`: rerun after `retry_after_ms`; `claim_overdue`: `tell_user_to_run`, restart the named owner pid) | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer movement <id>` (exit 0 when the data moves again), then `gbrain doctor --only managed_sync_not_moving --json` |
@@ -186,6 +187,32 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr
<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.
+<a id="terminal-write-failures"></a>**Doctor warns `persistence_terminal_failures`, or `gbrain sync status` reports terminal write failures?** Every write leaves a receipt, and a receipt that ended `failed`, `conflict` or `cancelled` stays in `persistence_requests` until compaction. gbrain reads them at query time and sorts each one into a category with a class, safe actions, whether a person decides, and a structured fix (nothing new is stored). Most rows need no action, so the check separates three things:
+
+- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).
+- **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.
+
+```bash
+gbrain doctor --only persistence_terminal_failures --json # blockers, unresolved, historical, the fix
+gbrain sync status --source <id> # the same summary for one source, with BLOCKING lines
+gbrain sources writer failures <id> --group-by category # groups on code + origin + category, each with its drill-down
+gbrain sources writer failures <id> --category owner_exception --code storage_error --origin owner_exception --json
+gbrain 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:
+
+```bash
+gbrain config set persistence.terminal_failures.window_days 14
+gbrain config set persistence.terminal_failures.spike_factor 3
+gbrain config set persistence.terminal_failures.spike_min 25
+```
+
+Refused writes a caller never saw land (`lost_caller_writes`) have their own repair: [failed writes](repair.md#failed-writes). Why a single write was refused: [write refusals](write-refusals.md).
+
<a id="owner-unavailable"></a>**`fence_repair`, chronicle, fact-fence adoption or another maintenance step refused `owner_unavailable`?** A managed source publishes only through the host that owns its checkout, and the refusal's `reason` says which condition this is; the fix is always the read-only `gbrain sources writer status --source <id> --json`, and nothing claims or transfers ownership to get a step through.
| `reason` | What it means | Next |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 3546a75fbe..f5462b5e67 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -25,7 +25,14 @@ in with the real source and slug where the code knows them, sometimes with
placeholders such as `<source>` or `<brain>` to fill in, and sometimes an
inspection instruction. A failed write receipt (`gbrain write-request <id>`) carries the error code as
`write_error` and its diagnostic message as `write_error_message`; managed
-sync and memory-verb errors add the specific reason.
+sync and memory-verb errors add the specific reason. Since #6650 a receipt that
+ended `failed`, `conflict` or `cancelled` (or still holds a recovery record)
+also carries `write_error_reason` (this page's reason), the same `suggestion`,
+and a `diagnosis`: its category, class, safe actions, whether a person decides,
+whether it is historical, and a structured `fix` (`fix.next`, `fix.command`).
+To see every such receipt of a source at once, grouped with a fix per group:
+`gbrain sources writer failures <source> --group-by category`
+([terminal write failures](troubleshooting.md#terminal-write-failures)).
Run recovery commands on the brain host unless the row says otherwise.
Keep the original `request_id`. Unless a row says to use a new one, retry the
diff --git a/llms-full.txt b/llms-full.txt
index 0400f73f60..25fc5ac965 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1898,6 +1898,16 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
the sync it prints; when `needs_human` is true, relay `next.user_message`
with the slug. Decision table:
[`docs/guides/sync-unblock-runbook.md`](./docs/guides/sync-unblock-runbook.md).
+- **Writes that ended without committing** (doctor
+ `persistence_terminal_failures`, `terminal write failures` in
+ `gbrain sync status`): the check separates active blockers (a recovery
+ record or a sync checkpoint blocker: run its `fix.command`) from the
+ unresolved pile and from historical rows that need nothing. Group the pile
+ with `gbrain sources writer failures <id> --group-by category` (read-only;
+ each group has a fix and an exact drill-down), read one receipt's
+ `diagnosis.fix` with `gbrain write-request <request> --json`, and relay a
+ group whose `needs_human` is true. Runbook:
+ [terminal write failures](docs/guides/troubleshooting.md#terminal-write-failures).
- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),
[`docs/UPGRADING_DOWNSTREAM_AGENTS.md`](./docs/UPGRADING_DOWNSTREAM_AGENTS.md),
[`skills/migrations/`](./skills/migrations/), `gbrain apply-migrations --yes --no-autopilot-install` (manual migration orchestration without service installation).
@@ -10175,6 +10185,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| [Sync held a file with `worktree_dirty`](#worktree-dirty-hold) | commit (or restore) the file, then `gbrain sync unblock --source <id> --apply` and the sync it prints | agent; whoever edits the file commits it | none | `gbrain sources status <id> --json` |
| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or `sliced catch-up: committed the <phase> slice of <commit> through <path>` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. A first sync, a `--full` sync or one commit that alone exceeds the bound is cut into path slices instead (#6349): every import slice, then bounded deletion slices, pinned at one target; `last_commit` moves only when the last slice settles, and the same command resumes an unfinished target at its stored slice. Only one file whose manifest entry alone exceeds the byte bound still refuses `request_too_large`, naming it; exclude it (`--exclude`, or `gbrain config set sync.exclude`) and rerun | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) |
| A write, sync, connector run or activation refuses `storage_error` with `requires exactly one known boolean persistence state` (`detail: persistence_mode_unknown`) | The `persistence_brain` singleton is missing, duplicated or malformed, so gbrain cannot tell whether the brain is managed and refuses instead of writing around the owner (#6482). Run `gbrain sources writer status --probe --json` on the brain host (it reports `mode: unknown` and the problem instead of refusing), restore the one row (`gbrain doctor --json` names the repair), then rerun the command | host operator | none | `gbrain doctor --json` |
+| [Doctor warns `persistence_terminal_failures`, or `gbrain sync status` shows `terminal write failures` with BLOCKING or unresolved rows](#terminal-write-failures) | run the check's `fix.command`; for the pile, `gbrain sources writer failures <id> --group-by category` and each group's drill-down; `gbrain write-request <request> --json` names one receipt's `diagnosis.fix` | agent; a group whose `needs_human` is true after the user decides | none to inspect; as the fix's `consent` | `gbrain doctor --only persistence_terminal_failures --json` is ok |
| The drain stopped `connection_lost` | check the database and pooler (`gbrain doctor --json`), then rerun the same sync; it resumes at the stored cursor | agent | none | `gbrain sync status --source <id> --json` |
| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
| [The catch-up is parked: `data_moving: false`, doctor `managed_sync_not_moving`, or `gbrain sources writer movement` exited 1](#managed-sync-not-moving) | `gbrain sources status <id> --json` prints the exact writer-status command; run it: `gbrain sources writer status --source <id> --json` ends each running claim in a `claim.next` (`claim_running`: rerun after `retry_after_ms`; `claim_overdue`: `tell_user_to_run`, restart the named owner pid) | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer movement <id>` (exit 0 when the data moves again), then `gbrain doctor --only managed_sync_not_moving --json` |
@@ -10329,6 +10340,32 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr
<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.
+<a id="terminal-write-failures"></a>**Doctor warns `persistence_terminal_failures`, or `gbrain sync status` reports terminal write failures?** Every write leaves a receipt, and a receipt that ended `failed`, `conflict` or `cancelled` stays in `persistence_requests` until compaction. gbrain reads them at query time and sorts each one into a category with a class, safe actions, whether a person decides, and a structured fix (nothing new is stored). Most rows need no action, so the check separates three things:
+
+- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).
+- **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.
+
+```bash
+gbrain doctor --only persistence_terminal_failures --json # blockers, unresolved, historical, the fix
+gbrain sync status --source <id> # the same summary for one source, with BLOCKING lines
+gbrain sources writer failures <id> --group-by category # groups on code + origin + category, each with its drill-down
+gbrain sources writer failures <id> --category owner_exception --code storage_error --origin owner_exception --json
+gbrain 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:
+
+```bash
+gbrain config set persistence.terminal_failures.window_days 14
+gbrain config set persistence.terminal_failures.spike_factor 3
+gbrain config set persistence.terminal_failures.spike_min 25
+```
+
+Refused writes a caller never saw land (`lost_caller_writes`) have their own repair: [failed writes](repair.md#failed-writes). Why a single write was refused: [write refusals](write-refusals.md).
+
<a id="owner-unavailable"></a>**`fence_repair`, chronicle, fact-fence adoption or another maintenance step refused `owner_unavailable`?** A managed source publishes only through the host that owns its checkout, and the refusal's `reason` says which condition this is; the fix is always the read-only `gbrain sources writer status --source <id> --json`, and nothing claims or transfers ownership to get a step through.
| `reason` | What it means | Next |
diff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
index 1028ef5827..f718c11f48 100644
--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
@@ -526,6 +526,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `gbrain doctor --remediate` steps marked "requires user agreement" (PROTECTED repairs, paid steps): show the plan and cost, and run with `--yes --include-repairs --expect <plan_hash> --max-usd <n>` (the hash from `--remediation-plan --json`) only after the user agrees; `preview_changed` means the plan moved, so preview and ask again. A step that would exceed the cap is not started.
- A finding classified `operator_required`: follow its instruction or relay it to the brain host's operator. `consent_required`: ask the user.
- A writer-coordination refusal (`writer_coordinator_required`, `writer_not_quiesced`, `recovery_required`): inspect `gbrain sources writer status` and hand the blocked recovery to the operator; never claim a checkout or delete a lock.
+- Doctor warns `persistence_terminal_failures`: run its `fix.command` (an active blocker: a recovery record or a sync checkpoint blocker; or an unresolved gbrain-defect class to report with the receipt ids). For the rest of the pile, `gbrain sources writer failures <source> --group-by category` (read-only) groups receipts with a fix and drill-down per group; historical rows need nothing. Never cancel or edit receipts to clear the count. Runbook: [terminal write failures](https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#terminal-write-failures).
- `gbrain dream` stops on a budget (exit 11): run the printed `resume_command` within the agreed budget.
## Anti-Patterns
diff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.md
index 1028ef5827..f718c11f48 100644
--- a/plugin/skills/maintain/SKILL.md
+++ b/plugin/skills/maintain/SKILL.md
@@ -526,6 +526,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `gbrain doctor --remediate` steps marked "requires user agreement" (PROTECTED repairs, paid steps): show the plan and cost, and run with `--yes --include-repairs --expect <plan_hash> --max-usd <n>` (the hash from `--remediation-plan --json`) only after the user agrees; `preview_changed` means the plan moved, so preview and ask again. A step that would exceed the cap is not started.
- A finding classified `operator_required`: follow its instruction or relay it to the brain host's operator. `consent_required`: ask the user.
- A writer-coordination refusal (`writer_coordinator_required`, `writer_not_quiesced`, `recovery_required`): inspect `gbrain sources writer status` and hand the blocked recovery to the operator; never claim a checkout or delete a lock.
+- Doctor warns `persistence_terminal_failures`: run its `fix.command` (an active blocker: a recovery record or a sync checkpoint blocker; or an unresolved gbrain-defect class to report with the receipt ids). For the rest of the pile, `gbrain sources writer failures <source> --group-by category` (read-only) groups receipts with a fix and drill-down per group; historical rows need nothing. Never cancel or edit receipts to clear the count. Runbook: [terminal write failures](https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#terminal-write-failures).
- `gbrain dream` stops on a budget (exit 11): run the printed `resume_command` within the agreed budget.
## Anti-Patterns
diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.ts
index fdb7cbad51..0eefffd4e4 100644
--- a/scripts/check-agent-contract.ts
+++ b/scripts/check-agent-contract.ts
@@ -266,6 +266,8 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st
'schema active',
// #6317: trusted-local writer administration reads (owners, running claims, consumers, movement); `sources writer claim|transfer|deactivate` stay mutating.
'sources writer status', 'sources writer movement',
+ // #6650: the terminal-failure drill-down and the sync operator status only read receipts and cursors.
+ 'sources writer failures', 'sync status',
// #6466: `--list` returns before the orchestration lock and never runs an orchestrator or writes the ledger.
'apply-migrations --list']);
diff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.md
index 654240493e..14418aefe1 100644
--- a/skills/maintain/SKILL.md
+++ b/skills/maintain/SKILL.md
@@ -525,6 +525,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `gbrain doctor --remediate` steps marked "requires user agreement" (PROTECTED repairs, paid steps): show the plan and cost, and run with `--yes --include-repairs --expect <plan_hash> --max-usd <n>` (the hash from `--remediation-plan --json`) only after the user agrees; `preview_changed` means the plan moved, so preview and ask again. A step that would exceed the cap is not started.
- A finding classified `operator_required`: follow its instruction or relay it to the brain host's operator. `consent_required`: ask the user.
- A writer-coordination refusal (`writer_coordinator_required`, `writer_not_quiesced`, `recovery_required`): inspect `gbrain sources writer status` and hand the blocked recovery to the operator; never claim a checkout or delete a lock.
+- Doctor warns `persistence_terminal_failures`: run its `fix.command` (an active blocker: a recovery record or a sync checkpoint blocker; or an unresolved gbrain-defect class to report with the receipt ids). For the rest of the pile, `gbrain sources writer failures <source> --group-by category` (read-only) groups receipts with a fix and drill-down per group; historical rows need nothing. Never cancel or edit receipts to clear the count. Runbook: [terminal write failures](https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#terminal-write-failures).
- `gbrain dream` stops on a budget (exit 11): run the printed `resume_command` within the agreed budget.
## Anti-Patterns
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 2c3e6961eb..5844e7ec64 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -94,7 +94,7 @@
"idea-lineage/SKILL.md": "8cb36179dbf94abc17065613b8e773b1bb2b22670742aa77347b91ac885a05c5",
"idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41",
"ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae",
- "maintain/SKILL.md": "2a1d99b68a58a6f67ee88c871bb1185f4f73b99d26a7ed38ac56b2e12a21e5ce",
+ "maintain/SKILL.md": "cb45aba2ea4075195ed244f28571457cec8cb42f70fe209b570c29528d857b9e",
"manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4",
"mcp-access/SKILL.md": "1bc16338b89f476aa8c24ffec79c989fa60716793998af264d357f7886d2bc96",
"measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",
diff --git a/src/commands/config/preparation-keys.ts b/src/commands/config/preparation-keys.ts
index 81b7e4ef77..177a154b39 100644
--- a/src/commands/config/preparation-keys.ts
+++ b/src/commands/config/preparation-keys.ts
@@ -2,16 +2,21 @@
* #6278: `config set` validation for the preparation budget family
* (persistence/preparation-budget.ts): each key's range, and the ceiling rule
* across the sibling keys, refused as a usage error (exit 2) with the value in
- * effect as the read-only fix; nothing is written.
+ * effect as the read-only fix; nothing is written. #6650 adds the terminal-failure thresholds.
*/
import type { BrainEngine } from '../../core/engine.ts';
import { PREPARATION_BUDGET_CONFIG_KEYS, readPreparationConfigValues, validatePreparationConfigValue } from '../../core/persistence/preparation-budget.ts';
import { exitCliError, usageError } from '../../cli/cli-error.ts';
+import { validateTerminalConfigValue } from '../../core/persistence/terminal-failures.ts';
export async function refuseInvalidPreparationValue(engine: BrainEngine, key: string, value: string): Promise<void> {
+ const getFix = { fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent' as const, why: 'Shows the value in effect; nothing was written.', requires_exclusive: false } };
+ // #6650: the terminal-failure thresholds (persistence/terminal-failures.ts) share this persistence.* refusal.
+ const terminal = validateTerminalConfigValue(key, value);
+ if (terminal) exitCliError(usageError(terminal, `Set ${key} to a value in that range, e.g. gbrain config set ${key} ${key.endsWith('window_days') ? 14 : key.endsWith('spike_factor') ? 3 : 25}.`, getFix), 'config');
if (!PREPARATION_BUDGET_CONFIG_KEYS.includes(key)) return;
const refusal = validatePreparationConfigValue(key, value, await readPreparationConfigValues(engine));
if (!refusal) return;
exitCliError(usageError(refusal.message, refusal.suggestion,
- { fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false } }), 'config');
+ getFix), 'config');
}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 3cb102df2c..8d83d8b033 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -308,6 +308,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'persistence_request_growth',
'persistence_write_stall',
'lost_caller_writes',
+ 'persistence_terminal_failures',
'persistence_session_timeouts',
'connector_held_items',
'git_held_files',
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 704dc64ac5..608712c965 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -6,7 +6,7 @@ import { claimStall, claimStateOf, MAX_CLAIM_CONFIG_KEY, readMaxClaimMs } from '
import { preparationBudgetMs } from '../../../core/persistence/preparation-budget.ts';
import { readPreparationPolicy } from '../../../core/persistence/switches.ts';
import { resolvePrepare, resolveSessionTimeouts } from '../../../core/db.ts';
-import { agentFix, checkError } from '../check-fix.ts';
+import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
import { lostCallerWrites } from '../../../core/repair/failed-writes.ts';
const WINDOW_DAYS = 7;
@@ -230,3 +230,72 @@ export async function lostCallerWritesCheck(engine: BrainEngine, sourceIds?: str
return checkError('lost_caller_writes', 'inspect refused caller writes', error, { details: { count: 'unknown', docs } });
}
}
+
+/**
+ * #6650 (L3): terminal write receipts that did not commit, read at doctor time (`terminal-failures.ts`, one bounded
+ * aggregate; `terminal-classify.ts` names each class and its fix). Warns on any active blocker (a receipt still holding
+ * a publication recovery record, which holds its root, or a receipt PR A's `checkpoint_blockers` names) and on an
+ * unresolved gbrain-defect class, whatever the trend; the spike check (the last 24 h against the zero-filled median of
+ * the 7 days before, `persistence.terminal_failures.spike_factor` / `spike_min`) is secondary. Rows written by a build
+ * older than the release that fixed their class, and rows a later request made moot, are historical and never warn.
+ * Archived sources are skipped; with no engine (the fast path) there is nothing to read.
+ */
+export async function terminalFailuresCheck(engine: BrainEngine | null, sourceIds?: string[]): Promise<Check | null> {
+ if (!engine) return null;
+ const name = 'persistence_terminal_failures';
+ const docs = 'docs/guides/troubleshooting.md#terminal-write-failures';
+ try {
+ const { readTerminalFailureSummary, readTerminalThresholds, readCheckpointBlockerMap, isSpike, sevenDayMedian, TERMINAL_WINDOW_KEY, TERMINAL_SPIKE_FACTOR_KEY, TERMINAL_SPIKE_MIN_KEY } = await import('../../../core/persistence/terminal-failures.ts');
+ const thresholds = await readTerminalThresholds(engine);
+ const checkpointBlockers = await readCheckpointBlockerMap(engine, sourceIds);
+ const summary = await readTerminalFailureSummary(engine, { sourceIds, thresholds, checkpointBlockers });
+ const config = { window_days: { key: TERMINAL_WINDOW_KEY, value: thresholds.windowDays }, spike_factor: { key: TERMINAL_SPIKE_FACTOR_KEY, value: thresholds.spikeFactor },
+ spike_min: { key: TERMINAL_SPIKE_MIN_KEY, value: thresholds.spikeMin }, receipt_retention_days: thresholds.retentionDays, window_clamped: thresholds.clamped };
+ if (summary.status === 'unknown') {
+ return { name, status: 'warn', message: `Terminal write failures could not be read: ${summary.reason}. Health is unknown, not clear; rerun gbrain doctor --only ${name}.`,
+ details: { health: 'unknown', config, docs } };
+ }
+ const sources = summary.sources;
+ const blockers = sources.flatMap(s => s.active_blockers);
+ const defects = sources.flatMap(s => s.defects.map(d => ({ ...d, source_id: s.source_id })));
+ const unresolved = sources.reduce((n, s) => n + s.unresolved.rows, 0);
+ const historical = sources.reduce((n, s) => n + s.historical_rows, 0);
+ const last24h = sources.reduce((n, s) => n + s.new_last_24h, 0);
+ const daily = Array.from({ length: 7 }, (_, i) => sources.reduce((n, s) => n + (s.daily_7d[i] ?? 0), 0));
+ const spike = isSpike(last24h, daily, thresholds);
+ const oldest = sources.reduce<number | null>((max, s) => s.unresolved.oldest_age_seconds === null ? max : Math.max(max ?? 0, s.unresolved.oldest_age_seconds), null);
+ const details = { count: blockers.length + defects.reduce((n, d) => n + d.rows, 0), active_blockers: blockers.map(({ action: _a, ...b }) => b),
+ unresolved: { rows: unresolved, distinct_slugs: sources.reduce((n, s) => n + s.unresolved.distinct_slugs, 0), distinct_intents: sources.reduce((n, s) => n + s.unresolved.distinct_intents, 0),
+ oldest_age_seconds: oldest },
+ historical_rows: historical, new_last_24h: last24h, spike: { last_24h: last24h, median_7d: sevenDayMedian(daily), daily_7d: daily, spiking: spike },
+ defects: defects.map(({ action: _a, ...d }) => d), sources: sources.map(s => ({ source_id: s.source_id, active_blockers: s.active_blockers.length, unresolved: s.unresolved.rows,
+ historical: s.historical_rows, new_last_24h: s.new_last_24h, categories: s.categories })), window_days: summary.window_days, config, docs };
+ const counts = `${blockers.length} active blocker(s), ${unresolved} unresolved row(s) (${details.unresolved.distinct_slugs} page(s), ${details.unresolved.distinct_intents} intent(s)`
+ + `${oldest !== null ? `, oldest ${Math.round(oldest / 3600)} h` : ''}), ${historical} historical non-blocking, ${last24h} in the last 24 h`;
+ if (blockers.length) {
+ const first = blockers[0]!;
+ return { name, status: 'warn', details, fix: { ...first.action, verify: doctorVerify(name) },
+ message: `${blockers.length} write receipt(s) block work right now (${blockers.slice(0, 3).map(b => `${b.kind === 'recovery' ? 'recovery record' : 'checkpoint blocker'} ${b.request_id}`
+ + `${b.slug ? ` (${b.slug})` : ''} on source ${b.source_id}`).join('; ')}). ${counts} in the last ${summary.window_days} d. ${first.action.why}` };
+ }
+ if (defects.length) {
+ const first = defects[0]!;
+ return { name, status: 'warn', details, fix: { ...first.action, verify: doctorVerify(name) },
+ message: `${defects.reduce((n, d) => n + d.rows, 0)} unresolved write receipt(s) in the last ${summary.window_days} d are a gbrain-defect class (${defects.slice(0, 3)
+ .map(d => `${d.category}/${d.code} ×${d.rows} on ${d.source_id}`).join('; ')}). ${counts}. ${first.human_reason ?? first.action.why}` };
+ }
+ const 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]!;
+ 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; `
+ + `${TERMINAL_SPIKE_FACTOR_KEY}, ${TERMINAL_SPIKE_MIN_KEY}=${thresholds.spikeMin}). ${counts}. Group them: ${drill(busiest.source_id).join(' ')}` };
+ }
+ return { name, status: 'ok', details,
+ message: unresolved + historical ? `No write receipt blocks work and no gbrain-defect class is unresolved. ${counts} in the last ${summary.window_days} d.`
+ : `No terminal write failures in the last ${summary.window_days} d.` };
+ } catch (error) {
+ return checkError(name, 'read terminal write failures', error, { details: { health: 'unknown', docs } });
+ }
+}
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index c1af746673..d078aa86b7 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -126,6 +126,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'Some caller writes (remember, put_page, add_timeline_entry) were refused at publication and never landed; the caller saw an error and the fact or edit was dropped',
run: async (engine, scope) => (await import('./checks/persistence-requests.ts')).lostCallerWritesCheck(engine, scope.sourceIds),
},
+ {
+ id: 'persistence_terminal_failures', resolution: 'operator', registration: 'wave',
+ hostOnly: 'Request ids, roots and recovery records are brain-host persistence state outside any source scope.',
+ count: d => Number(d.count ?? 0),
+ impact: 'A write receipt that did not commit blocks work now (a recovery record or a checkpoint blocker), or an unresolved receipt is a gbrain-defect class',
+ instruction: 'Run the fix doctor prints, then drill down with `gbrain sources writer failures <source> --group-by category --json` on the brain host (docs/guides/troubleshooting.md#terminal-write-failures).',
+ run: async (engine, scope) => (await (await import('./checks/persistence-requests.ts')).terminalFailuresCheck(engine, scope.sourceIds))!,
+ },
{
id: 'persistence_session_timeouts', resolution: 'operator', registration: 'wave',
count: d => d.reason === 'session_timeouts_not_applied' ? 1 : 0,
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index a4ef63d02e..dc1696183f 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -16,6 +16,8 @@ import { bigintToStringReplacer } from '../core/utils.ts';
export const WRITER_HELP = `Usage:
gbrain sources writer status [<source>] [--probe] [--json]
+ gbrain sources writer failures <source> [--state all] [--group-by category] [--since 7d] [--limit 20] [--before <cursor>]
+ [--category <c>] [--code <c>] [--origin <o>|none] [--json]
gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]
gbrain sources writer retry-effects <source> --request-id <uuid> [--dry-run] [--json]
gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [administration options] [--dry-run] [--json]
@@ -27,6 +29,13 @@ export const WRITER_HELP = `Usage:
gbrain sources writer lock [--json]
gbrain sources writer unlock [--json]
+failures (read-only) lists the source's write receipts that ended without committing
+(failed, conflict, cancelled) plus any still holding a recovery record, newest first, each
+with its class, safe actions, whether a person decides, its disposition (superseded,
+already_written, duplicate or unknown), an inspect command and its fix. --group-by category
+groups them on code, origin and category, each group with its exact drill-down filter.
+A full page prints truncated with the next command (--before <cursor>). Unresolved rows by
+default; --state all adds resolved and historical ones. Human table by default, JSON with --json.
Inspect status first. movement proves that managed sync data moves over a window
(committed pages and the head's step, never a lease or a lock): run it after
restarting serve and the workers; see movement --help for its states and exits.
@@ -133,6 +142,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
'--source-ids': 'source_ids', '--scopes': 'scopes', '--allowed-operations': 'allowed_operations',
'--slug-prefixes': 'slug_prefixes', '--limit': 'limit', '--before': 'before',
'--admin-intent': 'admin_intent', '--expected-state': 'expected_state', '--request-id': 'request_id', '--pat-file': 'pat_file',
+ '--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category',
};
const arrays = new Set(['source_ids', 'scopes', 'allowed_operations', 'slug_prefixes']);
const seen = new Set<string>();
@@ -163,6 +173,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (group === 'writer') {
const verb = positional.shift();
if (verb === 'status') operation = 'writer_status';
+ else if (verb === 'failures') operation = 'writer_failures';
else if (verb === 'retry-effects') operation = 'writer_retry_effects';
else if (verb === 'git-durability') operation = 'writer_git_durability';
else if (verb === 'claim') operation = 'writer_claim';
@@ -175,7 +186,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (phase !== 'prepare' && phase !== 'accept') throw invalid(group, 'Transfer requires prepare or accept.',
'Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed.');
operation = phase === 'prepare' ? 'writer_transfer_prepare' : 'writer_transfer_accept';
- } else throw invalid(group, 'Writer administration requires status, movement, retry-effects, git-durability, claim, activate, deactivate, transfer, lock, or unlock.',
+ } else throw invalid(group, 'Writer administration requires status, failures, movement, retry-effects, git-durability, claim, activate, deactivate, transfer, lock, or unlock.',
`Name the action after gbrain sources writer${verb ? ` instead of ${verb}` : ''}; start with gbrain sources writer status --json, which changes nothing.`);
const source = positional.shift();
if (source !== undefined) {
@@ -226,6 +237,12 @@ export async function runPersistenceAdminCli(group: Group, args: string[], conne
brainId === 'host' ? 'owner' : 'mounted_database');
}
if (['writer_status', 'writer_lock', 'writer_unlock'].includes(parsed.operation)) result = { selected_brain: brainId, ...(result as Record<string, unknown>) };
+ // #6650: the failures drill-down prints a table for a person and JSON only with --json (fixes rendered for the CLI either way).
+ if (parsed.operation === 'writer_failures') {
+ const { renderWriterFailures } = await import('./sources-writer-failures.ts');
+ await writeStdoutFinal(renderWriterFailures(result as Parameters<typeof renderWriterFailures>[0], parsed.json));
+ return;
+ }
await writeStdoutFinal(JSON.stringify(result, bigintToStringReplacer, 2) + '\n');
} catch (error) {
if (!await reportPersistenceCliError(error, args.includes('--json'))) {
diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.ts
index c052276e17..c32e7da305 100644
--- a/src/commands/serve-http-metrics.ts
+++ b/src/commands/serve-http-metrics.ts
@@ -24,6 +24,7 @@ import { resolveInflightTimeoutSeconds, resolveSessionTimeouts } from '../core/d
import { poolHealthSnapshot, type PoolHealthSnapshot } from '../core/postgres-engine/pool-stats.ts';
import { CODES } from '../core/error-registry.ts';
import { persistenceConsumerStatus } from '../core/persistence/service.ts';
+import { readCheckpointBlockerMap, readTerminalFailureSummary, type TerminalSourceSummary, type TerminalSummary } from '../core/persistence/terminal-failures.ts';
import { consumerRestartRequired, selfExitSuppressed, serveTransport, type ServeTransport } from './serve-health.ts';
import { VERSION } from '../version.ts';
import type { ServeHttpContext } from './serve-http.ts';
@@ -71,6 +72,36 @@ export function metricsTrackingMiddleware(counters: MetricsCounters): RequestHan
};
}
+/**
+ * #6650: writer terminal-failure gauges per source, from the same bounded aggregate doctor reads. Admin-gated with the
+ * rest of /metrics, never on /health. A read that did not finish sets `gbrain_writer_terminal_failures_known 0` and
+ * emits no per-source series, so a scraper sees unknown rather than zero.
+ */
+export function renderTerminalFailureMetrics(summary: TerminalSummary): string {
+ const known = summary.status === 'ok';
+ const lines = [
+ '# HELP gbrain_writer_terminal_failures_known 1 when the terminal-failure aggregate finished within its deadline, 0 when unknown.',
+ '# TYPE gbrain_writer_terminal_failures_known gauge',
+ `gbrain_writer_terminal_failures_known ${known ? 1 : 0}`,
+ '',
+ ];
+ if (!known) return lines.join('\n');
+ const series: Array<[string, string, (s: TerminalSourceSummary) => number]> = [
+ ['active_blockers', 'Write receipts blocking their root now (a recovery record or a sync checkpoint blocker).', s => s.active_blockers.length],
+ ['unresolved', `Unresolved terminal write receipts in the last ${summary.window_days} days (not superseded, not historical, not blocking).`, s => s.unresolved.rows],
+ ['historical', `Non-blocking terminal write receipts in the last ${summary.window_days} days that a later write superseded or a fixed release explains.`, s => s.historical_rows],
+ ['new_24h', 'Terminal write receipts that ended in the last 24 hours.', s => s.new_last_24h],
+ ['defects', 'Unresolved terminal write receipts of a gbrain defect class.', s => s.defects.reduce((n, d) => n + d.rows, 0)],
+ ];
+ const label = (id: string) => id.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n');
+ for (const [name, help, value] of series) {
+ lines.push(`# HELP gbrain_writer_terminal_failures_${name} ${help}`, `# TYPE gbrain_writer_terminal_failures_${name} gauge`);
+ for (const source of summary.sources) lines.push(`gbrain_writer_terminal_failures_${name}{source="${label(source.source_id)}"} ${value(source)}`);
+ lines.push('');
+ }
+ return lines.join('\n');
+}
+
export function renderPrometheusMetrics(
counters: MetricsCounters,
now: number = Date.now(),
@@ -315,8 +346,11 @@ export function mountMetrics(app: Express, ctx: ServeHttpContext): void {
// #3893 (reimplemented from @y2688): Prometheus exposition. Admin-gated —
// 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, (_req: Request, res: Response) => {
+ 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) }));
res.set('Content-Type', 'text/plain; version=0.0.4');
- res.send(renderPrometheusMetrics(metricsCounters));
+ res.send(renderPrometheusMetrics(metricsCounters) + renderTerminalFailureMetrics(summary));
});
}
diff --git a/src/commands/sources-writer-failures.ts b/src/commands/sources-writer-failures.ts
new file mode 100644
index 0000000000..30349ea98f
--- /dev/null
+++ b/src/commands/sources-writer-failures.ts
@@ -0,0 +1,55 @@
+/**
+ * #6650 (L3): output of `gbrain sources writer failures <source>` (`terminal-failures.ts` reads, `administration.ts`
+ * dispatches, locally or through the resident owner). A person gets a table; `--json` gets one document. Fixes and
+ * inspect actions are rendered for the CLI in both, so `fix.next` and `fix.command` follow the agent operator contract.
+ */
+import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';
+import type { TerminalFailureGroup, TerminalFailureListing, TerminalFailureRow } from '../core/persistence/terminal-failures.ts';
+
+type Rendered<T> = Omit<T, 'inspect' | 'fix'> & { inspect: RenderedAction; fix: RenderedAction };
+type RenderedGroup = Omit<TerminalFailureGroup, 'fix' | 'samples'> & { fix: RenderedAction; samples: Array<Omit<TerminalFailureGroup['samples'][number], 'inspect'> & { inspect: RenderedAction }> };
+type RenderedListing = Exclude<TerminalFailureListing, { status: 'ok' }> | (Omit<Extract<TerminalFailureListing, { status: 'ok' }>, 'rows' | 'groups'> & { rows?: Rendered<TerminalFailureRow>[]; groups?: RenderedGroup[] });
+
+function renderListing(listing: TerminalFailureListing): RenderedListing {
+ if (listing.status !== 'ok') return listing;
+ const ctx = cliRenderContext();
+ const { rows, groups, ...rest } = listing;
+ return {
+ ...rest,
+ ...(rows ? { rows: rows.map(row => ({ ...row, inspect: renderAction(row.inspect, ctx), fix: renderAction(row.fix, ctx) })) } : {}),
+ ...(groups ? { groups: groups.map(group => ({ ...group, fix: renderAction(group.fix, ctx),
+ samples: group.samples.map(sample => ({ ...sample, inspect: renderAction(sample.inspect, ctx) })) })) } : {}),
+ };
+}
+
+const pad = (value: string, width: number) => value.length > width ? `${value.slice(0, width - 1)}…` : value.padEnd(width);
+
+export function renderWriterFailures(listing: TerminalFailureListing, json: boolean): string {
+ const rendered = renderListing(listing);
+ if (json) return `${JSON.stringify(rendered, null, 2)}\n`;
+ if (rendered.status !== 'ok') return `Terminal write failures of source ${rendered.source_id}: unknown (${rendered.reason}). Nothing is concluded; run the same command again.\n`;
+ const lines: string[] = [];
+ const scope = `${rendered.state === 'all' ? 'all' : 'unresolved'} receipts of the last ${rendered.window_days} d${rendered.window_clamped ? ' (clamped to persistence.receipt_retention_days)' : ''}`;
+ if (rendered.groups) {
+ lines.push(`Source ${rendered.source_id}: ${rendered.groups.length} group(s) of ${scope}.`);
+ if (rendered.groups.length) lines.push(` ${pad('ROWS', 6)} ${pad('CATEGORY', 26)} ${pad('CODE', 28)} ${pad('ORIGIN', 18)} ${pad('CLASS', 10)} HUMAN`);
+ for (const g of rendered.groups) {
+ lines.push(` ${pad(String(g.rows), 6)} ${pad(g.category, 26)} ${pad(g.code, 28)} ${pad(g.origin ?? '-', 18)} ${pad(g.class, 10)} ${g.needs_human ? 'yes' : 'no'}`);
+ lines.push(` fix: ${g.fix.command ?? g.fix.why}`);
+ lines.push(` rows: ${g.drill_down.join(' ')}`);
+ }
+ } else {
+ const rows = rendered.rows ?? [];
+ lines.push(`Source ${rendered.source_id}: ${rows.length} ${scope}.`);
+ if (rows.length) lines.push(` ${pad('ENDED', 21)} ${pad('STATE', 10)} ${pad('CATEGORY', 22)} ${pad('CODE', 24)} ${pad('DISPOSITION', 15)} ${pad('SLUG', 32)} REQUEST`);
+ for (const r of rows) {
+ lines.push(` ${pad(r.ended_at, 21)} ${pad(r.blocking ? `${r.state}*` : r.state, 10)} ${pad(r.category, 22)} ${pad(r.code, 24)} ${pad(r.disposition, 15)} ${pad(r.slug, 32)} ${r.request_id}`);
+ }
+ if (rows.some(r => r.blocking)) lines.push(' * holds a publication recovery record: it blocks its root now.');
+ const first = rows[0];
+ if (first) lines.push(` Next for the newest: ${first.fix.command ?? first.fix.why}`, ` Inspect one: gbrain write-request <request> --json`);
+ }
+ if (rendered.truncated && rendered.next) lines.push(` More: ${rendered.next.join(' ')}`);
+ if (!rendered.groups?.length && !rendered.rows?.length) lines.push(' Nothing to show: no receipt in the window ended without committing.');
+ return `${lines.join('\n')}\n`;
+}
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index e916ec1f77..bb7e7692bc 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -91,6 +91,15 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);
for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code} safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`);
+ const t = status.terminal_failures;
+ if (t.status === 'unknown') console.log(` terminal write failures: unknown (${t.reason})`);
+ else {
+ const oldest = t.unresolved.oldest_age_seconds === null ? '' : `, oldest ${Math.round(t.unresolved.oldest_age_seconds / 3600)} h`;
+ console.log(` terminal write failures (last ${t.window_days} d): ${t.active_blockers.length} active blocker(s), ${t.unresolved.rows} unresolved (${t.unresolved.distinct_slugs} page(s), `
+ + `${t.unresolved.distinct_intents} intent(s)${oldest}), ${t.historical_rows} historical, ${t.new_last_24h} in the last 24 h${t.defects ? `, ${t.defects} gbrain-defect row(s)` : ''}`);
+ for (const b of t.active_blockers) console.log(` BLOCKING ${b.kind}: request ${b.request_id}${b.slug ? ` (${b.slug})` : ''} [${b.category}]`);
+ if (t.active_blockers.length || t.unresolved.rows) console.log(` drill down: ${t.drill_down.join(' ')}`);
+ }
if (rendered.next) console.log(` Next: ${rendered.next.command ?? rendered.next.argv?.join(' ')}\n Why: ${rendered.next.why}`);
else console.log(' Next: nothing; the source is synced and holds nothing.');
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 204bf24630..6ec4e711d9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -542,6 +542,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.209.0', text: 'Publishing a page now writes its timeline rows, fact rows, fact field refreshes and take resolutions in a few set-based statements (one per 500 rows) instead of one statement per row, and `insertFacts` inserts in multi-row chunks for every caller. A large page no longer needs thousands of round trips, so it publishes inside `persistence.publication_ceiling_ms` behind a transaction-mode pooler with pipelining off. A projection that takes 30 s or more logs `[persistence] phase=publication reason=slow_projection` with its row counts and per-step milliseconds.' },
{ since: '0.60.209.0', text: 'Before a publish opens its transaction, the consumer now commits one claim renewal that stamps the request `publishing` and leases it for the publication ceiling plus its grace, and stops renewing until the publish ends. A long publish no longer reads as a lapsed claim, so `gbrain sync` no longer stops `drain_stalled` with `owner_missing` while the publish is still working; a publish past the ceiling still reports `publication_overdue`. An owner that crashes mid-publish now holds its head until that lease runs out (the ceiling plus about 70 s) rather than 30 s.' },
{ since: '0.60.216.0', text: 'A managed sync now re-freezes, by itself, a page that was cancelled or refused only because another page of the same sync did not commit (a knock-on), under `sync.holds=fail` too and without `--retry-failed`; an operator cancel is never re-frozen. The re-freeze is bounded by `sync.knock_on_refreeze_limit` (per page, default 3, 0 turns it off) and `sync.knock_on_run_limit` (per sync invocation, default 25); past them the run stops `knock_on_exhausted` naming the root request. A checkpoint refused by such a receipt, or by one at an index the run passed without a commit, is re-assessed on every resume and commits without rediscovering the manifest. A "cursor changed" refusal now records its cause: `run_replaced` (superseded, not failed), `window_dropped` (a knock-on), or `outside_fence` (a coordination fault that needs a person). `--retry-failed` no longer silently does nothing when the old run still has open requests: it returns `partial` with `retryWait` naming the request. `gbrain sync status --json` adds `last_error.root_cause`, `cursors` (every live cursor of the source) and `checkpoint_blockers`, and shows the cursor its recorded failure belongs to. The write owner must run this release for the recovery to apply.' },
+ // #6650 (writer terminal-state visibility). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.216.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.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 357bcedf71..d92c606e8f 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -18,7 +18,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],
- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -73,14 +73,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--full', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
@@ -110,7 +110,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -124,11 +124,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/config.ts b/src/core/config.ts
index cba31a1939..003bc06ac9 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1771,7 +1771,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
'persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts
'persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts', 'persistence.preparation_deadlines', // #6278: persistence/preparation-budget.ts, switches.ts
- 'persistence.publication_ceiling_ms', // #6405: persistence/sync-drain.ts (in-pass publication ceiling)
+ 'persistence.publication_ceiling_ms', 'persistence.terminal_failures.window_days', 'persistence.terminal_failures.spike_factor', 'persistence.terminal_failures.spike_min', // #6405: persistence/sync-drain.ts (in-pass publication ceiling); #6650: persistence/terminal-failures.ts
'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)
// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 9b03e6847b..022f79e05c 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -264,6 +264,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'persistence_request_indexes',
'persistence_write_stall',
'lost_caller_writes',
+ // #6650: terminal write receipts that block work or are a gbrain-defect class (doctor/checks/persistence-requests.ts).
+ 'persistence_terminal_failures',
'stale_frontmatter_keys',
'managed_sync_not_moving',
'persistence_session_timeouts',
diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.ts
index 4d762d85e9..171656189b 100644
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@ -113,11 +113,22 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: W
// #5929: a trusted local reader learns when the owner that ran the attempt is on another build.
const mismatch = ctx.remote === false ? (await import('../persistence/publication-failure.ts')).ownerBuildMismatch(row.error_detail, (await import('../../version.ts')).VERSION) : null;
const withdrawn = (await import('../facts/withdrawal.ts')).withdrawnFromDetail(row.error_detail);
+ const diagnostic = isWriteErrorCode(row.error_code) ? writeFailureDiagnostic(row.error_code, row.error_message) : null;
+ // #6650: the classification the receipt's own columns support, with the structured next step (verify is read-only).
+ const terminal = isTerminalOrRecovering(row) ? (await import('../persistence/terminal-classify.ts')).classifyTerminal({ request_id: row.request_id, source_id: row.source_id,
+ slug: row.slug, operation: row.operation, state: row.state, error_code: row.error_code, error_detail: row.error_detail ?? null, recovery: row.recovery,
+ blocked_reason: row.blocked_reason, compacted: row.compacted, publication_started: row.publication_started, error_message: row.error_message,
+ intent_kind: typeof row.intent?.kind === 'string' ? row.intent.kind : null, build: (row as { admitter_version?: string | null }).admitter_version ?? null }) : null;
+ const { cliRenderContext, renderAction } = await import('../agent-output.ts');
+ const render = ctx.remote === false ? cliRenderContext() : { transport: 'stdio' as const, isCallable: () => false, preapproved: () => false };
return {
...publicWriteReceipt(receiptFor(row, facts)),
operation: row.operation, source_id: row.source_id, slug: row.slug,
...(mismatch ? { owner_build: mismatch } : {}),
- ...(isWriteErrorCode(row.error_code) ? { write_error: row.error_code, write_error_message: writeFailureDiagnostic(row.error_code, row.error_message).message } : {}),
+ ...(diagnostic ? { write_error: row.error_code, write_error_message: diagnostic.message, write_error_reason: diagnostic.reason, suggestion: diagnostic.suggestion } : {}),
+ ...(terminal ? { diagnosis: { category: terminal.category, code: terminal.code, class: terminal.class, safe_actions: terminal.safe_actions, needs_human: terminal.needs_human,
+ ...(terminal.human_reason ? { human_reason: terminal.human_reason } : {}), escalate: terminal.escalate, historical: terminal.historical,
+ fix: renderAction(terminal.action, render) } } : {}),
...(withdrawn ? { withdrawn } : {}),
...(checkpoint ? { detail: checkpoint.detail, suggestion: checkpoint.suggestion, docs: checkpoint.docs } : {}),
effects: (await publicEffectsForRequest(ctx.engine, row.id)).map(effect => {
@@ -127,6 +138,11 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: W
};
}
+/** A receipt the terminal classifier reads: ended without committing, or still holding a publication recovery record. */
+function isTerminalOrRecovering(row: WriteRequest): boolean {
+ return ['failed', 'conflict', 'cancelled'].includes(row.state) || (row.state === 'committed' && row.recovery != null);
+}
+
function requiredRequestId(value: unknown): string {
const id = parseWriteRequestId(value);
if (!id) throw opError('invalid_params', 'request_id is required.', 'Pass the request_id you sent with the write, or the one its receipt shows; list_write_requests shows recent ones.');
diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.ts
index 66aa917e4f..60cee8baec 100644
--- a/src/core/persistence/admin-contract.ts
+++ b/src/core/persistence/admin-contract.ts
@@ -10,7 +10,18 @@ export const PERSISTENCE_ADMIN_OPERATIONS = [
// #5575 DX-2/ENG-15: owner trust actions while a resident serve holds the brain (trust/owner-ipc.ts).
'trust_read', 'trust_preview', 'trust_apply',
] as const;
-export type PersistenceAdminOperation = typeof PERSISTENCE_ADMIN_OPERATIONS[number];
+/**
+ * #6650: administration added after the capability list froze. A client validates every entry of a resident owner's
+ * `administration` list against its own known set and drops the owner when one is unknown, so a new operation is never
+ * added there: the owner advertises it in `administration_extensions`, which older clients ignore, and a client calls
+ * one only when the owner lists it.
+ */
+export const PERSISTENCE_ADMIN_EXTENSIONS = ['writer_failures'] as const;
+export type PersistenceAdminExtension = typeof PERSISTENCE_ADMIN_EXTENSIONS[number];
+export type PersistenceAdminOperation = typeof PERSISTENCE_ADMIN_OPERATIONS[number] | PersistenceAdminExtension;
export function isPersistenceAdminOperation(value: unknown): value is PersistenceAdminOperation {
- return typeof value === 'string' && (PERSISTENCE_ADMIN_OPERATIONS as readonly string[]).includes(value);
+ return typeof value === 'string' && ((PERSISTENCE_ADMIN_OPERATIONS as readonly string[]).includes(value) || (PERSISTENCE_ADMIN_EXTENSIONS as readonly string[]).includes(value));
+}
+export function isPersistenceAdminExtension(value: unknown): value is PersistenceAdminExtension {
+ return typeof value === 'string' && (PERSISTENCE_ADMIN_EXTENSIONS as readonly string[]).includes(value);
}
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index d351b28f9b..7b8952531b 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -103,6 +103,25 @@ export const CLAIM_BEFORE_ACTIVATION_NOTICE = 'Persistence is not activated. Aft
+ 'file-writing maintenance) refuse while the checkout is managed. Stop older writers, review gbrain sources writer status, '
+ 'then activate deliberately.';
+/** #6650: `sources writer failures` options, validated with the usage each one takes. */
+function writerFailuresQuery(sourceId: string, params: Record<string, unknown>): import('./terminal-failures.ts').TerminalFailureQuery {
+ const bad = (key: string, pattern: RegExp) => params[key] !== undefined && (typeof params[key] !== 'string' || !pattern.test(params[key] as string));
+ if (bad('state', /^(all|unresolved)$/)) throw invalid('Invalid --state value.', 'Pass --state all to include resolved and historical receipts, or leave it out for the unresolved ones.');
+ if (bad('group_by', /^category$/)) throw invalid('Invalid --group-by value.', 'Pass --group-by category (groups on code, origin and category), or leave it out to list receipts.');
+ if (bad('since', /^[1-9]\d{0,3}d$/)) throw invalid('Invalid --since value.', 'Pass --since as whole days, e.g. --since 7d; the window is clamped to persistence.receipt_retention_days.');
+ if (bad('before', /^\d{1,19}$/)) throw invalid('Invalid --before value.', 'Pass --before exactly as the previous page\'s next_cursor.');
+ if (bad('code', /^[a-z][a-z0-9_]{0,63}$/)) throw invalid('Invalid --code value.', 'Pass --code as a snake_case code a group names, e.g. --code storage_error.');
+ if (bad('origin', /^[a-z][a-z0-9_]{0,63}$/)) throw invalid('Invalid --origin value.', 'Pass --origin as an origin a group names, or none for receipts with no recorded origin.');
+ if (bad('category', /^[a-z][a-z_]{0,63}$/)) throw invalid('Invalid --category value.', 'Pass --category as a category a group names, e.g. --category knock_on.');
+ if (params.limit !== undefined && !(typeof params.limit === 'number' && Number.isInteger(params.limit) && params.limit >= 1 && params.limit <= 100)) {
+ throw invalid('Invalid --limit value.', 'Pass --limit as a whole number from 1 to 100 (default 20).');
+ }
+ const p = params as { state?: 'all' | 'unresolved'; group_by?: string; since?: string; limit?: number; before?: string; code?: string; origin?: string; category?: string };
+ return { sourceId, ...(p.state ? { state: p.state } : {}), ...(p.group_by ? { groupBy: 'category' as const } : {}), ...(p.since ? { sinceDays: Number(p.since.slice(0, -1)) } : {}),
+ ...(p.limit !== undefined ? { limit: p.limit } : {}), ...(p.before ? { before: p.before } : {}), ...(p.code ? { code: p.code } : {}), ...(p.origin ? { origin: p.origin } : {}),
+ ...(p.category ? { category: p.category } : {}) };
+}
+
const transferStatusFix = (sourceId: string) =>
readFix(`Shows source ${sourceId}'s owner binding and prepared transfer, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });
@@ -206,6 +225,14 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
refederate:params.refederate as boolean|undefined,confirmDestructive:params.confirm_destructive as boolean|undefined,dryRun:params.dry_run===true,
remoteUrl:params.remote_url as string|undefined,createDirectory:params.create_directory as boolean|undefined,expiredOnly:params.expired_only as boolean|undefined});
}
+ if (operation === 'writer_failures') {
+ keys(params, ['source_id', 'state', 'group_by', 'since', 'limit', 'before', 'code', 'origin', 'category']);
+ const sourceId = source(params.source_id);
+ const [known] = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);
+ if (!known) throw invalid(`No active source ${sourceId}.`, 'Name an active source; archived sources are not inspected.', sourcesListFix('Lists the active source ids, read-only.'));
+ const { readTerminalFailures } = await import('./terminal-failures.ts');
+ return { ...await readTerminalFailures(engine, writerFailuresQuery(sourceId, params)) };
+ }
if (operation === 'writer_status') {
keys(params, ['source_id', 'probe']);
bool(params, 'probe');
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index bcdf5be683..d1aeb2c8ab 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -7,7 +7,7 @@ import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import { resolveSocketPathForConfig, socketHasLiveListener } from '../context/resolve-ipc.ts';
import { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt } from './types.ts';
-import { isPersistenceAdminOperation, PERSISTENCE_ADMIN_OPERATIONS, type PersistenceAdminOperation } from './admin-contract.ts';
+import { isPersistenceAdminExtension, isPersistenceAdminOperation, PERSISTENCE_ADMIN_EXTENSIONS, PERSISTENCE_ADMIN_OPERATIONS, type PersistenceAdminExtension, type PersistenceAdminOperation } from './admin-contract.ts';
import { claimLocalIpcBinding, isWindowsIpcPipe, prepareLocalIpcPath } from '../context/ipc-path.ts';
export const PERSISTENCE_IPC_VERSION = 1;
@@ -65,8 +65,10 @@ export interface PersistenceIpcCapabilities {
brain_id: string;
operations: readonly PersistenceIpcOperation[];
max_frame_bytes: number;
- /** Optional for protocol compatibility with owners predating local administration. */
+ /** Optional for protocol compatibility with owners predating local administration. Frozen: new operations go in `administration_extensions`. */
administration?: readonly PersistenceAdminOperation[];
+ /** #6650: administration added after `administration` froze; older clients ignore the key, a client keeps only the entries it knows. */
+ administration_extensions?: readonly PersistenceAdminExtension[];
/** #5232: the owner honors `write_wait_ms` on operation requests. */
write_wait?: true;
}
@@ -231,7 +233,7 @@ export async function startPersistenceIpcServer(
socket.end(responseFrame({ version: 1, ok: true, result: {
version: 1, brain_id: provider.brainId, operations: PERSISTENCE_IPC_OPERATIONS,
max_frame_bytes: PERSISTENCE_IPC_MAX_BYTES,
- ...(provider.administer ? { administration: PERSISTENCE_ADMIN_OPERATIONS } : {}),
+ ...(provider.administer ? { administration: PERSISTENCE_ADMIN_OPERATIONS, administration_extensions: PERSISTENCE_ADMIN_EXTENSIONS } : {}),
write_wait: true,
} satisfies PersistenceIpcCapabilities }));
return;
@@ -393,7 +395,15 @@ export async function requestPersistenceCapabilities(socketPath: string, timeout
|| value.max_frame_bytes < 1 || value.max_frame_bytes > PERSISTENCE_IPC_MAX_BYTES) {
throw new PersistenceIpcTransportError(false);
}
- return value as unknown as PersistenceIpcCapabilities;
+ // #6650: an extension list is advisory: a malformed one is dropped, an entry this build does not know is ignored.
+ const extensions = Array.isArray(value.administration_extensions) ? value.administration_extensions.filter(isPersistenceAdminExtension) : undefined;
+ const { administration_extensions: _ignored, ...rest } = value;
+ return { ...rest, ...(extensions ? { administration_extensions: extensions } : {}) } as unknown as PersistenceIpcCapabilities;
+}
+
+/** Whether a resident owner's capabilities include an administration operation (a frozen one or an extension). */
+export function ownerAdministers(capability: Pick<PersistenceIpcCapabilities, 'administration' | 'administration_extensions'>, operation: PersistenceAdminOperation): boolean {
+ return isPersistenceAdminExtension(operation) ? capability.administration_extensions?.includes(operation) === true : capability.administration?.includes(operation) === true;
}
function count(value: unknown): value is number {
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index c6b6809677..35b39af5f6 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -16,7 +16,7 @@ import {
isPersistenceIpcMutation, isPersistenceIpcOperation, isPersistenceIpcRegistration,
persistenceSocketPathForConfig, requestPersistenceCapabilities, requestPersistenceOperation,
PersistenceIpcTransportError, type PersistenceIpcCapabilities, type PersistenceIpcRegistration,
- requestPersistenceAdministration,
+ requestPersistenceAdministration, ownerAdministers,
} from './ipc.ts';
import type { PersistenceAdminOperation } from './admin-contract.ts';
import { currentCliWriteWait, replayWhilePending, writeExchangeBudget } from './write-wait.ts';
@@ -114,7 +114,7 @@ export async function maybeDelegateLocalAdministration(
const socketPath = persistenceSocketPathForConfig(config);
if (!socketPath) throw noDiscoveryPath('The PGLite owner has no persistence discovery path.', holder);
const capability = await residentOwnerCapabilities(socketPath, config.database_path, holder, options.startupWaitMs);
- if (!capability.administration?.includes(operation)) throw new OperationError('owner_unavailable',
+ if (!ownerAdministers(capability, operation)) throw new OperationError('owner_unavailable',
'The running owner does not support this local administration command.', 'Upgrade and restart the owner before administering this brain.');
const registration = readPersistenceCliRegistration(capability.brain_id);
const result = await requestPersistenceAdministration(socketPath, {
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index ed10088c00..16de09cc79 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -87,9 +87,33 @@ export interface SyncStatus {
checkpoint_blockers?: Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean; knock_on: boolean }>;
/** #6643: every managed-sync cursor of the source under its current incarnation, newest first (at most 20). */
cursors: SyncStatusCursor[];
+ /** #6650: the source's terminal write receipts that did not commit, summarized (`terminal-failures.ts`); `unknown` when the bounded read timed out. */
+ terminal_failures: SyncTerminalSummary;
next: Action | null;
}
+export type SyncTerminalSummary = { status: 'unknown'; reason: string } | {
+ status: 'ok'; window_days: number; active_blockers: Array<{ kind: 'recovery' | 'checkpoint'; request_id: string; slug?: string; category: string }>;
+ unresolved: { rows: number; distinct_slugs: number; distinct_intents: number; oldest_age_seconds: number | null };
+ historical_rows: number; new_last_24h: number; defects: number;
+ categories: Array<{ category: string; code: string; origin: string | null; rows: number; unresolved: number }>; drill_down: string[];
+};
+
+/** #6650: the source's slice of the terminal-failure summary, with PR A's checkpoint blockers passed in rather than recomputed. */
+async function terminalSummary(engine: BrainEngine, sourceId: string, blockers: SyncStatus['checkpoint_blockers']): Promise<SyncTerminalSummary & { recovery_next?: Action }> {
+ const { readTerminalFailureSummary } = await import('./terminal-failures.ts');
+ const summary = await readTerminalFailureSummary(engine, { sourceIds: [sourceId], checkpointBlockers: new Map([[sourceId, blockers ?? []]]) });
+ if (summary.status === 'unknown') return { status: 'unknown', reason: summary.reason };
+ const s = summary.sources[0];
+ const recovery = s?.active_blockers.find(b => b.kind === 'recovery');
+ return { status: 'ok', window_days: summary.window_days, ...(recovery ? { recovery_next: recovery.action } : {}),
+ active_blockers: (s?.active_blockers ?? []).map(b => ({ kind: b.kind, request_id: b.request_id, ...(b.slug ? { slug: b.slug } : {}), category: b.category })),
+ unresolved: { rows: s?.unresolved.rows ?? 0, distinct_slugs: s?.unresolved.distinct_slugs ?? 0, distinct_intents: s?.unresolved.distinct_intents ?? 0, oldest_age_seconds: s?.unresolved.oldest_age_seconds ?? null },
+ historical_rows: s?.historical_rows ?? 0, new_last_24h: s?.new_last_24h ?? 0, defects: (s?.defects ?? []).reduce((sum, d) => sum + d.rows, 0),
+ categories: (s?.categories ?? []).slice(0, 10).map(c => ({ category: c.category, code: c.code, origin: c.origin, rows: c.rows, unresolved: c.unresolved })),
+ drill_down: ['gbrain', 'sources', 'writer', 'failures', sourceId, '--group-by', 'category', '--json'] };
+}
+
interface CursorHeader { runId: string; index: number; total: number; target: string | null; done?: boolean;
progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };
processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'];
@@ -197,10 +221,26 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`
: `The cursor stands at ${header!.index}/${header!.total}; the same command resumes it against the frozen manifest.` }
: null;
+ const blockers = await checkpointBlockers(engine, header);
+ // #6650: a receipt still holding a recovery record holds its root, so a source with nothing else to do names it as `next`.
+ const { recovery_next, ...terminal } = await terminalSummary(engine, sourceId, blockers.checkpoint_blockers);
return { source_id: sourceId, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
committed_last_10m: Number(committed?.n ?? 0), ...estimate, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
- resume_argv: resume, ...(await checkpointBlockers(engine, header)), cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures), next };
+ resume_argv: resume, ...blockers, cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures),
+ terminal_failures: terminal, next: next ?? recovery_next ?? null };
+}
+
+/**
+ * #6650: `checkpoint_blockers` of the cursor `readSyncStatus` would show for the source, without the rest of the status
+ * (doctor's terminal-failure summary reuses them; it never recomputes the checkpoint's rule).
+ */
+export async function readCheckpointBlockers(engine: BrainEngine, sourceId: string): Promise<NonNullable<SyncStatus['checkpoint_blockers']>> {
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);
+ if (!source) return [];
+ const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');
+ const selected = await cursorHeader(engine, sourceId, source.incarnation, failures[0]?.cursor_key ?? null);
+ return (await checkpointBlockers(engine, selected?.header ?? null)).checkpoint_blockers ?? [];
}
/**
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
new file mode 100644
index 0000000000..ca7f53e705
--- /dev/null
+++ b/src/core/persistence/terminal-classify.ts
@@ -0,0 +1,310 @@
+/**
+ * #6650 (L3): the read-time classification of a terminal write request that did not commit, so an operator sees what a
+ * pile of failed, conflicted and cancelled receipts means and what clears it, without a persisted fix or a new table.
+ *
+ * `classifyTerminal(row)` reads only what survives receipt compaction (`compactWriteReceipts` nulls the intent and the
+ * message): `error_code`, `error_detail` (its `origin`, `reason` and `cause`), `operation`, `state`, `recovery`,
+ * `blocked_reason` and `compacted`. Every maintenance kind is stored as `submit_job`, so the intent's kind is used only
+ * when it is still there (the legacy knock-on texts need it, as `isSyncKnockOn` does). Codes that cover several causes
+ * (`source_changed`, `storage_error`) are routed by their recorded origin or reason; when a legacy receipt carries
+ * neither, the verdict is `diagnosis_required` with a read-only inspection, never a guessed fix.
+ *
+ * The verdict speaks the vocabulary of `gbrain sync status` (`class` / `safe_actions` / `needs_human` / `escalate`,
+ * `sync-fault-class.ts`) plus an `Action` whose `verify` is read-only. It classifies history only: whether a row blocks
+ * something right now (a checkpoint blocker, a recovery record holding its root) is decided by the reader
+ * (`terminal-failures.ts`) from PR A's `checkpoint_blockers` and the head blocker's `request_recovery`, never here.
+ *
+ * `supersessionSql` is the one rule for "a later request on the same page made this one moot", extracted from
+ * `gbrain repair failed-writes` (`disposition`), which uses it unchanged; `terminal-failures.ts` uses it to label a
+ * row `superseded` / `already_written` / `duplicate`, and anything without that evidence stays `unknown`.
+ */
+import type { Action } from '../agent-output.ts';
+import { CODES } from '../error-registry.ts';
+import { compareVersions } from '../migration-ledger.ts';
+import { classifySyncFault, SYNC_FAULT_TABLE, type SyncFaultClass, type SyncSafeAction } from './sync-fault-class.ts';
+import { isSyncKnockOn, knockOnRoot, SYNC_CURSOR_FENCE_ORIGIN, SYNC_KNOCK_ON_ORIGIN, cursorFenceCause, syncKnockOnSql } from './sync-knock-on.ts';
+import { writeFailureDiagnostic } from './verb-errors.ts';
+
+export type TerminalCategory =
+ | 'recovery_pending' | 'recovery_blocked'
+ | 'knock_on' | 'run_replaced' | 'outside_fence'
+ | 'operator_cancelled' | 'caller_conflict' | 'file_conflict'
+ | 'writer_guard' | 'database_refusal' | 'owner_exception' | 'legacy_publication_refusal'
+ | 'sync_fault' | 'transport' | 'caller_refusal' | 'gbrain_defect' | 'diagnosis_required';
+
+/** The receipt columns the classifier reads; every one but `intent_kind` and `error_message` survives compaction. */
+export interface TerminalInput {
+ request_id?: string;
+ source_id: string;
+ slug: string;
+ operation: string;
+ state: string;
+ error_code: string | null;
+ error_detail?: object | null;
+ recovery: unknown;
+ blocked_reason: string | null;
+ compacted: boolean;
+ publication_started?: boolean | null;
+ /** The build that ran the failed attempt (`error_detail.attempt.consumer_version`), else the admitting build. */
+ build?: string | null;
+ /** Nulled by compaction; used only for the legacy knock-on texts and the message-routed diagnostics. */
+ intent_kind?: string | null;
+ error_message?: string | null;
+ /** A reader that computed `terminalKnockOnSql` passes its answer, so the SQL twin and this verdict cannot disagree. */
+ knock_on?: boolean;
+}
+
+export interface TerminalVerdict {
+ category: TerminalCategory;
+ /** The code the verdict is keyed on: the row's `error_code`, or the refinement its origin names. */
+ code: string;
+ origin: string | null;
+ class: SyncFaultClass;
+ safe_actions: SyncSafeAction[];
+ needs_human: boolean;
+ human_reason?: string;
+ escalate: string;
+ /** A gbrain defect class: doctor warns on an unresolved one whatever the trend. */
+ defect: boolean;
+ /** The release that fixed this class, when one did; a row from an older build is historical. */
+ fixed_in: string | null;
+ historical: boolean;
+ /** The request a knock-on waited on, when its canceller recorded it. */
+ root_request_id?: string;
+ action: Action;
+}
+
+/** #6650: classes a release fixed. A row written by an older build is history: it does not warn. */
+export const TERMINAL_FIXED_IN = {
+ // #6643: the run re-freezes its own knock-ons and the checkpoint no longer waits on them.
+ knock_on: '0.60.216.0',
+ // #5974/#5982: a guard P0001 is classified (writer_coordinator_required, origin database_guard) and the misread is fixed;
+ // an unclassified "Publication failed (P0001)" receipt can only come from an older build.
+ legacy_publication_refusal: '0.60.40.0',
+} as const satisfies Partial<Record<TerminalCategory, string>>;
+
+/** The connection-loss texts `classifySyncFault` reads as `connection_lost`; POSIX-compatible, so readers match it in SQL (`~*`). */
+export const CONNECTION_MESSAGE_PATTERN = 'ECONN|ETIMEDOUT|EPIPE|connection.*closed|CONNECTION_ENDED';
+/** The prefix of an unclassified database refusal written before #5974. */
+export const LEGACY_PUBLICATION_PREFIX = 'Publication failed (P0001)';
+
+const DEFECTS = new Set<TerminalCategory>(['outside_fence', 'writer_guard', 'database_refusal', 'owner_exception', 'gbrain_defect']);
+const FAULT_CODES = new Set(SYNC_FAULT_TABLE.map(rule => rule.code));
+const escalateOf = (code: string) => SYNC_FAULT_TABLE.find(rule => rule.code === code)?.escalate ?? 'always';
+
+const statusArgv = (sourceId: string) => ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'];
+const failuresArgv = (sourceId: string) => ['gbrain', 'sources', 'writer', 'failures', sourceId, '--json'];
+/** The read-only drill-down an operator re-runs to see the class clear. */
+export function terminalVerifyArgv(sourceId: string): string[] { return failuresArgv(sourceId); }
+/** The per-receipt read-only inspection (the receipt with its diagnosis). */
+export function terminalInspectArgv(requestId: string): string[] { return ['gbrain', 'write-request', requestId, '--json']; }
+
+function syncRetry(sourceId: string, why: string): Action {
+ return { argv: ['gbrain', 'sync', '--source', sourceId, '--no-pull', '--retry-failed', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why,
+ verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] }, docs: 'docs/guides/sync-unblock-runbook.md' };
+}
+function inspect(sourceId: string, why: string, userMessage?: string): Action {
+ return { argv: statusArgv(sourceId), consent: [], actor: userMessage ? 'host_admin' : 'agent', requires_exclusive: false, why,
+ ...(userMessage ? { user_message: userMessage } : {}), verify: { argv: failuresArgv(sourceId) }, docs: 'docs/guides/troubleshooting.md#terminal-write-failures' };
+}
+
+function build(input: TerminalInput): string | null {
+ const attempt = (input.error_detail as { attempt?: { consumer_version?: unknown } } | null | undefined)?.attempt?.consumer_version;
+ const value = typeof attempt === 'string' ? attempt : input.build ?? null;
+ return value && /^\d+\.\d+\.\d+(\.\d+)?$/.test(value) ? value : null;
+}
+function stringField(detail: Record<string, unknown> | null | undefined, key: string): string | null {
+ const value = detail?.[key];
+ return typeof value === 'string' ? value : null;
+}
+
+type Partial_ = Omit<TerminalVerdict, 'defect' | 'fixed_in' | 'historical' | 'escalate'> & { escalate?: string };
+
+/** The read-time verdict for one terminal receipt that did not commit; null for a committed receipt with no recovery record. */
+export function classifyTerminal(input: TerminalInput): TerminalVerdict | null {
+ if (input.state === 'committed' && !input.recovery) return null;
+ const verdict = route(input);
+ const fixedIn = (TERMINAL_FIXED_IN as Partial<Record<TerminalCategory, string>>)[verdict.category] ?? null;
+ const ran = build(input);
+ const historical = fixedIn !== null && (verdict.category === 'legacy_publication_refusal' || (ran !== null && compareVersions(ran, fixedIn) < 0));
+ return { ...verdict, escalate: verdict.escalate ?? escalateOf(verdict.code), defect: DEFECTS.has(verdict.category), fixed_in: fixedIn, historical };
+}
+
+function fromTable(category: TerminalCategory, code: string, origin: string | null, action: Action, detail?: string | null, message?: string | null): Partial_ {
+ const v = classifySyncFault({ code, detail, message });
+ return { category, code: detail && FAULT_CODES.has(detail) ? detail : code, origin, class: v.class, safe_actions: v.safe_actions, needs_human: v.needs_human,
+ ...(v.human_reason ? { human_reason: v.human_reason } : {}), action };
+}
+
+function diagnosis(input: TerminalInput, code: string, origin: string | null, why: string): Partial_ {
+ return { category: 'diagnosis_required', code, origin, class: 'systemic', safe_actions: ['none'], needs_human: true,
+ human_reason: `${why} The receipt does not record enough to name a fix; inspect it and the writer before acting.`,
+ escalate: 'always: a person reads the writer status and the receipt',
+ action: inspect(input.source_id, `${why} Writer status and the receipt are read-only; nothing is guessed.`) };
+}
+
+function route(input: TerminalInput): Partial_ {
+ const code = input.error_code ?? 'unknown';
+ const detail = (input.error_detail ?? null) as Record<string, unknown> | null;
+ const origin = stringField(detail, 'origin');
+ const reason = stringField(detail, 'reason');
+ const source = input.source_id;
+ if (input.recovery) {
+ const blocked = input.blocked_reason === 'unexpected_staging_bytes' || input.blocked_reason === 'unexpected_file_bytes';
+ return blocked
+ ? { category: 'recovery_blocked', code: 'recovery_required', origin, class: 'systemic', safe_actions: ['none'], needs_human: true,
+ human_reason: `The publication recovery record of this request is blocked (${input.blocked_reason}): a file it staged or published changed outside gbrain, so its root stays held until a person inspects the bytes.`,
+ escalate: 'always: the bytes on disk differ from what the recovery record expects',
+ action: inspect(source, 'Writer status names the held root and the recovery record, read-only.', `Inspect the file named by gbrain sources writer status --source ${source} --json on the brain host; restore the expected bytes or report it.`) }
+ : { category: 'recovery_pending', code: 'recovery_required', origin, class: 'systemic', safe_actions: ['retry'], needs_human: false,
+ escalate: 'the record is still there after an owner pass (writer status then names a blocked_reason)',
+ action: { argv: ['gbrain', 'sync', '--source', source, '--no-pull', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'This request holds a publication recovery record, which holds every queued write on its root (head blocker request_recovery). An owner pass on this host '
+ + 'finishes it: the sync starts one, cleans the staged files and clears the record (a gbrain serve that owns the root does the same).',
+ verify: { argv: failuresArgv(source) }, docs: 'docs/guides/troubleshooting.md#terminal-write-failures' } };
+ }
+ const knockOn = input.knock_on ?? knockOnSafe(input);
+ if (knockOn) {
+ const root = knockOnRoot({ error_detail: detail });
+ return { ...fromTable('knock_on', code, origin, syncRetry(source, `This page only waited on another page of the same sync${root ? ` (request ${root})` : ''}; a sync re-freezes it under a fresh request.`), 'knock_on'),
+ ...(root ? { root_request_id: root } : {}) };
+ }
+ if (origin === SYNC_CURSOR_FENCE_ORIGIN) {
+ const cause = cursorFenceCause(detail);
+ if (cause === 'outside_fence') return fromTable('outside_fence', code, origin, inspect(source, 'A sync request published outside the cursor that admitted it; writer status and sync status list the drains, read-only.',
+ `Stop the extra drain of source ${source} (gbrain autopilot pause), then report the fence snapshot gbrain sync status --source ${source} --json shows.`), 'outside_fence');
+ if (cause === 'run_replaced') return fromTable('run_replaced', code, origin, syncRetry(source, 'Another run of the source replaced this one and covers its pages; the current sync finishes the source.'), 'run_replaced');
+ }
+ if (code === 'cancelled' && input.state === 'cancelled') {
+ return { category: 'operator_cancelled', code, origin, class: 'page', safe_actions: ['none'], needs_human: false,
+ escalate: 'never: a caller or operator cancelled it before publication',
+ action: { argv: terminalInspectArgv(input.request_id ?? '<request_id>'), consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Cancelled before publication by its caller or an operator; nothing was written. The receipt is read-only history.' } };
+ }
+ if (code === 'writer_coordinator_required' && origin === 'database_guard') {
+ return { category: 'writer_guard', code, origin, class: 'systemic', safe_actions: ['none'], needs_human: true,
+ human_reason: 'The managed-writer database guard refused the write: a gbrain defect, a schema change by another tool, or two gbrain builds sharing the database.',
+ escalate: 'always', action: { ...inspect(source, 'Writer status --probe names the table, operation, guard branch and executing build of each refusal, read-only.',
+ 'Read recent_failures[].error_detail from gbrain sources writer status --probe --json on the brain host, check doctor managed_guard_schema_drift, then retry the write with a new request id (gbrain repair failed-writes replays caller writes).'),
+ argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--probe', '--json'] } };
+ }
+ if (origin === 'owner_exception') {
+ return { category: 'owner_exception', code, origin, class: 'systemic', safe_actions: ['upgrade'], needs_human: true,
+ human_reason: 'The owner raised an unexpected exception while running this write: a gbrain defect.',
+ escalate: 'always: report the error class and frame writer status shows',
+ action: inspect(source, 'Writer status names the error class, errno, frame and the build that ran the attempt, read-only.',
+ 'Report the owner exception (gbrain sources writer status --json on the brain host names it) with the gbrain version; upgrade when a fix ships.') };
+ }
+ if (code === 'storage_error' || code === 'writer_coordinator_required') {
+ if (reason === 'graduation_in_progress') return fromTable('transport', code, origin, syncRetry(source, 'The engine-graduation fence refused writes while the brain moved; retry once gbrain migrate --status --json reports it finished.'), 'graduation_in_progress');
+ if (reason === 'attribution_unclassified_table' || reason === 'trust_unclassified_table') {
+ return { category: 'database_refusal', code, origin, class: 'systemic', safe_actions: ['upgrade'], needs_human: true,
+ human_reason: `A gbrain stamp trigger met a table it is not built for (${reason}): two gbrain builds share this database.`, escalate: 'always',
+ action: inspect(source, 'Writer status lists the admitter and consumer build of each host, read-only.', 'Upgrade every gbrain process that shares this database to one release, restart them, then retry the write.') };
+ }
+ if (origin === 'database_trigger' || origin === 'database' || origin === 'database_guard') {
+ return diagnosis(input, code, origin, `A database trigger refused the write (${stringField(detail, 'raiser') ?? 'unnamed raiser'}${reason ? `, reason ${reason}` : ''}).`);
+ }
+ if (!detail && input.error_message?.startsWith(LEGACY_PUBLICATION_PREFIX)) {
+ return { category: 'legacy_publication_refusal', code, origin: null, class: 'systemic', safe_actions: ['none'], needs_human: false,
+ escalate: 'never: only builds before refusals were classified wrote this receipt',
+ action: { argv: ['gbrain', 'repair', 'failed-writes', '--source', source], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'A database refusal recorded before refusals were classified (and before the writer-guard misread was fixed). The read-only preview lists caller writes it can replay.',
+ verify: { argv: failuresArgv(source) }, docs: 'docs/guides/repair.md#failed-writes' } };
+ }
+ if (input.error_message && new RegExp(CONNECTION_MESSAGE_PATTERN, 'i').test(input.error_message)) {
+ return fromTable('transport', code, origin, syncRetry(source, 'The database connection dropped during the write; nothing was committed.'), 'connection_lost', input.error_message);
+ }
+ return diagnosis(input, code, origin, `The write ended ${code} with no recorded origin${input.compacted ? ' (its receipt was compacted)' : ''}.`);
+ }
+ if (code === 'source_changed') {
+ const known = stringField(detail, 'reason') ?? (input.error_message ? writeFailureDiagnostic(code, input.error_message).reason : null);
+ if (!known || known === 'source_changed') return diagnosis(input, code, origin, `The write was refused source_changed with no recorded cause${input.compacted ? ' (its receipt was compacted)' : ''}.`);
+ if (known === 'file_database_drift' || known === 'canonical_path_occupied' || known === 'unbound_source') {
+ return { category: 'file_conflict', code, origin: origin ?? known, class: 'page', safe_actions: ['reconcile'], needs_human: true,
+ human_reason: 'The page\'s Git file and its database copy differ; a person chooses which version wins.', escalate: 'always: the file and the database page diverge',
+ action: { argv: ['gbrain', 'sources', 'reconcile', source, input.slug, '--preview'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Previews both versions of the page and writes nothing; apply the resolved preview, then resubmit the write with a new request id.',
+ verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#source_changed' } };
+ }
+ if (known === 'source_binding_changed' || known === 'unsafe_file_target') return diagnosis(input, code, known, `The write was refused source_changed (${known}).`);
+ return fromTable('sync_fault', code, origin ?? known, syncRetry(source, `The file changed under the write (${known}); a sync imports the current bytes.`), known === 'pinned_git_worktree_conflict' ? known : 'source_changed');
+ }
+ if (code === 'revision_conflict' || code === 'page_identity_changed') {
+ return { category: 'caller_conflict', code, origin, class: 'page', safe_actions: ['retry'], needs_human: false, escalate: escalateOf(code),
+ action: { argv: ['gbrain', 'get', '--source', source, '--', input.slug], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The page changed after the caller read it. Read the current revision and resubmit against it with a new request id.',
+ verify: { argv: failuresArgv(source) } } };
+ }
+ if (FAULT_CODES.has(code)) return fromTable('sync_fault', code, origin, faultAction(code, input), null, input.error_message);
+ const entry = (CODES as Record<string, { class: string } | undefined>)[code];
+ if (!entry) return diagnosis(input, code, origin, `The write ended with code ${code}, which this build does not know.`);
+ if (entry.class === 'server') {
+ return { category: 'gbrain_defect', code, origin, class: 'systemic', safe_actions: ['upgrade'], needs_human: true,
+ human_reason: `The write ended ${code}, a server-side fault in gbrain.`, escalate: 'always',
+ action: inspect(source, 'Writer status names the build that ran the attempt, read-only.', `Report the ${code} receipt with the gbrain version (gbrain errors ${code} explains it); upgrade when a fix ships.`) };
+ }
+ if (entry.class === 'retryable' || entry.class === 'unavailable') {
+ return { category: 'transport', code, origin, class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'the same code after a rerun',
+ action: { argv: terminalInspectArgv(input.request_id ?? '<request_id>'), consent: [], actor: 'agent', requires_exclusive: false,
+ why: `A transient refusal (${code}); the caller resubmits with a new request id. The receipt is read-only.`, verify: { argv: failuresArgv(source) } } };
+ }
+ return { category: 'caller_refusal', code, origin, class: 'page', safe_actions: ['none'], needs_human: entry.class !== 'caller',
+ ...(entry.class !== 'caller' ? { human_reason: `The write was refused ${code} (${entry.class}); gbrain errors ${code} names who acts.` } : {}),
+ escalate: 'never: the caller saw the refusal and its fix',
+ action: { argv: terminalInspectArgv(input.request_id ?? '<request_id>'), consent: [], actor: 'agent', requires_exclusive: false,
+ why: `The caller's write was refused ${code} and the caller saw why; the receipt carries the diagnosis, read-only.`, verify: { argv: failuresArgv(source) } } };
+}
+
+function faultAction(code: string, input: TerminalInput): Action {
+ const v = classifySyncFault({ code });
+ if (v.safe_actions[0] === 'retry') return syncRetry(input.source_id, `The sync recorded ${code} (${v.class}); a rerun holds or retries it.`);
+ return inspect(input.source_id, `The write ended ${code}; writer status names what holds it, read-only.`, v.human_reason);
+}
+
+/** `isSyncKnockOn` over the classifier's columns: a compacted receipt counts by its typed marker alone. */
+function knockOnSafe(input: TerminalInput): boolean {
+ return isSyncKnockOn({ state: input.state as never, error_code: input.error_code, error_message: input.error_message ?? null, error_detail: (input.error_detail ?? null) as Record<string, unknown> | null,
+ recovery: null, publication_started: input.publication_started ?? false, intent: input.intent_kind ? { kind: input.intent_kind } : null });
+}
+
+/**
+ * The kind-aware knock-on predicate for a read spanning every request, row for row `isSyncKnockOn`: `syncKnockOnSql`
+ * matches the legacy texts on any row, while `isSyncKnockOn` takes a typed marker unless the kept intent names a non-sync
+ * kind, and a legacy text only on a sync page kind. Never NULL.
+ */
+export function terminalKnockOnSql(alias: string): string {
+ const a = alias, sync = `${a}.intent->>'kind' IN ('managed_sync_import','managed_sync_delete')`;
+ return `(${syncKnockOnSql(a)} AND CASE WHEN ${a}.error_detail->>'origin' = '${SYNC_KNOCK_ON_ORIGIN}' THEN (${a}.intent->>'kind' IS NULL OR ${sync}) ELSE COALESCE(${sync}, false) END)`;
+}
+
+/** Page removals: a later one supersedes any earlier write of the page. */
+export const PAGE_REMOVAL_OPERATIONS: readonly string[] = ['delete_page', 'purge_page'];
+
+/**
+ * The supersession rule of `gbrain repair failed-writes`, as a predicate over a candidate later request `c` of the
+ * failed request `r` (both `persistence_requests` aliases): the same intent committed, failed or still pending; a later
+ * page removal committed or pending; for a `put_page`, any later write committed or pending, or a later caller
+ * `put_page` that failed (the newer content). Literal strings only; NULL-safe for a compacted `c` (no intent).
+ */
+export function supersessionSql(r: string, c: string): string {
+ const removals = PAGE_REMOVAL_OPERATIONS.map(op => `'${op}'`).join(',');
+ return `(${c}.source_id=${r}.source_id AND ${c}.slug=${r}.slug AND ${c}.sequence>${r}.sequence AND (
+ (${c}.digest=${r}.digest AND ${c}.state IN ('committed','failed','queued','running','recovering'))
+ OR (${c}.state IN ('committed','queued','running','recovering') AND (${c}.operation IN (${removals}) OR ${r}.operation='put_page'))
+ OR (${r}.operation='put_page' AND ${c}.state='failed' AND ${c}.operation='put_page' AND COALESCE(NOT (${c}.intent ? 'kind'), false))))`;
+}
+
+/** The order that picks the most telling superseding request: the same intent committed, then the same intent, then the oldest later write. */
+export function supersessionOrderSql(r: string, c: string): string {
+ return `(${c}.digest=${r}.digest AND ${c}.state='committed') DESC, (${c}.digest=${r}.digest) DESC, ${c}.sequence`;
+}
+
+export type TerminalDisposition = 'already_written' | 'duplicate' | 'superseded' | 'unknown';
+/** The disposition `supersessionSql`'s first match (in `supersessionOrderSql` order) proves, or `unknown` without one. */
+export function dispositionOf(later: { state: string; same_intent: boolean } | null | undefined): TerminalDisposition {
+ if (!later) return 'unknown';
+ if (later.same_intent && later.state === 'committed') return 'already_written';
+ if (later.same_intent) return 'duplicate';
+ return 'superseded';
+}
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
new file mode 100644
index 0000000000..effec8694f
--- /dev/null
+++ b/src/core/persistence/terminal-failures.ts
@@ -0,0 +1,344 @@
+/**
+ * #6650 (L3): the reader behind the writer's terminal-state visibility. Two reads over `persistence_requests`, both
+ * bounded (a statement deadline and a connection-acquisition deadline; a read that hits either reports `unknown`, never
+ * an empty pile):
+ *
+ * - `readTerminalFailureSummary`: ONE set-based aggregate over the terminal receipts that did not commit (failed,
+ * conflict, cancelled) in the window, plus every receipt that still holds a publication recovery record, grouped on
+ * the columns `classifyTerminal` reads. It reports active blockers (recovery records, which hold their root as the
+ * head blocker's `request_recovery`, plus PR A's `checkpoint_blockers` when the caller passes them), distinct
+ * unresolved slugs and intents, the oldest unresolved age, historical non-blocking rows, the attempts of the last
+ * 24 h and the zero-filled daily counts of the 7 days before them (the spike check). "Resolved" means
+ * `supersessionSql` found a later request that made the row moot; "historical" means resolved, or written by a build
+ * older than the release that fixed its class (`TERMINAL_FIXED_IN`). Archived sources are skipped.
+ * - `readTerminalFailures`: the drill-down for one source, rows newest first by `sequence` with a `before` cursor, or
+ * groups on code + origin + category with each group's exact filter, its drill-down command and inspect actions
+ * for a few samples. A page that fills (or a scan that reaches its bound) returns `truncated: true` with the next
+ * command instead of refusing.
+ *
+ * Neither read uses `persistence_requests_compactable`: that partial index excludes recovery-holding and compacted
+ * receipts, both of which this reader must see. The window is clamped to `persistence.receipt_retention_days`: past
+ * it a receipt's message is gone and the message-routed codes would read as `diagnosis_required`.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import { isStatementTimeout } from './bounded-reads.ts';
+import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limits.ts';
+import { classifyTerminal, dispositionOf, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
+ type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';
+
+export const TERMINAL_WINDOW_KEY = 'persistence.terminal_failures.window_days';
+export const TERMINAL_SPIKE_FACTOR_KEY = 'persistence.terminal_failures.spike_factor';
+export const TERMINAL_SPIKE_MIN_KEY = 'persistence.terminal_failures.spike_min';
+export const TERMINAL_CONFIG_KEYS = [TERMINAL_WINDOW_KEY, TERMINAL_SPIKE_FACTOR_KEY, TERMINAL_SPIKE_MIN_KEY] as const;
+export const TERMINAL_DEFAULTS = { windowDays: 7, spikeFactor: 3, spikeMin: 25 } as const;
+/** Server-side bound of each read, and how long it may wait for a pooled connection on top. */
+export const TERMINAL_STATEMENT_MS = 5_000;
+export const TERMINAL_ACQUIRE_MS = 2_000;
+
+export interface TerminalThresholds { windowDays: number; spikeFactor: number; spikeMin: number; retentionDays: number; clamped: boolean }
+
+/** `gbrain config set` validation for the three keys: a positive number (whole days for the window). */
+export function validateTerminalConfigValue(key: string, value: string): string | null {
+ if (!(TERMINAL_CONFIG_KEYS as readonly string[]).includes(key)) return null;
+ const n = Number(value);
+ const ok = key === TERMINAL_WINDOW_KEY ? Number.isInteger(n) && n >= 1 && n <= 3650 : Number.isFinite(n) && n > 0 && n <= 1_000_000;
+ return ok ? null : `${key} must be ${key === TERMINAL_WINDOW_KEY ? 'a whole number of days from 1 to 3650' : 'a positive number'}; got ${JSON.stringify(value)}.`;
+}
+
+export async function readTerminalThresholds(engine: Pick<BrainEngine, 'executeRaw'>, requestedDays?: number): Promise<TerminalThresholds> {
+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key=ANY($1::text[])', [[...TERMINAL_CONFIG_KEYS]]);
+ const read = (key: string, fallback: number) => {
+ const raw = rows.find(row => row.key === key)?.value;
+ return raw !== undefined && validateTerminalConfigValue(key, raw) === null ? Number(raw) : fallback;
+ };
+ const retentionDays = Math.max(1, Math.floor(await readReceiptRetentionDays(engine as BrainEngine).catch(() => DEFAULT_RECEIPT_RETENTION_DAYS)));
+ const wanted = requestedDays ?? read(TERMINAL_WINDOW_KEY, TERMINAL_DEFAULTS.windowDays);
+ return { windowDays: Math.min(wanted, retentionDays), spikeFactor: read(TERMINAL_SPIKE_FACTOR_KEY, TERMINAL_DEFAULTS.spikeFactor),
+ spikeMin: read(TERMINAL_SPIKE_MIN_KEY, TERMINAL_DEFAULTS.spikeMin), retentionDays, clamped: wanted > retentionDays };
+}
+
+/** The receipt columns every read selects, with the knock-on, routed-message and build columns computed once in SQL. */
+const ROUTED_MESSAGE = (r: string) => `CASE
+ WHEN ${r}.error_code='source_changed' AND ${r}.error_detail->>'reason' IS NULL THEN left(${r}.error_message, 500)
+ WHEN ${r}.error_code IN ('storage_error','writer_coordinator_required') AND ${r}.error_detail IS NULL AND ${r}.error_message LIKE '${LEGACY_PUBLICATION_PREFIX}%' THEN '${LEGACY_PUBLICATION_PREFIX}'
+ WHEN ${r}.error_code='storage_error' AND ${r}.error_message ~* '${CONNECTION_MESSAGE_PATTERN}' THEN 'connection closed' END`;
+/** A version column older than `fixed` (both MAJOR.MINOR.PATCH[.MICRO]); NULL-safe (an unknown build is not older). */
+const OLDER_THAN = (column: string, fixed: string) => `COALESCE(${column} ~ '^\\d+\\.\\d+\\.\\d+(\\.\\d+)?$' AND string_to_array(${column} || CASE WHEN ${column} ~ '^\\d+\\.\\d+\\.\\d+$' THEN '.0' ELSE '' END, '.')::int[] < '{${fixed.split('.').concat(fixed.split('.').length === 3 ? ['0'] : []).join(',')}}'::int[], false)`;
+/**
+ * The SQL twin of `TerminalVerdict.historical` for the categories `TERMINAL_FIXED_IN` names, over the base CTE's columns,
+ * so distinct counts leave history out. The classifier stays the authority for every per-group count; a test pins the twin.
+ */
+export const TERMINAL_HISTORICAL_SQL: Readonly<Record<keyof typeof TERMINAL_FIXED_IN, (b: string) => string>> = {
+ knock_on: b => `(${b}.knock_on AND NOT ${b}.has_recovery AND ${OLDER_THAN(`${b}.build`, TERMINAL_FIXED_IN.knock_on)})`,
+ legacy_publication_refusal: b => `(NOT ${b}.has_recovery AND NOT ${b}.knock_on AND ${b}.routed_message = '${LEGACY_PUBLICATION_PREFIX}' AND ${b}.origin IS NULL AND ${b}.error_code IN ('storage_error','writer_coordinator_required'))`,
+};
+const HISTORICAL_BY_BUILD = (b: string) => `COALESCE(${Object.values(TERMINAL_HISTORICAL_SQL).map(sql => sql(b)).join(' OR ')}, false)`;
+const BUILD = (r: string) => `COALESCE(${r}.error_detail->'attempt'->>'consumer_version', ${r}.admitter_version)`;
+const ENDED = (r: string) => `COALESCE(${r}.completed_at, ${r}.updated_at)`;
+const TERMINAL = (r: string) => `${r}.state IN ('failed','conflict','cancelled')`;
+const RECOVERY = (r: string) => `(${r}.recovery IS NOT NULL AND ${r}.state IN ('committed','failed','conflict','cancelled'))`;
+
+interface KeyColumns { source_id: string; state: string; error_code: string | null; origin: string | null; reason: string | null; cause: string | null; operation: string;
+ has_recovery: boolean; blocked_reason: string | null; compacted: boolean; knock_on: boolean; routed_message: string | null; build: string | null }
+
+function verdictOf(row: KeyColumns & { request_id?: string; slug?: string; error_detail?: Record<string, unknown> | null }): TerminalVerdict {
+ const detail = row.error_detail ?? (row.origin || row.reason || row.cause ? { ...(row.origin ? { origin: row.origin } : {}), ...(row.reason ? { reason: row.reason } : {}),
+ ...(row.cause ? { cause: row.cause } : {}) } : null);
+ return classifyTerminal({ request_id: row.request_id, source_id: row.source_id, slug: row.slug ?? '<slug>', operation: row.operation, state: row.state, error_code: row.error_code,
+ error_detail: detail, recovery: row.has_recovery || null, blocked_reason: row.blocked_reason, compacted: row.compacted, knock_on: row.knock_on,
+ error_message: row.routed_message, build: row.build })!;
+}
+
+async function bounded<T>(engine: BrainEngine, sql: string, params: unknown[]): Promise<T[] | 'unknown'> {
+ try {
+ return await engine.executeRaw<T>(sql, params, { timeoutMs: TERMINAL_STATEMENT_MS, signal: AbortSignal.timeout(TERMINAL_STATEMENT_MS + TERMINAL_ACQUIRE_MS) } as never);
+ } catch (error) {
+ const name = (error as { name?: string } | null)?.name;
+ if (isStatementTimeout(error) || name === 'AbortError' || name === 'TimeoutError' || (error as { code?: string })?.code === 'pool_capacity') return 'unknown';
+ throw error;
+ }
+}
+
+export interface TerminalBlocker { kind: 'recovery' | 'checkpoint'; source_id: string; request_id: string; slug?: string; category: TerminalCategory | 'checkpoint_blocker'; action: Action; human_reason?: string; needs_human: boolean }
+export interface TerminalSourceSummary {
+ source_id: string;
+ active_blockers: TerminalBlocker[];
+ 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;
+ 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 }>;
+}
+export type TerminalSummary = { status: 'ok'; window_days: number; window_clamped: boolean; retention_days: number; sources: TerminalSourceSummary[] } | { status: 'unknown'; window_days: number; reason: string };
+
+/**
+ * The one aggregate. `sourceIds` narrows it (a remote scope or one source); otherwise every non-archived source.
+ * `checkpointBlockers` are PR A's `checkpoint_blockers` per source (the caller read them; this module never recomputes them).
+ */
+export async function readTerminalFailureSummary(engine: BrainEngine, opts: { sourceIds?: string[]; thresholds?: TerminalThresholds;
+ checkpointBlockers?: Map<string, Array<{ request_id: string; slug: string; knock_on: boolean; recovery: boolean }>> } = {}): Promise<TerminalSummary> {
+ const t = opts.thresholds ?? await readTerminalThresholds(engine);
+ const span = Math.max(t.windowDays, 8);
+ const days = Array.from({ length: 7 }, (_, i) => `count(*) FILTER (WHERE state<>'committed' AND ended_at <= now()-interval '${i + 1} day' AND ended_at > now()-interval '${i + 2} day')::int AS d${i + 2}`).join(',\n ');
+ const rows = await bounded<KeyColumns & { set: number; resolved: boolean | null; rows: number; in_window: number; n_24h: number; oldest: string | null; oldest_age: number | null;
+ distinct_slugs: number; distinct_intents: number; recovery_ids: string[] | null; recovery_slugs: string[] | null } & Record<string, number>>(engine,
+ `WITH base AS (
+ SELECT r.id, r.request_id::text AS request_id, r.source_id, r.slug, r.digest, r.sequence, r.operation, r.state, r.error_code,
+ r.error_detail->>'origin' AS origin, r.error_detail->>'reason' AS reason, r.error_detail->>'cause' AS cause,
+ r.recovery IS NOT NULL AS has_recovery, r.blocked_reason, r.compacted, ${terminalKnockOnSql('r')} AS knock_on,
+ ${ROUTED_MESSAGE('r')} AS routed_message, ${BUILD('r')} AS build, ${ENDED('r')} AS ended_at
+ FROM persistence_requests r JOIN sources s ON s.id=r.source_id AND s.archived IS NOT TRUE
+ WHERE (${RECOVERY('r')} OR (${TERMINAL('r')} AND ${ENDED('r')} > now()-($1::int*interval '1 day')))
+ AND ($2::text[] IS NULL OR r.source_id=ANY($2::text[]))
+ ), resolved AS (
+ SELECT r.id FROM base r WHERE NOT r.has_recovery AND EXISTS (SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')})
+ ), tagged AS (
+ SELECT b.*, (x.id IS NOT NULL) AS resolved, (b.has_recovery OR b.ended_at > now()-($3::int*interval '1 day')) AS in_window, ${HISTORICAL_BY_BUILD('b')} AS historical_build
+ FROM base b LEFT JOIN resolved x ON x.id=b.id
+ )
+ SELECT GROUPING(state) AS set, source_id, state, error_code, origin, reason, cause, operation, has_recovery, blocked_reason, compacted, knock_on, routed_message, build, resolved,
+ count(*) FILTER (WHERE in_window)::int AS rows, count(*) FILTER (WHERE in_window)::int AS in_window,
+ count(*) FILTER (WHERE state<>'committed' AND ended_at > now()-interval '1 day')::int AS n_24h,
+ ${days},
+ to_char(min(ended_at) FILTER (WHERE in_window) AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS oldest,
+ floor(EXTRACT(EPOCH FROM now()-min(ended_at) FILTER (WHERE in_window)))::bigint AS oldest_age,
+ count(DISTINCT slug) FILTER (WHERE in_window AND NOT resolved AND NOT has_recovery AND NOT historical_build)::int AS distinct_slugs,
+ count(DISTINCT digest) FILTER (WHERE in_window AND NOT resolved AND NOT has_recovery AND NOT historical_build)::int AS distinct_intents,
+ (array_agg(request_id ORDER BY sequence) FILTER (WHERE has_recovery))[1:20] AS recovery_ids,
+ (array_agg(slug ORDER BY sequence) FILTER (WHERE has_recovery))[1:20] AS recovery_slugs
+ FROM tagged
+ GROUP BY GROUPING SETS ((source_id, state, error_code, origin, reason, cause, operation, has_recovery, blocked_reason, compacted, knock_on, routed_message, build, resolved), (source_id))
+ ORDER BY source_id`, [span, opts.sourceIds ?? null, t.windowDays]);
+ if (rows === 'unknown') return { status: 'unknown', window_days: t.windowDays, reason: `the aggregate did not finish within ${TERMINAL_STATEMENT_MS} ms (or no connection within ${TERMINAL_ACQUIRE_MS} ms)` };
+ const bySource = new Map<string, TerminalSourceSummary>();
+ const 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: [] });
+ return s;
+ };
+ // Per-group oldest unresolved: the GROUPING SETS total row's oldest covers every row, so the unresolved one is taken from groups.
+ for (const row of rows) {
+ const s = summaryOf(row.source_id);
+ if (Number(row.set) === 1) {
+ s.unresolved.distinct_slugs = Number(row.distinct_slugs); s.unresolved.distinct_intents = Number(row.distinct_intents);
+ s.new_last_24h = Number(row.n_24h);
+ s.daily_7d = Array.from({ length: 7 }, (_, i) => Number(row[`d${i + 2}`] ?? 0));
+ continue;
+ }
+ const verdict = verdictOf(row);
+ const n = Number(row.rows);
+ if (row.has_recovery) {
+ (row.recovery_ids ?? []).forEach((id, i) => {
+ const v = verdictOf({ ...row, request_id: id, slug: row.recovery_slugs?.[i] });
+ s.active_blockers.push({ kind: 'recovery', source_id: row.source_id, request_id: id, slug: row.recovery_slugs?.[i], category: v.category, action: v.action,
+ needs_human: v.needs_human, ...(v.human_reason ? { human_reason: v.human_reason } : {}) });
+ });
+ }
+ if (!n) continue;
+ const historical = !row.has_recovery && (row.resolved === true || verdict.historical);
+ const unresolved = !row.has_recovery && !historical;
+ if (historical) s.historical_rows += n;
+ if (unresolved) {
+ s.unresolved.rows += n;
+ const age = row.oldest_age === null ? null : Number(row.oldest_age);
+ if (age !== null && (s.unresolved.oldest_age_seconds === null || age > s.unresolved.oldest_age_seconds)) { s.unresolved.oldest_age_seconds = age; s.unresolved.oldest_at = row.oldest; }
+ if (verdict.defect) {
+ const existing = s.defects.find(d => d.category === verdict.category && d.code === verdict.code && d.origin === verdict.origin);
+ if (existing) existing.rows += n;
+ else s.defects.push({ category: verdict.category, code: verdict.code, origin: verdict.origin, rows: n, ...(verdict.human_reason ? { human_reason: verdict.human_reason } : {}), action: verdict.action });
+ }
+ }
+ const cat = s.categories.find(c => c.category === verdict.category && c.code === verdict.code && c.origin === verdict.origin);
+ if (cat) { cat.rows += n; cat.unresolved += unresolved ? n : 0; cat.historical += historical ? n : 0; }
+ else s.categories.push({ category: verdict.category, code: verdict.code, origin: verdict.origin, rows: n, unresolved: unresolved ? n : 0, historical: historical ? n : 0,
+ class: verdict.class, needs_human: verdict.needs_human });
+ }
+ for (const [sourceId, blockers] of opts.checkpointBlockers ?? []) {
+ const live = blockers.filter(b => !b.knock_on && !b.recovery);
+ if (!live.length) continue;
+ const s = summaryOf(sourceId);
+ for (const b of live) s.active_blockers.push({ kind: 'checkpoint', source_id: sourceId, request_id: b.request_id, slug: b.slug, category: 'checkpoint_blocker', needs_human: false,
+ action: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Receipt ${b.request_id} (${b.slug}) blocks the sync checkpoint of source ${sourceId}; sync status names the next step, read-only.`, verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] } } });
+ }
+ for (const s of bySource.values()) s.categories.sort((a, b) => b.rows - a.rows || a.category.localeCompare(b.category) || a.code.localeCompare(b.code));
+ return { status: 'ok', window_days: t.windowDays, window_clamped: t.clamped, retention_days: t.retentionDays,
+ sources: [...bySource.values()].sort((a, b) => a.source_id.localeCompare(b.source_id)) };
+}
+
+/**
+ * PR A's checkpoint blockers for every non-archived source whose managed-sync cursor waits at its checkpoint step
+ * (the others have none), keyed by source, for `readTerminalFailureSummary`.
+ */
+export async function readCheckpointBlockerMap(engine: BrainEngine, sourceIds?: string[]): Promise<NonNullable<Parameters<typeof readTerminalFailureSummary>[1]>['checkpointBlockers'] & {}> {
+ const { readCheckpointBlockers } = await import('./sync-status.ts');
+ const atCheckpoint = await engine.executeRaw<{ source_id: string }>(`SELECT DISTINCT o.completed_keys->0->>'sourceId' AS source_id FROM op_checkpoints o
+ JOIN sources s ON s.id=o.completed_keys->0->>'sourceId' AND s.archived IS NOT TRUE
+ WHERE o.op='managed-sync' AND o.completed_keys->0->'pending'->'intent'->>'kind'='managed_sync_checkpoint' AND COALESCE(o.completed_keys->0->>'done','false')<>'true'
+ AND ($1::text[] IS NULL OR o.completed_keys->0->>'sourceId'=ANY($1::text[]))`, [sourceIds ?? null]);
+ const blockers = new Map<string, Awaited<ReturnType<typeof readCheckpointBlockers>>>();
+ for (const row of atCheckpoint) blockers.set(row.source_id, await readCheckpointBlockers(engine, row.source_id));
+ return blockers;
+}
+
+/** The zero-filled median of the 7 days before the last 24 h. */
+export function sevenDayMedian(daily: number[]): number {
+ const sorted = [...daily, ...Array(Math.max(0, 7 - daily.length)).fill(0)].slice(0, 7).sort((a, b) => a - b);
+ return sorted[3]!;
+}
+export function isSpike(last24h: number, daily: number[], t: Pick<TerminalThresholds, 'spikeFactor' | 'spikeMin'>): boolean {
+ return last24h >= t.spikeMin && last24h > t.spikeFactor * sevenDayMedian(daily);
+}
+
+export interface TerminalFailureQuery {
+ sourceId: string;
+ /** `unresolved` (default): rows that neither block, nor are resolved or historical. `all`: every terminal row in the window. */
+ state?: 'unresolved' | 'all';
+ groupBy?: 'category' | null;
+ sinceDays?: number;
+ limit?: number;
+ /** The previous page's `next_cursor` (a request sequence). */
+ before?: string;
+ code?: string;
+ origin?: string;
+ category?: string;
+}
+export interface TerminalFailureRow {
+ request_id: string; slug: string; operation: string; state: string; code: string; origin: string | null; category: TerminalCategory;
+ class: string; safe_actions: string[]; needs_human: boolean; human_reason?: string; disposition: TerminalDisposition; blocking: boolean; historical: boolean;
+ compacted: boolean; ended_at: string; cursor: string; inspect: Action; fix: Action; root_request_id?: string;
+}
+export interface TerminalFailureGroup {
+ code: string; origin: string | null; category: TerminalCategory; rows: number; class: string; needs_human: boolean; human_reason?: string;
+ filter: { code: string; origin: string | null; category: TerminalCategory }; drill_down: string[]; fix: Action; samples: Array<Pick<TerminalFailureRow, 'request_id' | 'slug' | 'state' | 'ended_at' | 'inspect'>>;
+}
+export type TerminalFailureListing = {
+ status: 'ok'; source_id: string; window_days: number; window_clamped: boolean; state: 'unresolved' | 'all'; group_by: 'category' | null;
+ rows?: TerminalFailureRow[]; groups?: TerminalFailureGroup[]; truncated: boolean; next_cursor: string | null; next?: string[]; scanned: number;
+} | { status: 'unknown'; source_id: string; reason: string };
+
+const MAX_SCAN = 2_000;
+const BATCH = 200;
+/** How a null origin is written in a drill-down filter (`--origin none`). */
+export const NO_ORIGIN = 'none';
+
+export function terminalFailuresArgv(q: TerminalFailureQuery, extra: Record<string, string | null | undefined> = {}): string[] {
+ const argv = ['gbrain', 'sources', 'writer', 'failures', q.sourceId];
+ const flags: Record<string, string | null | undefined> = { state: q.state === 'all' ? 'all' : null, 'group-by': q.groupBy ?? null, since: q.sinceDays ? `${q.sinceDays}d` : null,
+ category: q.category, code: q.code, origin: q.origin, limit: q.limit && q.limit !== 20 ? String(q.limit) : null, ...extra };
+ for (const [flag, value] of Object.entries(flags)) if (value) argv.push(`--${flag}`, value);
+ return [...argv, '--json'];
+}
+
+/**
+ * The drill-down for one source. Rows are classified here, so the `code` / `origin` / `category` filters (the verdict's,
+ * exactly as a group names them) are applied after the read, and one call scans at most `MAX_SCAN` receipts.
+ */
+export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailureQuery): Promise<TerminalFailureListing> {
+ const t = await readTerminalThresholds(engine, q.sinceDays);
+ const limit = Math.min(100, Math.max(1, q.limit ?? 20));
+ const state = q.state ?? 'unresolved';
+ const out: TerminalFailureRow[] = [];
+ let cursor = q.before ?? null, scanned = 0, exhausted = false;
+ const want = q.groupBy ? MAX_SCAN : limit + 1;
+ while (out.length < want && scanned < MAX_SCAN && !exhausted) {
+ const batch = await bounded<KeyColumns & { request_id: string; sequence: string; slug: string; error_detail: Record<string, unknown> | null; ended_at: string; later_state: string | null; same_intent: boolean | null }>(engine,
+ `SELECT r.request_id::text AS request_id, r.sequence::text AS sequence, r.source_id, r.slug, r.operation, r.state, r.error_code, r.error_detail,
+ r.error_detail->>'origin' AS origin, r.error_detail->>'reason' AS reason, r.error_detail->>'cause' AS cause,
+ r.recovery IS NOT NULL AS has_recovery, r.blocked_reason, r.compacted, ${terminalKnockOnSql('r')} AS knock_on, ${ROUTED_MESSAGE('r')} AS routed_message, ${BUILD('r')} AS build,
+ to_char(${ENDED('r')} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS ended_at, later.state AS later_state, later.same_intent
+ FROM persistence_requests r
+ LEFT JOIN LATERAL (SELECT c.state, c.digest=r.digest AS same_intent FROM persistence_requests c WHERE ${supersessionSql('r', 'c')}
+ ORDER BY ${supersessionOrderSql('r', 'c')} LIMIT 1) later ON r.recovery IS NULL
+ WHERE r.source_id=$1 AND (${RECOVERY('r')} OR (${TERMINAL('r')} AND ${ENDED('r')} > now()-($2::int*interval '1 day')))
+ AND ($3::bigint IS NULL OR r.sequence < $3::bigint)
+ ORDER BY r.sequence DESC LIMIT $4`, [q.sourceId, t.windowDays, cursor, BATCH]);
+ if (batch === 'unknown') return { status: 'unknown', source_id: q.sourceId, reason: `the read did not finish within ${TERMINAL_STATEMENT_MS} ms (or no connection within ${TERMINAL_ACQUIRE_MS} ms)` };
+ if (batch.length < BATCH) exhausted = true;
+ for (const row of batch) {
+ scanned++;
+ cursor = row.sequence;
+ const v = verdictOf(row);
+ const disposition = dispositionOf(row.later_state ? { state: row.later_state, same_intent: row.same_intent === true } : null);
+ const historical = !row.has_recovery && (disposition !== 'unknown' || v.historical);
+ const matches = (!q.category || v.category === q.category) && (!q.code || v.code === q.code)
+ && (q.origin === undefined || (v.origin ?? NO_ORIGIN) === q.origin) && (state === 'all' || !historical);
+ if (matches) out.push({ request_id: row.request_id, slug: row.slug, operation: row.operation, state: row.state, code: v.code, origin: v.origin, category: v.category, class: v.class,
+ safe_actions: v.safe_actions, needs_human: v.needs_human, ...(v.human_reason ? { human_reason: v.human_reason } : {}), disposition, blocking: row.has_recovery, historical,
+ compacted: row.compacted, ended_at: row.ended_at, cursor: row.sequence, ...(v.root_request_id ? { root_request_id: v.root_request_id } : {}),
+ inspect: { argv: terminalInspectArgv(row.request_id), consent: [], actor: 'agent', requires_exclusive: false, why: 'The receipt with its diagnosis and structured fix, read-only.' },
+ fix: v.action });
+ if (out.length >= want || scanned >= MAX_SCAN) { exhausted = exhausted && row === batch.at(-1); break; }
+ }
+ }
+ const window = { window_days: t.windowDays, window_clamped: t.clamped };
+ if (!q.groupBy) {
+ const page = out.slice(0, limit);
+ // A page past `limit`, or a scan that stopped at its bound with receipts left, continues from the last row it covered.
+ const resume = out.length > limit ? page.at(-1)!.cursor : !exhausted ? cursor : null;
+ return { status: 'ok', source_id: q.sourceId, ...window, state, group_by: null, rows: page, scanned,
+ truncated: resume !== null, next_cursor: resume, ...(resume !== null ? { next: terminalFailuresArgv(q, { before: resume }) } : {}) };
+ }
+ const groups = new Map<string, TerminalFailureGroup>();
+ for (const row of out) {
+ const key = `${row.code}\0${row.origin ?? ''}\0${row.category}`;
+ let g = groups.get(key);
+ if (!g) {
+ const filter = { code: row.code, origin: row.origin, category: row.category };
+ groups.set(key, g = { code: row.code, origin: row.origin, category: row.category, rows: 0, class: row.class, needs_human: row.needs_human,
+ ...(row.human_reason ? { human_reason: row.human_reason } : {}), filter, fix: row.fix, samples: [],
+ drill_down: terminalFailuresArgv({ sourceId: q.sourceId, state: q.state, sinceDays: q.sinceDays, category: row.category, code: row.code, origin: row.origin ?? NO_ORIGIN }) });
+ }
+ g.rows++;
+ if (g.samples.length < 3) g.samples.push({ request_id: row.request_id, slug: row.slug, state: row.state, ended_at: row.ended_at, inspect: row.inspect });
+ }
+ const sorted = [...groups.values()].sort((a, b) => b.rows - a.rows || a.category.localeCompare(b.category) || a.code.localeCompare(b.code) || (a.origin ?? '').localeCompare(b.origin ?? ''));
+ // Groups count the receipts this call scanned; a scan that stopped at its bound continues from where it stopped.
+ const resume = !exhausted ? cursor : null;
+ const more = resume !== null || sorted.length > limit;
+ return { status: 'ok', source_id: q.sourceId, ...window, state, group_by: 'category', groups: sorted.slice(0, limit), scanned, truncated: more, next_cursor: resume,
+ ...(resume !== null ? { next: terminalFailuresArgv(q, { before: resume }) } : sorted.length > limit ? { next: terminalFailuresArgv({ ...q, limit: 100 }) } : {}) };
+}
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index 81146be688..41789d4cc9 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -55,12 +55,13 @@ import { getWorktreeBinding } from '../persistence/ownership.ts';
import { prepareFileTarget } from '../persistence/page-prepare.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { resolveEntitySlugWithSource } from '../entities/resolve.ts';
+import { dispositionOf, PAGE_REMOVAL_OPERATIONS, supersessionOrderSql, supersessionSql } from '../persistence/terminal-classify.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
const REPLAYABLE = ['put_page', 'add_timeline_entry', 'remember'];
const REMEMBER_PREPARED_KEYS = ['entity_slug', 'fence', 'valid_from', 'valid_until', 'entity_inferred', 'entity_warning'];
const REMOTE_PREPARED_KEYS = ['source_kind', 'source_uri', 'ingested_via'];
-const PAGE_REMOVALS = ['delete_page', 'purge_page'];
+const PAGE_REMOVALS = PAGE_REMOVAL_OPERATIONS;
const GUARD_REFUSAL = `(r.state='failed' AND (r.error_code='writer_coordinator_required'
OR (r.error_code='storage_error' AND r.error_message LIKE 'Publication failed (P0001)%')))`;
/** #6429: a refusal from prepareFileTarget (page-prepare.ts); the receipt keeps the code, not the refusal's detail. */
@@ -255,16 +256,12 @@ async function disposition(engine: BrainEngine, write: FailedWrite): Promise<{ c
}
const replace = write.operation === 'put_page';
const [later] = await engine.executeRaw<{ state: string; operation: string; same_intent: boolean }>(
- `SELECT state, operation, digest=$3 AS same_intent FROM persistence_requests
- WHERE source_id=$1 AND slug=$2 AND sequence > $4::bigint AND (
- (digest=$3 AND state IN ('committed','failed','queued','running','recovering'))
- OR (state IN ('committed','queued','running','recovering') AND (operation = ANY($6::text[]) OR $5::boolean))
- OR ($5::boolean AND state='failed' AND operation='put_page' AND NOT (intent ? 'kind')))
- ORDER BY (digest=$3 AND state='committed') DESC, (digest=$3) DESC, sequence LIMIT 1`,
- [write.source_id, write.slug, write.digest, write.sequence, replace, PAGE_REMOVALS]);
- if (later?.same_intent && later.state === 'committed') return { class: 'already_written' };
- if (later?.same_intent) return { class: 'duplicate', detail: `a later request with the same intent is ${later.state}` };
- if (later) return { class: 'superseded', detail: `a later ${later.operation} of this page is ${later.state}` };
+ `SELECT c.state, c.operation, c.digest=r.digest AS same_intent FROM persistence_requests r JOIN persistence_requests c ON ${supersessionSql('r', 'c')}
+ WHERE r.id=$1::uuid ORDER BY ${supersessionOrderSql('r', 'c')} LIMIT 1`, [write.id]);
+ const found = dispositionOf(later);
+ if (found === 'already_written') return { class: 'already_written' };
+ if (found === 'duplicate') return { class: 'duplicate', detail: `a later request with the same intent is ${later!.state}` };
+ if (found === 'superseded') return { class: 'superseded', detail: `a later ${later!.operation} of this page is ${later!.state}` };
const read = write.intent.expected_revision;
if (replace && typeof read === 'string' && read !== await pageRevision(engine, write.source_id, write.slug)) {
return { class: 'superseded', detail: 'the page changed after the revision the caller read' };
diff --git a/test/agent-journey-terminal-failures-6650.test.ts b/test/agent-journey-terminal-failures-6650.test.ts
new file mode 100644
index 0000000000..ae5cf09a67
--- /dev/null
+++ b/test/agent-journey-terminal-failures-6650.test.ts
@@ -0,0 +1,112 @@
+/**
+ * #6650 (L3): the agent journey over terminal write failures, through the real CLI.
+ *
+ * A keyless PGLite brain with a managed source carries a pile of terminal receipts (pre-fix knock-on cancels from an
+ * older build, caller conflicts, a refusal a later write superseded) and one committed receipt still holding a
+ * publication recovery record. An agent with no TTY and no keys gets from the doctor warning to a verified clear in
+ * three commands, each the previous one's structured output run verbatim (the knock-on pile is a day old, so no 24 h
+ * spike rides along):
+ *
+ * doctor --only persistence_terminal_failures --json warn: the recovery record is the active blocker; fix.next = run
+ * <fix.command> the owner pass clears the record
+ * <fix.verify.argv> ok: no blocker, the pile is history or ordinary refusals
+ *
+ * The drill-down (`sources writer failures --group-by category --json`) classifies the same pile with an exact filter
+ * per group. Real CLI subprocesses and a PGLite datastore in a temp home.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { knockOnDetail } from '../src/core/persistence/sync-knock-on.ts';
+import { gb, oneDocument } from './helpers/agent-journey.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SOURCE = 'journey-notes';
+const CHECK = 'persistence_terminal_failures';
+let home: string;
+let blocker: string;
+
+/** The shell an agent runs a rendered command in: split on spaces (every argv here is space-free). */
+const argvOf = (command: string) => { const parts = command.split(' '); expect(parts[0]).toBe('gbrain'); return parts.slice(1); };
+const checkOf = (doc: Record<string, any>) => (doc.checks as Array<Record<string, any>>).find(c => c.name === CHECK)!;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-6650-journey-'));
+ const init = await gb(home, ['init', '--pglite', '--no-embedding', '--json']);
+ expect(init.exitCode).toBe(0);
+ const root = join(home, SOURCE);
+ mkdirSync(root);
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ git('init', '-q');
+ writeFileSync(join(root, 'held.md'), '---\ntitle: Held\n---\nA page whose publication left a recovery record.\n');
+ git('add', '.'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content');
+ await withEnv({ HOME: home, GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });
+ try {
+ 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,\'{}\')', [SOURCE, root]);
+ await claimWorktree(engine, SOURCE, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const binding = (await getWorktreeBinding(engine, SOURCE))!;
+ // The on-disk brain's writer floor is protocol 2: the fixture rows are written in one transaction that declares it.
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");
+ const seed = async (o: { slug: string; state: string; code?: string; detail?: unknown; recovery?: unknown; build?: string; hoursAgo?: number }) => {
+ const requestId = randomUUID();
+ 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,recovery,recovery_bytes,intent,completed_at,updated_at,admitter_version,worktree_id)
+ VALUES('local_cli','journey',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,$5,$6,'x',$7::text::jsonb,$8::text::jsonb,0,
+ '{"content":"x"}'::jsonb,now()-($9::double precision*interval '1 hour'),now()-($9::double precision*interval '1 hour'),$10,$11::uuid)`,
+ [requestId, SOURCE, o.slug, randomUUID(), o.state, o.code ?? null, o.detail === undefined ? null : JSON.stringify(o.detail),
+ o.recovery === undefined ? null : JSON.stringify(o.recovery), o.hoursAgo ?? 2, o.build ?? '0.60.216.0', binding.worktree_id]);
+ return requestId;
+ };
+ for (let i = 0; i < 20; i++) await seed({ slug: `notes/knock-${i}`, state: 'cancelled', code: 'storage_error', detail: knockOnDetail('window_predecessor', randomUUID()), build: '0.60.200.0', hoursAgo: 30 });
+ for (let i = 0; i < 6; i++) await seed({ slug: `notes/conflict-${i}`, state: 'conflict', code: 'revision_conflict' });
+ await seed({ slug: 'notes/rewritten', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception' }, hoursAgo: 3 });
+ await seed({ slug: 'notes/rewritten', state: 'committed', hoursAgo: 1 });
+ blocker = await seed({ slug: 'held', state: 'committed', recovery: { version: 1, path: join(root, 'held.md'), root, before: null, beforeHash: null, afterHash: null,
+ mode: null, ownerEpoch: String(binding.owner_epoch), attempt: randomUUID() } });
+ });
+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+}, 180_000);
+afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });
+
+describe('terminal write failures: doctor warning to verified clear', () => {
+ test('the drill-down classifies the pile with a filter per group', async () => {
+ const doc = oneDocument(await gb(home, ['sources', 'writer', 'failures', SOURCE, '--group-by', 'category', '--state', 'all', '--json']), 'writer failures');
+ const groups = doc.groups as Array<Record<string, any>>;
+ expect(groups.find(g => g.category === 'knock_on')).toMatchObject({ rows: 20 });
+ expect(groups.find(g => g.category === 'caller_conflict')).toMatchObject({ rows: 6, needs_human: false });
+ for (const g of groups) expect(g.drill_down.slice(0, 5)).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE]);
+ }, 120_000);
+
+ test('three commands: warn → run the fix → its verify is ok', async () => {
+ const warned = checkOf(oneDocument(await gb(home, ['doctor', '--only', CHECK, '--json']), 'doctor warn'));
+ expect(warned.status).toBe('warn');
+ expect(warned.message).toContain(blocker);
+ expect(warned.details.active_blockers).toEqual([expect.objectContaining({ kind: 'recovery', request_id: blocker, slug: 'held', category: 'recovery_pending' })]);
+ // History never warns: the pre-fix knock-ons and the superseded refusal are counted apart from the blocker.
+ expect(warned.details.historical_rows).toBe(21);
+ expect(warned.fix.next).toBe('run');
+ expect(warned.fix.command).toBe(`gbrain sync --source ${SOURCE} --no-pull --json --brain host`);
+
+ const fixed = await gb(home, argvOf(warned.fix.command), { timeoutMs: 120_000 });
+ expect(fixed.exitCode).toBe(0);
+
+ expect(warned.fix.verify.argv.slice(0, 4)).toEqual(['gbrain', 'doctor', '--only', CHECK]);
+ const verified = checkOf(oneDocument(await gb(home, warned.fix.verify.argv.slice(1)), 'doctor verify'));
+ expect(verified.status).toBe('ok');
+ expect(verified.details.active_blockers).toEqual([]);
+ expect(verified.details.unresolved.rows).toBe(6);
+ expect(verified.details.historical_rows).toBe(21);
+ }, 300_000);
+});
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 962cbb350a..397cf0541f 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -91,6 +91,7 @@
" [OK] persistence_request_growth: 6 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",
" [OK] persistence_write_stall: No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
" [OK] lost_caller_writes: Every caller write with a retained receipt committed or was superseded.",
+ " [OK] persistence_terminal_failures: No terminal write failures in the last 7 d.",
" [OK] persistence_session_timeouts: PGLite has no session to time out.",
" [OK] connector_held_items: No connector items are held.",
" [OK] git_held_files: No Git source files are held.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 2f3cb72821..63ffff719a 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -926,6 +926,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 2d4192a540..2d49672ea6 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -954,6 +954,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -4059,6 +4111,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index faaabbf893..db1303d2ce 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -943,6 +943,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -4040,6 +4092,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 8dfaee3626..76272ab12d 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -866,6 +866,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 8703fc099b..d9d06823e8 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -885,6 +885,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 7900113e9f..1a9dbd79f2 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -874,6 +874,58 @@
"name": "lost_caller_writes",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_blockers": [],
+ "config": {
+ "receipt_retention_days": 30,
+ "spike_factor": {
+ "key": "persistence.terminal_failures.spike_factor",
+ "value": 3
+ },
+ "spike_min": {
+ "key": "persistence.terminal_failures.spike_min",
+ "value": 25
+ },
+ "window_clamped": false,
+ "window_days": {
+ "key": "persistence.terminal_failures.window_days",
+ "value": 7
+ }
+ },
+ "count": 0,
+ "defects": [],
+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",
+ "historical_rows": 0,
+ "new_last_24h": 0,
+ "sources": [],
+ "spike": {
+ "daily_7d": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "last_24h": 0,
+ "median_7d": 0,
+ "spiking": false
+ },
+ "unresolved": {
+ "distinct_intents": 0,
+ "distinct_slugs": 0,
+ "oldest_age_seconds": null,
+ "rows": 0
+ },
+ "window_days": 7
+ },
+ "message": "No terminal write failures in the last 7 d.",
+ "name": "persistence_terminal_failures",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 440ff87b8d..0a12bd1d2b 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -405,6 +405,10 @@
"category": "ops",
"name": "lost_caller_writes"
},
+ {
+ "category": "ops",
+ "name": "persistence_terminal_failures"
+ },
{
"category": "ops",
"name": "persistence_session_timeouts"
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index e3884ae6b5..c36d571a6a 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -162,6 +162,7 @@ test/sync-status-failure-detail-6513.test.ts
test/sync-waiver-budget.test.ts
test/sync-waiver-run-imports.test.ts
test/takes-vector-lifecycle-5885.serial.test.ts
+test/terminal-failures-6650.test.ts
test/trust-channel-writes.test.ts
test/trust-guarded-supersession.test.ts
test/trust-owner-actions.test.ts
diff --git a/test/sync-status-terminal-6650.test.ts b/test/sync-status-terminal-6650.test.ts
new file mode 100644
index 0000000000..8f1eff645b
--- /dev/null
+++ b/test/sync-status-terminal-6650.test.ts
@@ -0,0 +1,81 @@
+/**
+ * #6650 (L3): `gbrain sync status` summarizes the source's terminal write receipts.
+ *
+ * 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.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+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';
+
+const SOURCE = 'status-src';
+const OTHER = 'status-other';
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1),($2,$2)', [SOURCE, OTHER]);
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await engine.executeRaw('DELETE FROM persistence_requests'); });
+
+async function seed(o: { source?: string; slug: string; state: string; code?: string | null; detail?: unknown; recovery?: unknown; hoursAgo?: number; build?: string }) {
+ const requestId = randomUUID();
+ await engine.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,recovery,intent,completed_at,updated_at,admitter_version)
+ VALUES('local_cli','fixture',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,$5,$6,'x',$7::text::jsonb,$8::text::jsonb,'{"content":"x"}'::jsonb,
+ now()-($9::double precision*interval '1 hour'),now()-($9::double precision*interval '1 hour'),$10)`,
+ [requestId, o.source ?? SOURCE, o.slug, randomUUID(), o.state, o.code ?? null, o.detail === undefined ? null : JSON.stringify(o.detail),
+ o.recovery === undefined ? null : JSON.stringify(o.recovery), o.hoursAgo ?? 1, o.build ?? '0.60.216.0']);
+ return requestId;
+}
+
+async function human(sourceId: string): Promise<string> {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try { await withEnv({ GBRAIN_SOURCE: undefined }, () => runSyncStatus(engine, ['--source', sourceId])); } finally { console.log = log; }
+ return lines.join('\n');
+}
+
+describe('sync status terminal_failures', () => {
+ test('a clean source reports zero and next stays nothing', async () => {
+ const status = await readSyncStatus(engine, SOURCE);
+ expect(status.terminal_failures).toMatchObject({ status: 'ok', window_days: 7, active_blockers: [], unresolved: { rows: 0 }, historical_rows: 0, new_last_24h: 0, defects: 0 });
+ expect(status.next).toBeNull();
+ const out = await human(SOURCE);
+ expect(out).toContain('terminal write failures (last 7 d): 0 active blocker(s), 0 unresolved');
+ expect(out).not.toContain('drill down:');
+ });
+
+ test('separates the blocker, the unresolved pile and history, and names the blocker as next', async () => {
+ const held = await seed({ slug: 'notes/held', state: 'committed', recovery: { version: 1, path: '/nonexistent/x.md', root: '/nonexistent', beforeHash: null, afterHash: 'a' } });
+ await seed({ slug: 'notes/a', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception', error_class: 'TypeError' } });
+ await seed({ slug: 'notes/b', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception', error_class: 'TypeError' } });
+ // A pre-fix knock-on from an older build is history, not a pile to work.
+ await seed({ slug: 'notes/old', state: 'cancelled', code: 'storage_error', detail: { origin: 'sync_knock_on', knock_on: 'window_predecessor' }, build: '0.60.200.0' });
+ await seed({ source: OTHER, slug: 'notes/elsewhere', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception' } });
+
+ const status = await readSyncStatus(engine, SOURCE);
+ const t = status.terminal_failures;
+ if (t.status !== 'ok') throw new Error('expected a finished summary');
+ expect(t.active_blockers).toEqual([{ kind: 'recovery', request_id: held, slug: 'notes/held', category: 'recovery_pending' }]);
+ expect(t.unresolved).toMatchObject({ rows: 2, distinct_slugs: 2 });
+ expect(t.defects).toBe(2);
+ expect(t.drill_down).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE, '--group-by', 'category', '--json']);
+ expect(status.next).not.toBeNull();
+ expect(status.next!.argv).toEqual(['gbrain', 'sync', '--source', SOURCE, '--no-pull', '--json']);
+ expect(status.next!.why).toContain('publication recovery record');
+
+ const out = await human(SOURCE);
+ expect(out).toContain('1 active blocker(s), 2 unresolved (2 page(s)');
+ expect(out).toContain('2 gbrain-defect row(s)');
+ expect(out).toContain(`BLOCKING recovery: request ${held} (notes/held) [recovery_pending]`);
+ expect(out).toContain(`drill down: gbrain sources writer failures ${SOURCE} --group-by category --json`);
+ expect(out).not.toContain('notes/elsewhere');
+ });
+});
diff --git a/test/terminal-failure-metrics-6650.test.ts b/test/terminal-failure-metrics-6650.test.ts
new file mode 100644
index 0000000000..a84ac582cc
--- /dev/null
+++ b/test/terminal-failure-metrics-6650.test.ts
@@ -0,0 +1,88 @@
+/**
+ * #6650 (L3): writer terminal-failure counts on `GET /metrics`.
+ *
+ * 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.
+ * PGLite in-memory, a bare Express app wired with the real mount functions.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+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 type { ServeHttpContext } from '../src/commands/serve-http.ts';
+
+const SOURCE = 'metrics-src';
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [SOURCE]);
+ for (const origin of ['owner_exception', 'owner_exception', 'file_database_drift']) {
+ await engine.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)
+ VALUES('local_cli','fixture',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,'failed',$5,'x',$6::text::jsonb,'{"content":"x"}'::jsonb,
+ now()-interval '1 hour',now()-interval '1 hour','0.60.216.0')`,
+ [randomUUID(), SOURCE, `notes/${randomUUID()}`, randomUUID(), origin === 'owner_exception' ? 'storage_error' : 'file_database_drift', JSON.stringify({ origin })]);
+ }
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function withApp<T>(authed: boolean, fn: (base: string) => Promise<T>): 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;
+ mountHealth(app, ctx);
+ mountMetrics(app, ctx);
+ const server: Server = app.listen(0);
+ await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const addr = server.address();
+ try { return await fn(`http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`); }
+ finally { await new Promise<void>(resolve => server.close(() => resolve())); }
+}
+
+describe('terminal-failure gauges on /metrics', () => {
+ test('an admin scrape carries per-source counts from the aggregate', async () => {
+ await withApp(true, async base => {
+ const res = await fetch(`${base}/metrics`);
+ expect(res.status).toBe(200);
+ const text = await res.text();
+ expect(text).toContain('gbrain_requests_total 0');
+ expect(text).toContain('gbrain_writer_terminal_failures_known 1');
+ expect(text).toContain(`gbrain_writer_terminal_failures_unresolved{source="${SOURCE}"} 3`);
+ expect(text).toContain(`gbrain_writer_terminal_failures_defects{source="${SOURCE}"} 2`);
+ expect(text).toContain(`gbrain_writer_terminal_failures_active_blockers{source="${SOURCE}"} 0`);
+ expect(text).toContain(`gbrain_writer_terminal_failures_new_24h{source="${SOURCE}"} 3`);
+ expect(text).toContain('# TYPE gbrain_writer_terminal_failures_historical gauge');
+ });
+ });
+
+ test('the counts never leave the admin gate: 401 on /metrics, absent from /health', async () => {
+ await withApp(false, async base => {
+ const metrics = await fetch(`${base}/metrics`);
+ expect(metrics.status).toBe(401);
+ expect(await metrics.text()).not.toContain('terminal_failures');
+ const health = await fetch(`${base}/health`);
+ const body = await health.text();
+ expect(body).not.toContain('terminal');
+ expect(body).not.toContain(SOURCE);
+ });
+ });
+
+ 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');
+ expect(text).not.toContain('{source=');
+ });
+
+ 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: [] };
+ 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.ts
new file mode 100644
index 0000000000..edf3245dfa
--- /dev/null
+++ b/test/terminal-failures-6650.test.ts
@@ -0,0 +1,286 @@
+/**
+ * #6650 (L3): writer terminal-state visibility.
+ *
+ * Protects: the read-time classifier routes heterogeneous codes by their recorded origin, survives receipt compaction,
+ * names `diagnosis_required` instead of a guessed fix, and labels rows from builds older than the fixing release as
+ * historical; its knock-on predicate agrees with the SQL twin the reader uses; the one aggregate reports active
+ * blockers apart from history and skips archived sources; doctor `persistence_terminal_failures` warns on a blocker
+ * or an unresolved defect class whatever the trend and on a spike only secondarily; the drill-down pages with a stable
+ * cursor and groups on code + origin + category with an exact filter per group; a read past its deadline is
+ * `unknown`, never an empty pile (on Postgres through a real statement_timeout behind a table lock). PGLite in-memory,
+ * and an isolated Postgres database when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { classifyTerminal, terminalKnockOnSql, supersessionSql, type TerminalInput } from '../src/core/persistence/terminal-classify.ts';
+import { isSyncKnockOn, knockOnDetail } from '../src/core/persistence/sync-knock-on.ts';
+import { WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
+import { readTerminalFailureSummary, readTerminalFailures, readTerminalThresholds, sevenDayMedian, validateTerminalConfigValue, TERMINAL_HISTORICAL_SQL,
+ TERMINAL_STATEMENT_MS, TERMINAL_ACQUIRE_MS } from '../src/core/persistence/terminal-failures.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { TERMINAL_FIXED_IN } from '../src/core/persistence/terminal-classify.ts';
+import { terminalFailuresCheck } from '../src/commands/doctor/checks/persistence-requests.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';
+
+let engine: BrainEngine;
+
+const base: TerminalInput = { source_id: 'src', slug: 'notes/a', operation: 'put_page', state: 'failed', error_code: null, error_detail: null, recovery: null,
+ blocked_reason: null, compacted: false };
+
+describe('classifyTerminal', () => {
+ test('routes storage_error by origin, and an origin-less compacted one is diagnosis_required', () => {
+ expect(classifyTerminal({ ...base, error_code: 'storage_error', error_detail: { origin: 'owner_exception', error_class: 'TypeError' } }))
+ .toMatchObject({ category: 'owner_exception', defect: true, needs_human: true });
+ expect(classifyTerminal({ ...base, error_code: 'storage_error', error_detail: { origin: 'database_trigger', sqlstate: '55000', raiser: 'gbrain_graduation_fence', reason: 'graduation_in_progress' } }))
+ .toMatchObject({ category: 'transport', code: 'graduation_in_progress', class: 'connection', defect: false });
+ expect(classifyTerminal({ ...base, error_code: 'storage_error', error_detail: { origin: 'database_trigger', reason: 'attribution_unclassified_table' } }))
+ .toMatchObject({ category: 'database_refusal', defect: true });
+ expect(classifyTerminal({ ...base, error_code: 'storage_error', error_message: 'write ECONNRESET' })).toMatchObject({ category: 'transport', code: 'connection_lost' });
+ const opaque = classifyTerminal({ ...base, error_code: 'storage_error', compacted: true })!;
+ expect(opaque).toMatchObject({ category: 'diagnosis_required', safe_actions: ['none'], needs_human: true, defect: false });
+ expect(opaque.action.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'src', '--json']);
+ expect(opaque.action.verify?.argv).toEqual(['gbrain', 'sources', 'writer', 'failures', 'src', '--json']);
+ });
+
+ test('routes source_changed by its recorded cause; without one it is diagnosis_required', () => {
+ const drift = classifyTerminal({ ...base, state: 'conflict', error_code: 'source_changed', error_message: 'The canonical file contains an uncoordinated local edit.' })!;
+ expect(drift).toMatchObject({ category: 'file_conflict', safe_actions: ['reconcile'], needs_human: true });
+ expect(drift.action.argv).toEqual(['gbrain', 'sources', 'reconcile', 'src', 'notes/a', '--preview']);
+ expect(classifyTerminal({ ...base, state: 'conflict', error_code: 'source_changed', error_message: 'The imported file changed after sync admission.' }))
+ .toMatchObject({ category: 'sync_fault', safe_actions: ['retry'] });
+ // Compaction nulls the message: the same row no longer says why, so nothing is guessed.
+ expect(classifyTerminal({ ...base, state: 'conflict', error_code: 'source_changed', compacted: true })).toMatchObject({ category: 'diagnosis_required' });
+ });
+
+ test('a typed knock-on survives compaction; a recovery record outranks the code; a cancel is the operator\'s', () => {
+ const detail = knockOnDetail('window_predecessor', randomUUID());
+ const live = classifyTerminal({ ...base, operation: 'submit_job', state: 'cancelled', error_code: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE, intent_kind: 'managed_sync_import', error_detail: detail })!;
+ const compacted = classifyTerminal({ ...base, operation: 'submit_job', state: 'cancelled', error_code: 'cancelled', compacted: true, error_detail: detail })!;
+ expect(compacted).toMatchObject({ category: 'knock_on', code: 'knock_on', root_request_id: detail.root_request_id! });
+ expect({ ...compacted, action: null }).toEqual({ ...live, action: null });
+ expect(classifyTerminal({ ...base, state: 'committed', error_code: null, recovery: { version: 1 } })).toMatchObject({ category: 'recovery_pending', needs_human: false });
+ expect(classifyTerminal({ ...base, state: 'failed', error_code: 'storage_error', recovery: { version: 1 }, blocked_reason: 'unexpected_file_bytes' }))
+ .toMatchObject({ category: 'recovery_blocked', needs_human: true });
+ expect(classifyTerminal({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: 'Cancelled before publication.' }))
+ .toMatchObject({ category: 'operator_cancelled', needs_human: false, defect: false });
+ expect(classifyTerminal({ ...base, state: 'committed' })).toBeNull();
+ });
+
+ test('a row from a build older than the release that fixed its class is historical; an unknown code is diagnosis_required', () => {
+ const knock = { ...base, operation: 'submit_job', state: 'cancelled', error_code: 'cancelled', error_detail: knockOnDetail('lane_fault', null) };
+ expect(classifyTerminal({ ...knock, build: '0.60.200.0' })).toMatchObject({ category: 'knock_on', fixed_in: '0.60.216.0', historical: true });
+ expect(classifyTerminal({ ...knock, build: '0.60.216.0' })).toMatchObject({ historical: false });
+ expect(classifyTerminal({ ...knock, error_detail: { ...knockOnDetail('lane_fault', null), attempt: { consumer_version: '0.60.100.0', consumer_host_id: null } } }))
+ .toMatchObject({ historical: true });
+ expect(classifyTerminal({ ...base, error_code: 'storage_error', error_message: 'Publication failed (P0001). Inspect owner diagnostics.' }))
+ .toMatchObject({ category: 'legacy_publication_refusal', historical: true, defect: false });
+ expect(classifyTerminal({ ...base, error_code: 'made_up_code' })).toMatchObject({ category: 'diagnosis_required' });
+ expect(classifyTerminal({ ...base, error_code: 'writer_coordinator_required', error_detail: { origin: 'database_guard', sqlstate: 'P0001' } }))
+ .toMatchObject({ category: 'writer_guard', defect: true });
+ });
+});
+
+const SOURCE = 'tf-a';
+const OTHER = 'tf-archived';
+async function seed(o: { source?: string; slug: string; operation?: string; state: string; code?: string | null; message?: string | null; detail?: unknown; recovery?: unknown;
+ compacted?: boolean; digest?: string; hoursAgo?: number; build?: string; kind?: string; blocked?: string }): Promise<string> {
+ const requestId = randomUUID();
+ await engine.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,recovery,compacted,intent,completed_at,updated_at,admitter_version,blocked_reason)
+ VALUES('local_cli','fixture',$1::uuid,$2,$3,(SELECT incarnation FROM sources WHERE id=$3),$4,$5,'{}'::jsonb,0,0,$6,$7,$8,$9::text::jsonb,$10::text::jsonb,$11,$12::text::jsonb,
+ now()-($13::double precision*interval '1 hour'),now()-($13::double precision*interval '1 hour'),$14,$15)`,
+ [requestId, o.operation ?? 'put_page', o.source ?? SOURCE, o.slug, o.digest ?? randomUUID(), o.state, o.code ?? null, o.compacted ? null : o.message ?? null,
+ o.detail === undefined ? null : JSON.stringify(o.detail), o.recovery === undefined ? null : JSON.stringify(o.recovery), o.compacted === true,
+ o.compacted ? null : JSON.stringify(o.kind ? { kind: o.kind } : { content: 'x' }), o.hoursAgo ?? 1, o.build ?? '0.60.216.0', o.blocked ?? null]);
+ return requestId;
+}
+
+for (const kind of testBackends()) describe(`the aggregate, doctor and the drill-down (${kind})`, () => {
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM persistence_requests');
+ await engine.executeRaw('DELETE FROM sources WHERE id = ANY($1::text[])', [[SOURCE, OTHER]]);
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES($1,$1),($2,$2)", [SOURCE, OTHER]);
+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [OTHER]);
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.terminal_failures.%' OR key='persistence.receipt_retention_days'");
+ });
+
+ test('the knock-on SQL twin agrees with isSyncKnockOn on every seeded receipt', async () => {
+ const cases = [
+ { slug: 'k1', operation: 'submit_job', state: 'cancelled', code: 'cancelled', message: WINDOW_CANCEL_MESSAGE, kind: 'managed_sync_import' },
+ { slug: 'k2', operation: 'submit_job', state: 'cancelled', code: 'cancelled', message: WINDOW_CANCEL_MESSAGE, kind: 'facts_extract' },
+ { slug: 'k3', operation: 'submit_job', state: 'cancelled', code: 'cancelled', compacted: true, detail: knockOnDetail('bulk_group', null) },
+ { slug: 'k4', operation: 'submit_job', state: 'cancelled', code: 'cancelled', message: 'Cancelled before publication.', kind: 'managed_sync_import' },
+ { slug: 'k5', operation: 'submit_job', state: 'cancelled', code: 'cancelled', compacted: true },
+ { slug: 'k6', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knockOnDetail('lane_fault', null) },
+ { slug: 'k7', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knockOnDetail('lane_fault', null), kind: 'facts_extract' },
+ { slug: 'k8', operation: 'submit_job', state: 'cancelled', code: 'cancelled', message: WINDOW_CANCEL_MESSAGE },
+ ];
+ for (const c of cases) await seed(c);
+ const rows = await engine.executeRaw<{ slug: string; sql: boolean; state: string; error_code: string; error_message: string | null; error_detail: unknown; intent: unknown }>(
+ `SELECT slug, ${terminalKnockOnSql('r')} AS sql, state, error_code, error_message, error_detail, intent FROM persistence_requests r ORDER BY slug`);
+ for (const row of rows) expect([row.slug, row.sql]).toEqual([row.slug, isSyncKnockOn({ ...row, recovery: null, publication_started: false } as never)]);
+ expect(rows.filter(row => row.sql).map(row => row.slug)).toEqual(['k1', 'k3', 'k6']);
+ });
+
+ test('blockers, unresolved, historical and defects are reported apart; archived sources are skipped', async () => {
+ const blocker = await seed({ slug: 'notes/held', state: 'committed', recovery: { version: 1, path: '/nonexistent/x.md', root: '/nonexistent', beforeHash: null, afterHash: 'a' } });
+ for (let i = 0; i < 3; i++) await seed({ slug: `sync/k${i}`, operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knockOnDetail('lane_fault', null), build: '0.60.200.0', hoursAgo: 30 });
+ const digest = randomUUID();
+ await seed({ slug: 'notes/drift', state: 'conflict', code: 'source_changed', message: 'The canonical file contains an uncoordinated local edit.', digest, hoursAgo: 50 });
+ await seed({ slug: 'notes/drift', state: 'committed', digest: randomUUID(), hoursAgo: 40 });
+ await seed({ slug: 'notes/drift2', state: 'conflict', code: 'source_changed', message: 'The canonical file contains an uncoordinated local edit.', hoursAgo: 60 });
+ await seed({ slug: 'notes/opaque', state: 'failed', code: 'storage_error', compacted: true, hoursAgo: 2 });
+ await seed({ source: OTHER, slug: 'notes/gone', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception' } });
+ const summary = await readTerminalFailureSummary(engine);
+ expect(summary.status).toBe('ok');
+ if (summary.status !== 'ok') return;
+ expect(summary.sources.map(s => s.source_id)).toEqual([SOURCE]);
+ const s = summary.sources[0]!;
+ expect(s.active_blockers).toEqual([expect.objectContaining({ kind: 'recovery', request_id: blocker, slug: 'notes/held', category: 'recovery_pending' })]);
+ expect(s.active_blockers[0]!.action.argv).toEqual(['gbrain', 'sync', '--source', SOURCE, '--no-pull', '--json']);
+ // Three old-build knock-ons and the drift a later put_page superseded are history; the other drift and the opaque row are not.
+ expect(s.historical_rows).toBe(4);
+ expect(s.unresolved).toMatchObject({ rows: 2, distinct_slugs: 2, distinct_intents: 2 });
+ expect(s.unresolved.oldest_age_seconds).toBeGreaterThanOrEqual(59 * 3600);
+ expect(s.defects).toEqual([]);
+ expect(s.new_last_24h).toBe(1);
+
+ const check = (await terminalFailuresCheck(engine))!;
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(`recovery record ${blocker} (notes/held) on source ${SOURCE}`);
+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'sync', '--source', SOURCE, '--no-pull', '--json']);
+ expect((check.fix as { verify: { argv: string[] } }).verify.argv).toEqual(['gbrain', 'doctor', '--only', 'persistence_terminal_failures', '--json']);
+ expect(check.details).toMatchObject({ unresolved: { rows: 2 }, historical_rows: 4, new_last_24h: 1 });
+
+ // With the recovery record gone, nothing blocks and no defect is open: the pile alone does not warn.
+ await engine.executeRaw('UPDATE persistence_requests SET recovery=NULL WHERE request_id=$1::uuid', [blocker]);
+ expect((await terminalFailuresCheck(engine))!.status).toBe('ok');
+ // An owner exception is a gbrain defect: it warns whatever the trend, on an active source only.
+ await seed({ slug: 'notes/boom', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception', error_class: 'TypeError' }, hoursAgo: 100 });
+ const defect = (await terminalFailuresCheck(engine))!;
+ expect(defect.status).toBe('warn');
+ expect(defect.message).toContain('owner_exception/storage_error ×1');
+ });
+
+ test('a spike warns secondarily, against the zero-filled 7-day median, with its thresholds named as config keys', async () => {
+ expect(sevenDayMedian([0, 0, 1])).toBe(0);
+ await engine.setConfig('persistence.terminal_failures.spike_min', '3');
+ for (let i = 0; i < 4; i++) await seed({ slug: `notes/c${i}`, state: 'conflict', code: 'revision_conflict', hoursAgo: 1 });
+ const check = (await terminalFailuresCheck(engine))!;
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('above 3× the 7-day median (0/day');
+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE, '--group-by', 'category', '--json']);
+ expect(check.details).toMatchObject({ config: { spike_min: { key: 'persistence.terminal_failures.spike_min', value: 3 }, spike_factor: { key: 'persistence.terminal_failures.spike_factor', value: 3 } } });
+ expect(validateTerminalConfigValue('persistence.terminal_failures.window_days', '0')).toStartWith('persistence.terminal_failures.window_days must be a whole number');
+ expect(validateTerminalConfigValue('persistence.terminal_failures.spike_factor', '2.5')).toBeNull();
+ });
+
+ 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 });
+ expect(await readTerminalThresholds(engine, 2)).toMatchObject({ windowDays: 2, clamped: false });
+ });
+
+ test('the drill-down pages newest first with a cursor and groups with an exact filter', async () => {
+ const ids: string[] = [];
+ for (let i = 0; i < 5; i++) ids.push(await seed({ slug: `notes/r${i}`, state: 'conflict', code: 'revision_conflict', hoursAgo: 10 - i }));
+ const opaque = await seed({ slug: 'notes/opaque', state: 'failed', code: 'storage_error', compacted: true, hoursAgo: 1 });
+ const first = await readTerminalFailures(engine, { sourceId: SOURCE, limit: 2 });
+ if (first.status !== 'ok') throw new Error('unknown');
+ expect(first.rows!.map(r => r.request_id)).toEqual([opaque, ids[4]]);
+ expect(first.truncated).toBe(true);
+ expect(first.next).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE, '--limit', '2', '--before', first.next_cursor!, '--json']);
+ expect(first.rows![0]!.inspect.argv).toEqual(['gbrain', 'write-request', opaque, '--json']);
+ const second = await readTerminalFailures(engine, { sourceId: SOURCE, limit: 2, before: first.next_cursor! });
+ if (second.status !== 'ok') throw new Error('unknown');
+ expect(second.rows!.map(r => r.request_id)).toEqual([ids[3], ids[2]]);
+ const last = await readTerminalFailures(engine, { sourceId: SOURCE, limit: 2, before: (await readTerminalFailures(engine, { sourceId: SOURCE, limit: 4 }) as { next_cursor: string }).next_cursor });
+ if (last.status !== 'ok') throw new Error('unknown');
+ expect(last.rows!.map(r => r.request_id)).toEqual([ids[1], ids[0]]);
+ expect(last.truncated).toBe(false);
+
+ const grouped = await readTerminalFailures(engine, { sourceId: SOURCE, groupBy: 'category' });
+ if (grouped.status !== 'ok') throw new Error('unknown');
+ expect(grouped.groups!.map(g => [g.category, g.code, g.origin, g.rows])).toEqual([['caller_conflict', 'revision_conflict', null, 5], ['diagnosis_required', 'storage_error', null, 1]]);
+ const group = grouped.groups![1]!;
+ expect(group.drill_down).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE, '--category', 'diagnosis_required', '--code', 'storage_error', '--origin', 'none', '--json']);
+ expect(group.samples[0]!.inspect.argv).toEqual(['gbrain', 'write-request', opaque, '--json']);
+ const filtered = await readTerminalFailures(engine, { sourceId: SOURCE, category: 'diagnosis_required', code: 'storage_error', origin: 'none' });
+ if (filtered.status !== 'ok') throw new Error('unknown');
+ expect(filtered.rows!.map(r => r.request_id)).toEqual([opaque]);
+ });
+
+ test('a read past its statement deadline is unknown, and doctor says health is unknown', async () => {
+ await seed({ slug: 'notes/x', state: 'failed', code: 'storage_error', compacted: true });
+ const slow = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: unknown) => {
+ if (sql.includes('GROUPING SETS') || sql.includes('LEFT JOIN LATERAL')) throw Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+ return target.executeRaw(sql, params, opts as never);
+ };
+ return Reflect.get(target, key);
+ } }) as BrainEngine;
+ expect((await readTerminalFailureSummary(slow)).status).toBe('unknown');
+ expect((await readTerminalFailures(slow, { sourceId: SOURCE })).status).toBe('unknown');
+ const check = (await terminalFailuresCheck(slow))!;
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ health: 'unknown' });
+ });
+
+ if (kind === 'postgres') test('on Postgres the statement deadline is real: a read blocked behind a table lock is unknown, not empty', async () => {
+ await seed({ slug: 'notes/x', state: 'failed', code: 'storage_error', detail: { origin: 'owner_exception' } });
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ let locked!: () => void;
+ const acquired = new Promise<void>(resolve => { locked = resolve; });
+ const holder = engine.transaction(async tx => { await tx.executeRaw('LOCK TABLE persistence_requests IN ACCESS EXCLUSIVE MODE'); locked(); await held; });
+ await acquired;
+ try {
+ const started = Date.now();
+ expect((await readTerminalFailureSummary(engine)).status).toBe('unknown');
+ expect(Date.now() - started).toBeLessThan(TERMINAL_STATEMENT_MS + TERMINAL_ACQUIRE_MS + 3_000);
+ expect((await readTerminalFailures(engine, { sourceId: SOURCE })).status).toBe('unknown');
+ } finally { release(); await holder; }
+ const after = await readTerminalFailureSummary(engine);
+ expect(after.status === 'ok' && after.sources[0]?.unresolved.rows).toBe(1);
+ }, 60_000);
+
+ test('the SQL twin of historical-by-build covers every fixed class and agrees with the classifier', async () => {
+ expect(Object.keys(TERMINAL_HISTORICAL_SQL).sort()).toEqual(Object.keys(TERMINAL_FIXED_IN).sort());
+ const knock = knockOnDetail('lane_fault', null);
+ await seed({ slug: 'h1', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knock, build: '0.60.215.9' });
+ await seed({ slug: 'h2', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knock, build: '0.60.216.0' });
+ await seed({ slug: 'h3', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: { ...knock, attempt: { consumer_version: '0.59.1', consumer_host_id: null } }, build: '0.60.300.0' });
+ await seed({ slug: 'h4', state: 'failed', code: 'storage_error', message: 'Publication failed (P0001). Inspect owner diagnostics.' });
+ await seed({ slug: 'h5', state: 'failed', code: 'storage_error', message: 'Publication failed (P0001 in x: unknown). Inspect owner diagnostics.', detail: { origin: 'database_trigger', raiser: 'x' } });
+ await seed({ slug: 'h6', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knock, build: 'dev-build' });
+ const all = Object.values(TERMINAL_HISTORICAL_SQL).map(sql => sql('b')).join(' OR ');
+ const rows = await engine.executeRaw<{ slug: string; flag: boolean; state: string; error_code: string; error_message: string | null; error_detail: Record<string, unknown> | null; operation: string;
+ compacted: boolean; build: string | null }>(`SELECT b.*, (${all}) AS flag FROM (SELECT r.slug, r.state, r.error_code, r.error_message, r.error_detail, r.operation, r.compacted,
+ r.error_detail->>'origin' AS origin, r.recovery IS NOT NULL AS has_recovery, ${terminalKnockOnSql('r')} AS knock_on,
+ CASE WHEN r.error_detail IS NULL AND r.error_message LIKE 'Publication failed (P0001)%' THEN 'Publication failed (P0001)' END AS routed_message,
+ COALESCE(r.error_detail->'attempt'->>'consumer_version', r.admitter_version) AS build FROM persistence_requests r) b ORDER BY b.slug`);
+ const ts = rows.map(row => [row.slug, classifyTerminal({ ...base, ...row, recovery: null, blocked_reason: null })!.historical]);
+ expect(rows.map(row => [row.slug, row.flag])).toEqual(ts as never);
+ expect(ts).toEqual([['h1', true], ['h2', false], ['h3', true], ['h4', true], ['h5', false], ['h6', false]]);
+ });
+
+ test('the extracted supersession rule is the one failed-writes applies', async () => {
+ const digest = randomUUID();
+ await seed({ slug: 'notes/s', state: 'failed', code: 'writer_coordinator_required', digest, hoursAgo: 5 });
+ await seed({ slug: 'notes/s', state: 'committed', digest, hoursAgo: 4 });
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests r JOIN persistence_requests c ON ${supersessionSql('r', 'c')} WHERE r.state='failed'`);
+ expect(row!.n).toBe(1);
+ expect(categorizeCheck('persistence_terminal_failures')).toBe('ops');
+ expect(WAVE_CHECKS.find(spec => spec.id === 'persistence_terminal_failures')).toMatchObject({ resolution: 'operator', registration: 'wave' });
+ });
+});
diff --git a/test/write-request-diagnosis-6650.test.ts b/test/write-request-diagnosis-6650.test.ts
new file mode 100644
index 0000000000..f57b795f6d
--- /dev/null
+++ b/test/write-request-diagnosis-6650.test.ts
@@ -0,0 +1,77 @@
+/**
+ * #6650 (L3 item 2): `gbrain write-request <id>` (get_write_request) returns the suggestion `writeFailureDiagnostic`
+ * already computes and the structured fix of the receipt's read-time classification, instead of dropping both.
+ * A compacted receipt whose code covers several causes gets `diagnosis_required` with a read-only inspection,
+ * never a guessed fix. PGLite in-memory.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomBytes, randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite } from '../src/core/persistence/journal.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+
+const SOURCE = 'diag-6650';
+let engine: PGLiteEngine;
+let owner: LocalRegistration;
+const context = (): OperationContext => ({ engine, config: { engine: 'pglite' }, remote: false, sourceId: SOURCE, dryRun: false, logger: { info() {}, warn() {}, error() {} } });
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [SOURCE]);
+ owner = { id: randomUUID(), credential: randomBytes(32).toString('hex'), lane: 'cli' };
+ await engine.executeRaw('INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling) VALUES($1,$2,$3,$4::jsonb)', [owner.id, owner.lane, sha256(owner.credential),
+ JSON.stringify({ sourceIds: ['*'], operations: ['put_page', 'get_write_request'], scopes: ['read', 'write'], slugPrefixes: null })]);
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); });
+
+async function receiptFor(slug: string, patch: { state: string; error_code: string; error_message: string | null; compacted?: boolean }) {
+ const requestId = randomUUID();
+ await withVerifiedLocalRegistration(engine, owner, async () => {
+ const [s] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [SOURCE]);
+ const authority = await submissionAuthority(context(), 'put_page', SOURCE, s.incarnation, slug);
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: SOURCE, sourceIncarnation: s.incarnation, slug, requestId,
+ callerIntent: { content: 'x' }, intent: { content: 'x' } });
+ });
+ await engine.executeRaw(`UPDATE persistence_requests SET state=$2, error_code=$3, error_message=$4, completed_at=now(), compacted=$5, intent=CASE WHEN $5 THEN NULL ELSE intent END
+ WHERE request_id=$1::uuid`, [requestId, patch.state, patch.error_code, patch.error_message, patch.compacted === true]);
+ const op = operations.find(operation => operation.name === 'get_write_request')!;
+ return withVerifiedLocalRegistration(engine, owner, () => op.handler(context(), { request_id: requestId })) as Promise<Record<string, any>>;
+}
+
+test('a drift refusal returns the computed suggestion and the reconcile preview as its structured fix', async () => {
+ const receipt = await receiptFor('notes/drifted', { state: 'conflict', error_code: 'source_changed', error_message: 'The canonical file contains an uncoordinated local edit.' });
+ expect(receipt.write_error).toBe('source_changed');
+ expect(receipt.write_error_reason).toBe('file_database_drift');
+ expect(receipt.suggestion).toContain('gbrain sources reconcile <source> <slug>');
+ expect(receipt.diagnosis).toMatchObject({ category: 'file_conflict', class: 'page', safe_actions: ['reconcile'], needs_human: true });
+ expect(receipt.diagnosis.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', SOURCE, 'notes/drifted', '--preview']);
+ expect(receipt.diagnosis.fix.next).toBe('run');
+ expect(receipt.diagnosis.fix.verify.argv.slice(0, 5)).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE]);
+});
+
+test('a compacted storage_error with no recorded origin is diagnosis_required, with a read-only inspection and no guessed fix', async () => {
+ const receipt = await receiptFor('notes/opaque', { state: 'failed', error_code: 'storage_error', error_message: null, compacted: true });
+ expect(receipt.diagnosis).toMatchObject({ category: 'diagnosis_required', code: 'storage_error', safe_actions: ['none'], needs_human: true });
+ expect(receipt.diagnosis.fix.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', SOURCE, '--json']);
+ expect(receipt.diagnosis.human_reason).toContain('does not record enough to name a fix');
+});
+
+test('a committed receipt carries no diagnosis', async () => {
+ const requestId = randomUUID();
+ await withVerifiedLocalRegistration(engine, owner, async () => {
+ const [s] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [SOURCE]);
+ const authority = await submissionAuthority(context(), 'put_page', SOURCE, s.incarnation, 'notes/done');
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: SOURCE, sourceIncarnation: s.incarnation, slug: 'notes/done', requestId,
+ callerIntent: { content: 'y' }, intent: { content: 'y' } });
+ });
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed', completed_at=now() WHERE request_id=$1::uuid", [requestId]);
+ const op = operations.find(operation => operation.name === 'get_write_request')!;
+ const receipt = await withVerifiedLocalRegistration(engine, owner, () => op.handler(context(), { request_id: requestId })) as Record<string, unknown>;
+ expect(receipt.diagnosis).toBeUndefined();
+ expect(receipt.suggestion).toBeUndefined();
+});
diff --git a/test/writer-failures-cli-6650.test.ts b/test/writer-failures-cli-6650.test.ts
new file mode 100644
index 0000000000..d9f045a024
--- /dev/null
+++ b/test/writer-failures-cli-6650.test.ts
@@ -0,0 +1,152 @@
+/**
+ * #6650 (L3): `gbrain sources writer failures <source>`.
+ *
+ * Protects: the verb parses and dispatches through local administration (the same path a resident owner runs);
+ * every option is validated with the usage it takes and an unknown or archived source is refused; the human table
+ * names the next command and the JSON carries rendered `fix.command` / `inspect` for each row and group; a full
+ * page prints `truncated` with the exact next command. The capability handshake stays compatible both ways: the
+ * owner's frozen `administration` list is unchanged (an older client rejects an owner listing an entry it does not
+ * know), the new operation rides `administration_extensions`, a client keeps only extension entries it knows, and a
+ * client never sends `writer_failures` to an owner that does not list it. PGLite in-memory and a local socket.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import net, { type Server } from 'node:net';
+import { once } from 'node:events';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts';
+import { renderWriterFailures } from '../src/commands/sources-writer-failures.ts';
+import type { TerminalFailureListing } from '../src/core/persistence/terminal-failures.ts';
+import { PERSISTENCE_ADMIN_OPERATIONS } from '../src/core/persistence/admin-contract.ts';
+import { ownerAdministers, requestPersistenceCapabilities, startPersistenceIpcServer, type PersistenceIpcBinding } from '../src/core/persistence/ipc.ts';
+
+const SOURCE = 'wf-src';
+const ARCHIVED = 'wf-archived';
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [SOURCE]);
+ await engine.executeRaw('INSERT INTO sources(id,name,archived) VALUES($1,$1,true)', [ARCHIVED]);
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function seed(slug: string, code: string, detail: unknown, hoursAgo = 1): Promise<string> {
+ const requestId = randomUUID();
+ await engine.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)
+ VALUES('local_cli','fixture',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,'failed',$5,'x',$6::text::jsonb,'{"content":"x"}'::jsonb,
+ now()-($7::double precision*interval '1 hour'),now()-($7::double precision*interval '1 hour'),'0.60.216.0')`,
+ [requestId, SOURCE, slug, randomUUID(), code, JSON.stringify(detail), hoursAgo]);
+ return requestId;
+}
+
+describe('sources writer failures', () => {
+ test('parses the verb, its source and its options', () => {
+ expect(parsePersistenceAdminArgs('writer', ['failures', SOURCE, '--group-by', 'category', '--limit', '5', '--json'])).toEqual({
+ operation: 'writer_failures', params: { source_id: SOURCE, group_by: 'category', limit: 5 }, json: true });
+ expect(parsePersistenceAdminArgs('writer', ['failures', SOURCE, '--state', 'all', '--since', '3d', '--origin', 'none', '--before', '12'])).toMatchObject({
+ operation: 'writer_failures', params: { source_id: SOURCE, state: 'all', since: '3d', origin: 'none', before: '12' }, json: false });
+ });
+
+ test('refuses bad options, a missing source and an archived one with the usage to fix it', async () => {
+ const run = (params: Record<string, unknown>) => runPersistenceAdministration(engine, 'writer_failures', params);
+ await expect(run({})).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(run({ source_id: 'wf-missing' })).rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('No active source') });
+ await expect(run({ source_id: ARCHIVED })).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(run({ source_id: SOURCE, since: '7' })).rejects.toMatchObject({ code: 'invalid_params', message: 'Invalid --since value.' });
+ await expect(run({ source_id: SOURCE, group_by: 'slug' })).rejects.toMatchObject({ code: 'invalid_params', message: 'Invalid --group-by value.' });
+ await expect(run({ source_id: SOURCE, limit: 0 })).rejects.toMatchObject({ code: 'invalid_params', message: 'Invalid --limit value.' });
+ await expect(run({ source_id: SOURCE, before: 'abc' })).rejects.toMatchObject({ code: 'invalid_params', message: 'Invalid --before value.' });
+ await expect(run({ source_id: SOURCE, slug: 'x' })).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+
+ test('lists through administration, pages with the next command, and renders a table or JSON', async () => {
+ const ids = [] as string[];
+ for (let i = 0; i < 3; i++) ids.push(await seed(`notes/owner-${i}`, 'storage_error', { origin: 'owner_exception', error_class: 'TypeError' }, 3 - i));
+ await seed('notes/drift', 'file_database_drift', { origin: 'file_database_drift' });
+
+ const page = await runPersistenceAdministration(engine, 'writer_failures', { source_id: SOURCE, limit: 2 }) as TerminalFailureListing & { status: 'ok' };
+ expect(page.rows!.length).toBe(2);
+ expect(page.truncated).toBe(true);
+ expect(page.next).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE, '--limit', '2', '--before', page.next_cursor!, '--json']);
+ const rest = await runPersistenceAdministration(engine, 'writer_failures', { source_id: SOURCE, limit: 2, before: page.next_cursor! }) as TerminalFailureListing & { status: 'ok' };
+ expect(rest.truncated).toBe(false);
+ expect([...page.rows!, ...rest.rows!].map(r => r.request_id).filter(id => ids.includes(id)).sort()).toEqual([...ids].sort());
+
+ const json = JSON.parse(renderWriterFailures(page, true));
+ expect(json.rows[0].inspect).toMatchObject({ next: 'run', command: `gbrain write-request ${page.rows![0].request_id} --json` });
+ expect(typeof json.rows[0].fix.next).toBe('string');
+ const table = renderWriterFailures(page, false);
+ expect(table).toContain(`Source ${SOURCE}: 2 unresolved receipts of the last 7 d.`);
+ expect(table).toContain(page.rows![0].request_id);
+ expect(table).toContain(`More: gbrain sources writer failures ${SOURCE} --limit 2 --before ${page.next_cursor} --json`);
+
+ const grouped = await runPersistenceAdministration(engine, 'writer_failures', { source_id: SOURCE, group_by: 'category' }) as TerminalFailureListing & { status: 'ok' };
+ const owner = grouped.groups!.find(g => g.category === 'owner_exception')!;
+ expect(owner.rows).toBe(3);
+ expect(owner.drill_down).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE, '--category', 'owner_exception', '--code', owner.code, '--origin', 'owner_exception', '--json']);
+ const groupedJson = JSON.parse(renderWriterFailures(grouped, true));
+ expect(groupedJson.groups[0].samples[0].inspect.command).toStartWith('gbrain write-request ');
+ expect(renderWriterFailures(grouped, false)).toContain(`rows: ${owner.drill_down.join(' ')}`);
+ });
+
+ test('an unknown read prints that nothing is concluded', () => {
+ const out = renderWriterFailures({ status: 'unknown', source_id: SOURCE, reason: 'the read did not finish' }, false);
+ expect(out).toContain('unknown (the read did not finish)');
+ expect(out).not.toContain('Nothing to show');
+ });
+});
+
+const bindings: PersistenceIpcBinding[] = [];
+const rawServers: Server[] = [];
+const dirs: string[] = [];
+const BRAIN = '10000000-0000-4000-8000-000000006650';
+function socketPath() { const dir = mkdtempSync(join(tmpdir(), 'gb-6650-ipc-')); dirs.push(dir); return join(dir, 'write.sock'); }
+afterEach(async () => {
+ for (const binding of bindings.splice(0)) { const closed = binding.server.listening ? once(binding.server, 'close') : Promise.resolve(); binding.close(); await closed; }
+ for (const server of rawServers.splice(0)) if (server.listening) { const closed = once(server, 'close'); server.close(); await closed; }
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+async function rawOwner(capabilities: Record<string, unknown>) {
+ const path = socketPath();
+ const server = net.createServer(socket => socket.once('data', () => socket.end(`${JSON.stringify({ version: 1, ok: true, result: capabilities })}\n`)));
+ rawServers.push(server); server.listen(path); await once(server, 'listening');
+ return path;
+}
+
+describe('capability handshake across releases', () => {
+ // The administration list as of 0.60.216.0. An older client drops an owner whose list names anything else.
+ const FROZEN = ['writer_status', 'writer_sync', 'writer_refresh', 'writer_extract_stale', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts',
+ 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept', 'writer_deactivate', 'writer_lock', 'writer_unlock', 'writer_git_durability',
+ 'local_writer_list', 'local_writer_register', 'local_writer_revoke', 'source_lifecycle', 'source_add', 'company_brain_preview', 'company_brain_connect',
+ 'company_brain_resume', 'writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',
+ 'trust_read', 'trust_preview', 'trust_apply'];
+
+ test('a new owner keeps the frozen list and advertises writer_failures as an extension', async () => {
+ expect([...PERSISTENCE_ADMIN_OPERATIONS as readonly string[]].sort()).toEqual([...FROZEN].sort());
+ const path = socketPath();
+ const binding = await startPersistenceIpcServer(path, { brainId: BRAIN, dispatch: async () => ({}), administer: async () => ({}) });
+ bindings.push(binding!);
+ const capability = await requestPersistenceCapabilities(path);
+ expect((capability.administration ?? []).every(op => FROZEN.includes(op))).toBe(true);
+ expect(capability.administration_extensions).toEqual(['writer_failures']);
+ expect(ownerAdministers(capability, 'writer_failures')).toBe(true);
+ expect(ownerAdministers(capability, 'writer_status')).toBe(true);
+ });
+
+ test('a client keeps only extension entries it knows and never calls writer_failures on an owner that does not list it', async () => {
+ const base = { version: 1, brain_id: BRAIN, operations: ['get_write_request'], max_frame_bytes: 1024, administration: ['writer_status'] };
+ const future = await requestPersistenceCapabilities(await rawOwner({ ...base, administration_extensions: ['writer_failures', 'writer_from_the_future'] }));
+ expect(future.administration_extensions).toEqual(['writer_failures']);
+ const malformed = await requestPersistenceCapabilities(await rawOwner({ ...base, administration_extensions: 'writer_failures' }));
+ expect(malformed.administration_extensions).toBeUndefined();
+ expect(ownerAdministers(malformed, 'writer_failures')).toBe(false);
+ const older = await requestPersistenceCapabilities(await rawOwner(base));
+ expect(ownerAdministers(older, 'writer_failures')).toBe(false);
+ expect(ownerAdministers(older, 'writer_status')).toBe(true);
+ });
+});