Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Data-integrity follow-ups: purges keep outcome rows, the secret audit sees glued passwords, guard refusals are typed

garrytan4f0af5766004
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index fad4efb266..7ca58ebfbc 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -454,9 +454,16 @@ does not own a function, v277 names it on stderr and leaves it; `gbrain doctor`
**Writer-protocol fences.** The managed-writer guard, the persistence protocol floor, protocol
activation and the Git-canonical source counter also run as the writing role and read their state
under its RLS. Since migration v278 (#7636) they fail closed: a role that cannot see the
-`persistence_brain` row is refused with `writer_coordinator_required` (relationship
-`unreadable_state`) on every guarded write, managed brain or not, instead of being treated as
-unmanaged. On a managed brain the same refusal covers a hidden `git_canonical_brain` row or
+`persistence_brain` row is refused on every guarded write, managed brain or not, instead of being
+treated as unmanaged. The message is `writer_coordinator_required: writer state is unreadable to
+this database role`: the managed-writer guard raises it as P0001, the request, effect and
+activation guards of the persistence protocol as SQLSTATE 42501. During a coordinated write's
+publication either one is stored on the receipt as `writer_coordinator_required` (relationship
+`unreadable_state`, the role remedy, and the owner-only `error_detail.state` naming the table; since
+#7777 for the protocol guards, #7780 for the state and remedy). A protocol guard's
+refusal outside publication (write admission, protocol activation) reaches the command as that
+database error, which gbrain's generic database output labels `permission_denied` with grant
+advice: the code at the start of the message names the refusal. On a managed brain the same refusal covers a hidden `git_canonical_brain` row or
Git-canonical source row (for a writer without the git protocol) and a hidden page row behind a tag,
timeline entry or take. Protocol activation (row-level security on `sources`, `persistence_requests`,
`persistence_effects`, `persistence_worktrees` or `persistence_source_bindings`) and a change to
@@ -998,7 +1005,7 @@ names — reasons may be added, never renamed or removed). All 16:
| `no_url` | nothing configured at all — `gbrain init --prefer-postgres` (or `gbrain init` for PGLite) |
| `env_shadowed` | a cwd-.env `DATABASE_URL` exists but the cwd-.env guard excludes it — export `GBRAIN_DATABASE_URL` |
| `auth_failed` | password/role rejected (28P01) — reset credentials, then `gbrain init --url <conn>` |
-| `permission_denied` | 28000/42501 — the role lacks a GRANT or hits RLS |
+| `permission_denied` | 28000/42501 — the role lacks a GRANT or hits RLS; a 42501 whose message starts with a writer code (`writer_coordinator_required:`, `writer_upgrade_required:`, `writer_not_quiesced:`, `unsupported_mutation_protocol:`) is a persistence protocol guard's refusal ([write refusals](guides/write-refusals.md#protocol-guard)) |
| `tenant_not_found` | Supavisor rejected the tenant — pooler usernames are `postgres.<project-ref>`; also raised by paused projects |
| `ssl_required` | the server demands SSL — `?sslmode=require` rewrite (rewrite tier) |
| `pool_exhausted` | 53300 / session-slot exhaustion — [pool sizing](#pool-sizing) guidance: `export GBRAIN_POOL_SIZE=6` per long-running process, fewer processes |
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index f0a234c8ff..ee48444d6c 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -8,7 +8,7 @@ See [generations](generations.md) and [continued entries](canonical-reconciliati
- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list (or rows advancing a date), an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).
-- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE, a severity and a routine; never a PL/pgSQL RAISE or ASSERT or another class P0 error) also keeps `error_text` (its primary message, at most 240 characters; object names survive only in a known catalog message such as a not-null violation, or a syntax-error or does-not-exist message whose name the statement holds as an identifier; any other message loses everything from its first quote to its last, because Postgres does not escape quotes inside a value) and `statement` (the failing SQL tokenized: keywords, identifiers, parameter markers and operators, with every literal, E-string, dollar-quoted body, number and comment replaced or dropped, cut at anything unrecognized, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).
+- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and `state` and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE, a severity and a routine; never a PL/pgSQL RAISE or ASSERT or another class P0 error) also keeps `error_text` (its primary message, at most 240 characters; object names survive only in a known catalog message such as a not-null violation, or a syntax-error or does-not-exist message whose name the statement holds as an identifier; any other message loses everything from its first quote to its last, because Postgres does not escape quotes inside a value) and `statement` (the failing SQL tokenized: keywords, identifiers, parameter markers and operators, with every literal, E-string, dollar-quoted body, number and comment replaced or dropped, cut at anything unrecognized, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).
- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Unmanaged atom items complete as one generation; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
@@ -36,7 +36,7 @@ See [generations](generations.md) and [continued entries](canonical-reconciliati
- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). The window ends at the source's own newest request (current incarnation, the `(source_incarnation, sequence)` index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant `source_id` through `resolveRequestedScope`. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison; reason `canonical_file_missing` for a live page whose canonical file is gone, `file_missing` for any other `source_changed`) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file `path`. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).
- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`. GBRA-133: an agreeing hold is a `ReleasePage` (`release_hold`; apply re-checks the pins, then `requestGitHoldRetry` for its path); a page with no file origin (`recordsNoFileOrigin`) adopts `slugPathFile` (the spelling sync imports); file wins writes `fileWinsContent` (file bytes plus appended protected keys and timeline rows) or refuses `file_wins_rewrite`. Test: `test/sync-holds-wave-gbra133.test.ts`.
- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.
-- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.
+- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target, a code or image ghost's recorded file (#7967), is the approved path with no bytes, so publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.
- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).
- `src/core/persistence/unindexed-files.ts` — #6865 the unindexed-file detector: `findUnindexedFiles(engine, sourceId, opts)` streams `git ls-tree -r -l -z` of the source's last synced commit, filters it through discovery's own `loadSyncEligibility`, and in batches (one `pages.source_path = ANY` read on `pages_source_path_idx`, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (`readGitHoldRetryPaths`; those count as `scheduled`); a file whose path slug belongs to a live page with another or no origin is still unindexed and counted `slug_taken`. Found files are screened read-only with `screenImportContent` (at most 2,000 per pass, the rest `unscreened`). Folder-scaffolding names sync skips on purpose (`isSyncMetafile`) that would otherwise be eligible (checked against a probe name in the same directory plus `sync.exclude` and the reserved skill paths) and carry a frontmatter `type:` or `title:` are counted apart as `metafile_skipped` (only under `sync.metafile_pages off`: under the default `typed` the eligibility predicate admits a nested one, so it is an ordinary unindexed file; each tree batch primes its metafile heads) with samples, and never scheduled. A time or count budget stops it with `complete: false` and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). `refreshUnindexedFiles` continues an incomplete stored result of the same incarnation and eligibility also after the source's commit moved (#7149): it first re-examines the paths before the cursor that changed between the two commits (`git diff-tree`; more than `UNINDEXED_REVISIT_CAP`, or an unreadable old commit, starts over), then resumes after the cursor. It schedules the found paths (`requestGitHoldRetry`, a scheduling write only) and stores one `op_checkpoints` row per source (op `unindexed-files`, fingerprint the source id; the 7-day checkpoint purge applies). `unindexedScanBudgetMs` sizes one pass's budget: 60 s per started 100k live pages, at most 5 min. `judgeUnindexedFiles` is doctor's read without scanning: a scheduled path with a page or a hold is settled even while the retry row still names it (#7149); of the rest, those in the retry row wait for a sync and the others are still unindexed. Tests: `test/unindexed-files.test.ts`, `test/unindexed-files-convergence-7149.test.ts`.
- `src/commands/doctor/checks/unindexed-files.ts` — #6865 doctor `unindexed_files` (BRAIN, after `missing_recorded_files`): reads `judgeUnindexedFiles` for each bound managed Git source; `ok` when every result is complete, recent and nothing is missing; `warn` with counts by code, samples and age when files are unindexed (fix `gbrain sources retry-held <id> --unindexed`, `then` the follow-up sync from `gitFollowUpSync`, verify `gbrain doctor --only unindexed_files --json`) or scheduled and waiting (fix the sync); info `unknown` when a result is missing, older than 7 days or incomplete with nothing found, naming the maintenance phase and the command; info `not_applicable` on a classic brain. `metafile_skipped` files are named in the message and details and never make it warn; alone they are info `degraded` with a `user` fix (rename the file, then the sync). Test: `test/unindexed-files.test.ts`.
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index 2c4742f32c..31c47d71b7 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -21,7 +21,7 @@ Patterns, drift reports and the cycle modules listed after them.
- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.
-- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory (`derivedFileTarget`), replaces an existing file only when `replaceableFile` (`facts/file-body-guard.ts`) finds it equal to the page or one of its recent page_versions rows, then calls `writePageThrough` bound to the bytes compared with `inlineOnly` (a generated page stored in segments is skipped `segmented_page`, since the batch rollback compares file strings) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. #8073: every file write and retired-file unlink is uncommitted (`deferCommit`) and the batch (an item's atoms plus its retired atoms' files, the backfill, or one concept) commits once through the shared-checkout door `commitPathsLocked` (`git/commit-push.ts`) under the source filesystem lock, naming only the batch's paths that exist or are tracked; a directory that is not a Git checkout, or whose checkout lookup fails (`classifyGitCheckout` `unknown`), has nothing to commit. A refused commit leaves a file whose change HEAD already holds (another writer's locked commit swept it from the ledger) as committed, restores each other file still holding the bytes the batch wrote (`WriteThroughResult.content`; prior bytes, or removed), clears the `source_path` the write bound so the next backfill rewrites it, and returns a typed `DerivedCommitFailure` (`{code, message, paths, kept}`); the hook then writes nothing more that run and the phases report `details.write_through_failed` with `warn` (`reportDerivedWriteThrough`), while `writeDerivedPageThrough` returns it as `error` so the concept is held. Each file written or removed is also recorded in the door's pending ledger (`notePending`) right after the write, so a crash before the commit leaves it for the next `commitPathsLocked` in that checkout to sweep (ledger paths inside the source root that still differ from HEAD; only paths gbrain wrote are recorded). The dream reverse-write (`writeDreamPageFile`, `removeDreamPageFile`, `reverseWriteDreamRefs`) commits the same way: one batch per `reverseWriteDreamRefs` call (committed in a `finally`, so an abort still commits what it wrote) and one per summary write or retired-file removal; a refused commit rolls the files back and returns or pushes a `write_through_failed` hold, which the phases report through their existing `file_holds`. A checkout carrying a canonical owner marker commits through `commitAndPush`'s named-paths-only path (`commitManagedPaths`), and paths git ignores are left uncommitted. Tests: `test/cycle/derived-write-through-commit.test.ts` (with the `derivedWriteSeams.beforeCommit` crash fault point) and `test/cycle/dream-reverse-write-commit.test.ts` (PGLite and Postgres). A retired atom's file is removed under the same filter and comparison, the unlink rechecking the bytes under the source filesystem lock. A file holding an edit the database lacks (or an unindexed file at a backfilled page's path) is left as it is and listed in the hook's `held`, which both phases report as `details.file_holds` (`file_database_drift`) with a `warn` status. Tests: `test/cycle/derived-write-through.test.ts`, `test/pathological/d10-derived-atom-file-overwrite.test.ts`, `test/pathological/d11-derived-retired-atom-unlink.test.ts`. #6982: `writeDreamPageFile` is the dream reverse-write (synthesize, patterns, the cycle summary): nothing with `sync.write_through` off, for an owned url clone or a `storage.db_only` slug; the path is `resolvePageWriteTarget`'s (recorded source_path), falling back to the caller's brainDir layout when the source has no root or its root is missing; the file is replaced only when `replaceableFile` (facts/file-body-guard.ts) finds nothing in it the database lacks and, once the replacement is staged, still holds the compared bytes right before the rename, else the result carries the `file_database_drift` hold. It writes directly (not `writePageThrough`/`atomicWriteFileSync`) because a checkout a subagent tool write claimed through the coordinator refuses those with `writer_coordinator_required`. `reportFileHolds` lists every phase's holds in `details.file_holds` and turns ok into warn.
+- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory (`derivedFileTarget`), replaces an existing file only when `replaceableFile` (`facts/file-body-guard.ts`) finds it equal to the page or one of its recent page_versions rows, then calls `writePageThrough` bound to the bytes compared with `inlineOnly` (a generated page stored in segments is skipped `segmented_page`, since the batch rollback compares file strings) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. #8073: every file write and retired-file unlink is uncommitted (`deferCommit`) and the batch (an item's atoms plus its retired atoms' files, the backfill, or one concept) commits once through the shared-checkout door `commitPathsLocked` (`git/commit-push.ts`) under the source filesystem lock, naming only the batch's paths that exist or are tracked; a directory that is not a Git checkout, or whose checkout lookup fails (`classifyGitCheckout` `unknown`), has nothing to commit. A batch waits for a busy commit lock without blocking the event loop (`acquireCommitLockAsync`, up to 30 s), then takes it synchronously with a 2 s cap. A refused commit is rolled back under the commit lock (2 s wait; still busy, nothing is restored and every file stays in the pending ledger for that writer's commit): it leaves a file whose change HEAD already holds (another writer's locked commit swept it from the ledger) as committed, restores each other file still holding the bytes the batch wrote (`WriteThroughResult.content`; prior bytes, or removed), clears the `source_path` the write bound, settles the restored paths out of the ledger (`settlePending`), and returns a typed `DerivedCommitFailure` (`{code, message, paths, kept}`); the hook then writes nothing more that run and the phases report `details.write_through_failed` with `warn` (`reportDerivedWriteThrough`), while `writeDerivedPageThrough` returns it as `error` so the concept is held. Each page whose change was rolled back or left unwritten is marked in `op_checkpoints` (op `derived-write-retry`, fingerprint `<source>:<slug>`, pruned after the usual 7 days), and the next hook's backfill selects marked pages, live (rewritten, an update of an existing file included) and retired (file removed), clearing each mark once its change commits. Each file written or removed is also recorded in the door's pending ledger (`notePending`) right after the write, so a crash before the commit leaves it for the next `commitPathsLocked` in that checkout to sweep (ledger paths inside the source root that still differ from HEAD; only paths gbrain wrote are recorded). The dream reverse-write (`writeDreamPageFile`, `removeDreamPageFile`, `reverseWriteDreamRefs`) commits the same way: one batch per `reverseWriteDreamRefs` call (committed in a `finally`, so an abort still commits what it wrote) and one per summary write or retired-file removal; a refused commit rolls the files back and returns or pushes a `write_through_failed` hold, which the phases report through their existing `file_holds`. A checkout carrying a canonical owner marker commits through `commitAndPush`'s named-paths-only path (`commitManagedPaths`), and paths git ignores are left uncommitted. Tests: `test/cycle/derived-write-through-commit.test.ts` (with the `derivedWriteSeams.beforeCommit` crash fault point) and `test/cycle/dream-reverse-write-commit.test.ts` (PGLite and Postgres). A retired atom's file is removed under the same filter and comparison, the unlink rechecking the bytes under the source filesystem lock. A file holding an edit the database lacks (or an unindexed file at a backfilled page's path) is left as it is and listed in the hook's `held`, which both phases report as `details.file_holds` (`file_database_drift`) with a `warn` status. Tests: `test/cycle/derived-write-through.test.ts`, `test/pathological/d10-derived-atom-file-overwrite.test.ts`, `test/pathological/d11-derived-retired-atom-unlink.test.ts`. #6982: `writeDreamPageFile` is the dream reverse-write (synthesize, patterns, the cycle summary): nothing with `sync.write_through` off, for an owned url clone or a `storage.db_only` slug; the path is `resolvePageWriteTarget`'s (recorded source_path), falling back to the caller's brainDir layout when the source has no root or its root is missing; the file is replaced only when `replaceableFile` (facts/file-body-guard.ts) finds nothing in it the database lacks and, once the replacement is staged, still holds the compared bytes right before the rename, else the result carries the `file_database_drift` hold. It writes directly (not `writePageThrough`/`atomicWriteFileSync`) because a checkout a subagent tool write claimed through the coordinator refuses those with `writer_coordinator_required`. `reportFileHolds` lists every phase's holds in `details.file_holds` and turns ok into warn.
- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `replaceConceptProvenanceLinks` banks the concept-provenance edges and retires the edges of atoms that left the group in one transaction (coordinated on a managed brain), only while the concept is at the revision its publication produced (GBRA-161 PR 5, C-4). On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's canonical file holds anything the database lacks (`replaceableFile`: body, fences, timeline, frontmatter, tags, type or title equal to neither the page nor a recent page_versions row; formatting is ignored; this also covers an unindexed file at a new concept's path, and the message names the page with `file_database_drift`), and otherwise composes the new narrative with the database's latest fences, timeline, tags and frontmatter, so a take added during synthesis survives (`test/pathological/d12-concept-stale-fences.test.ts`, `d13-concept-occupied-path.test.ts`). The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds rep... (line truncated to 2000 chars)
- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 72e6eefdf0..2c697d949c 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#purge).
-- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`; the segmented preimage version by `test/large-pages/purge-fact-segmented-preimage.test.ts` (inline twin parity, both engines). Segmented pages (Wave B): live bodies are rewritten fence by fence through `rewriteLiveSegmentedFences` (a new generation; only the rewritten occurrences' chunks change, an unsealed page is projected after commit), and each rewritten page gets the preimage version an inline page gets: a segmented version of the revision the flip moved off, read before the flip and referencing the new generation (the body a reader of that revision sees under the purge's tombstone, as the inline preimage is read), so no generation holding the claim stays pinned; retained generations are rebuilt through `rewriteSegmentedGeneration`; the plan (and its digest) also lists open, sealed or prepared stagings whose staged texts or parts hold the claim plus the queued requests whose `body_ref` names them (`stagingsHoldingClaim`, which also reads `page_body_staging_texts`; `findRequestsHoldingStagings`): the stagings are aborted with their parts deleted, the requests cancelled with `purged_content` (a running or recovering one refuses with `purge_blocked_pending_recovery`), and the segment texts no manifest row references any more are deleted in the same transaction, never left to GC (`purgeSegmentStorage`, which the restore-time replay also runs).
+- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`) except extraction outcome rows (`outcomeMarkerSql`; the receipt's fact probes, `purgeCompletion` and the restore replay skip them too, #7831), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`; the segmented preimage version by `test/large-pages/purge-fact-segmented-preimage.test.ts` (inline twin parity, both engines). Segmented pages (Wave B): live bodies are rewritten fence by fence through `rewriteLiveSegmentedFences` (a new generation; only the rewritten occurrences' chunks change, an unsealed page is projected after commit), and each rewritten page gets the preimage version an inline page gets: a segmented version of the revision the flip moved off, read before the flip and referencing the new generation (the body a reader of that revision sees under the purge's tombstone, as the inline preimage is read), so no generation holding the claim stays pinned; retained generations are rebuilt through `rewriteSegmentedGeneration`; the plan (and its digest) also lists open, sealed or prepared stagings whose staged texts or parts hold the claim plus the queued requests whose `body_ref` names them (`stagingsHoldingClaim`, which also reads `page_body_staging_texts`; `findRequestsHoldingStagings`): the stagings are aborted with their parts deleted, the requests cancelled with `purged_content` (a running or recovering one refuses with `purge_blocked_pending_recovery`), and the segment texts no manifest row references any more are deleted in the same transaction, never left to GC (`purgeSegmentStorage`, which the restore-time replay also runs).
- `src/core/facts/purge-verify.ts` — receipts and verification. `verifyFactPurge` runs one bounded adapter per store (row bound, per-statement `statement_timeout`, a total deadline; `__setPurgeProbeLimitsForTests`): swept stores report `deleted`, `incomplete` (still holds the claim) or `unverified` (bound hit); page-text stores report remaining text as `out_of_scope: source_prose`; every `probed_reported` inventory table is probed and listed; derived rows are `retained_inactive`; model-derived pages without edges are `derived_legacy: unverified`. On-disk: page files (`canonical_markdown`), a quarantined `<file>.tmp` carrying the claim is deleted, the facts write-failure log is reported. `gitResidualCommits` scans `git log --all -p -- <page paths>` output in-process (the pattern never enters argv; byte and time bounded) and lists commits; `OUT_OF_REACH_RESIDUALS` lead every receipt. Links, timeline entries and raw data that still carry the claim are named row by row (`link:<id> <from> -> <to>`, `timeline:<id> <slug> <date>`, `raw_data:<id> <slug> <source>`, up to 20); queued `persistence_effects` whose data, outcome or recovery carry it are reported; `belief_events` and `fact_context` get ledger reports. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate. `purgeCompletion` derives `committed | complete | incomplete` from effects (failed or parked = incomplete), a fingerprint probe and the receipt, with exit codes 10/0/75. A segmented page or version is probed segment by segment (`segmentedBodyContains`, a needle split by a cut is found; row and time bounded) and reported with the page stores; `page_segment_texts` gets an exact-bytes probe (an unreferenced text holding the claim is `incomplete`, a referenced one `out_of_scope`); the page purge probes the texts its manifests referenced (`PagePurgeContext.segmentShas`).
- `src/core/belief/purge.ts` — the purge half of the belief ledger (BELIEF_LEDGER.md 6.5). Every fact or page purge bumps `sources.purge_epoch` (`bumpPurgeEpoch`; an append prepared at an older epoch with `preparedEpoch` refuses `belief_stale_preparation`) and runs three passes inside the purge transaction: `redactPurgedKeys` (the purged keys, by `claim_fp` and page lifetime, keep skeletons: value, value_hash and prior_hash null, `purged`), `redactCarryingFields` (keyset batches of 1000 reading only the carrying fields of fact, take and link events, matched in JS by `quotes` over `claimForms`, never SQL `lower()`/`strpos`: each carrying field from `CARRYING_FIELDS` that quotes a purged claim, plain or fence-escaped, becomes `REDACTION_MARKER(<purge request>)` and is listed in `redacted_fields`; a later event's prior_hash naming the old hash names the new one) with `registerLiveCarriers` (a surviving row whose field quotes the claim enters `belief_redactions` with its field hash, so its next event writes the marker until an explicit owner edit sets a different value: `publicationBeliefOptions` marks `ownerEdit` only on a local `put_page`, `edit_page`, `takes_update` or `takes_resolve` with no internal intent kind, and append still needs `OWNER_TIER_FLOOR`) and, for a fact purge, `registerVersionCarriers` (the retained versions still quoting the claim, registered under the keys the backfill gives them). A claim shorter than 8 characters quotes a field only as a word in spaced scripts (`ceo` does not match `herbaceous`; CJK and markup still match), and `appendDerivedHidden` (one `derived.hidden` per key the derivation walk hid; `readBeliefHistory` then hides that key's earlier events and every backfill event of it). A page purge's claims come from `pagePurgeClaims`: the page's facts and takes, every retained version's fence rows and every claim in its lifetimes' events, unbounded. `releaseSuppressedFields` is the owner release `trust confirm` runs (`belief_redactions.released_hash`); every release, there or in an owner-edit append, appends one `redaction.released` (`redactionReleasedDraft`: fields, purge requests and released hashes, never the text) in the publication `released_by` names. The receipt's `ledger` block reports the counts and `derived_walk`; a truncated walk withholds certification of its coverage interval (`coverage-report.ts`). Purge-verify's ledger report is a JS keyset scan too: a missed carrying field is `incomplete`, another subject's recorded value quoting the claim is `out_of_scope` with `field@key` items. Seam: `__setPurgeRedactionFaultForTests`. Probes: `test/belief-ledger-purge.test.ts` (both engines).
- `src/core/belief/purge-mirror.ts` — the text-free purge mirror `<brain home>/.gbrain/purge-events.jsonl` (0600, fsynced): an `intent` line before the purge commits (`appendPurgeIntent`; request, source and incarnation, scope, fingerprints, content hashes, lifetimes, epoch; never claim text; an unwritable mirror refuses the purge with the typed `purge_mirror_unwritable`, with or without a ledger) and a `committed` line after (`appendPurgeCommitted`, best effort; a page purge writes it from the coordinator's `afterCommit`, so it does not depend on the op handler finishing). `restorePgliteBackup` (`gbrain backup restore --purge-mirror <absolute path>` names a mirror other than the brain home's) replays every committed purge newer than the archive inside its transaction (`replayPurgesInRestore`: tombstones, row removal (a fact-scope replay rewrites page bodies and versions through `rewritePageBodies` / `redactPageVersions`, then runs `purgeSegmentStorage` with each claim's `stagingsHoldingClaim`; a page-scope replay deletes the page through `deletePageWithSegments`, so segment texts that held the purged content go in the replay, as in the purge), the three passes, the derived rows hidden again with `derived.hidden` cause `restore_replay`, one `fact.purged`/`page.purged` with cause `restore_replay`; a page-scope replay matches pages by content hash or lifetime, never by slug alone; an archive from before the ledger, no `belief_events`, replays tombstones and row removal and reports `ledger: 'absent'`; an intent whose request already has tombstones is skipped), records each as `complete`, `partial` (no restored row held the text, or the derivation walk could not run) or `unverified` (intent without committed line, not replayed), returns `purge_replay` in the receipt and adds a reconnect warning unless the state is `none` or `complete`; an unreadable mirror is `unavailable`. `coverage.restored` carries the outcome, which `readRestorePurgeReplay` reads back for the doctor. A Postgres restore runs `gbrain beliefs replay-purges --archived-at <iso> (--purge-mirror <abs path> | --from-url-env <VAR>) [--apply]` (`src/commands/beliefs-replay-purges.ts`; dry run by default: `replayPurges` runs the replay in a transaction that rolls back), whose database source `purgeLinesFromDatabase` rebuilds the intents from every pre-restore tombstone (not bounded by `purged_at`, the purge transaction's start) and skips those the archive already holds. Seam: `__setPurgeReplayFaultForTests`. Probes: `test/belief-ledger-restore.test.ts`; segment storage after a replay: `test/large-pages/purge-replay-segments.test.ts` (both engines).
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 6d2bf4edd8..ea5f4c47ce 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -31,7 +31,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.
- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a follower's stamp has only its token and owner (#6650) until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
-- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`.
+- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`. #7777/#7780: a guard failure of known cause gets `guardRefusalHint`.
- `src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts` — #6278: `persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0)`, the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in the `persistence_requests` CREATE TABLE of `src/schema.sql`, with no index) so a fresh install and an upgraded brain keep the same column order. Tests: `test/persistence-preparation-attempts-migration.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 7d7a94ecc0..35024129ac 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -36,7 +36,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/trust/claim.ts` + `claim-state.ts` + `claim-notice.ts`, `src/commands/trust-claim.ts`: #5575 legacy content. `gbrain trust claim-sources` (local CLI; typed source id on a TTY, `--yes` never counts, non-TTY refuses `confirmation_required` with a tell_user_to_run fix) records a claim in `sources.config` (`trust_tier: operator_curated`, `trust_claimed_at`, `trust_claim_lifted_at`) and lifts the source's legacy `unknown` rows (ids at or below `write_gate.scan_baseline`) through `trust/backfill.ts` scoped to the claimed sources (own cursor, `write_origin.channel` `trust_claim`), lowered by `frontmatterTrustCapsSql` (channel.ts, pinned to `frontmatterTrustCaps`) and every backfill signal, never above operator_curated; connector sources refuse. Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the behavior-change notice name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. `claim-sources --relower [--dry-run]` (`relowerClaimedRows`, backfill.ts) is the lower-only #6533 repair: `trust_claim` rows whose page rule now ranks below their stored tier (legacy `extracted_by: extract_atoms-*` atoms) drop to it, pages first with child rows following through the relower-mode page taint, receipt `write_origin.channel` `trust_relower`; the dry run reports the same rows; doctor `trust_sources_unclaimed` names it. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`, `test/trust-claim-relower.test.ts`.
- `src/core/trust/marker-repair.ts`: #6550 `gbrain trust backfill --repair-unknown-markers` (local CLI, `src/cli/commands/trust.ts`). `previewMarkerRepair` lists live pages whose frontmatter `trust_tier` is `unknown` while the row is higher, with evidence (first `page_versions` snapshot showing the marker vs the fixed release `UNKNOWN_MARKER_FIX_RELEASE`: its commit time bounds the first run, `upgrade-state.json` can name it; whether the oldest kept version had the marker), an `assessment` (`consistent_with_6550` only when a pre-fix snapshot shows it and the first import did not, else `ambiguous`), pages already lowered through the marker (with their revert command), a `preview_hash` and the apply argv naming only the consistent pages. `applyMarkerRepair` refuses `preview_changed` unless the fresh preview hashes to `--expect`, then calls `page-handlers.ts` `repairPageMarker` per named slug: the `trust_owner_page` mode `repair_marker` (refused for remote requests) rewrites the marker to `repairedMarker(stored tier)` (none at owner tiers) at the previewed revision and keeps the tier. `review.ts` adds a `repair` command to `lower_page` items an `unknown` marker caused. Pinned by `test/trust-channel-writes.test.ts` (#6550 repair) and `test/trust-cli.test.ts`.
- `src/core/trust/label-lowerings.ts`: GST-2468 `gbrain trust backfill --label-lowerings` (local CLI, `src/cli/commands/trust.ts`), read-only. `listLabelLowerings` reads every `lower_page` proposal with the `page_versions` row its `before_state.version_id` names and the live page, and classes it `label_only` (only `LABEL_KEYS` and the stamp keys differ, a label among them), `content` or `unreadable`, counted by proposer; `changed_since` when the page moved past the proposal's recorded revision. Writes nothing.
-- `src/core/trust/provenance-drift.ts`, `src/core/repair/provenance.ts`, `src/commands/doctor/checks/provenance-stamp-drift.ts`: #7891 / #7918. `analyzePageDrift` (pure) walks a page's `page_versions` plus its live row; each transition's writer is the older snapshot's `archived_write_request_id` (joined to `persistence_requests.id` for `authority.remote`, else the principal kind; none: `unattributed`). Verdicts: `remote`, `ambiguous`, `local`, `needs_review` (a later local write changed the same stamp) and `restamp` (a classified page whose live caps rank above its stored tier). A restore puts each stamp back to the server-written column or the value before the first non-local change, and stamps min(lost cap, live caps, stored tier) with `stampTrustMarker`, so it only lowers. `scanProvenanceDrift` is bounded (`DRIFT_SCAN_LIMIT` per source) and degrades to `pre_trust` / `pre_attribution`. The doctor check is read-only; the repair kind is explicit-only and preview-bound (`provenance-v1` hash, approved set) and writes through `trust_owner_page` mode `restore_provenance` (`restorePageProvenance` in `page-handlers.ts`, local CLI only, re-checked against `plannedDigest`, files `lower_page` with proposer `provenance_repair`) or `repair_marker` for `restamp`. A page sync holds is listed `held` by the preview and skipped `held` by the apply, both through `pageHolds` (#8009), so the apply writes what the preview counted. Both repair modes render the page to its file on a classic checkout (`writePageThrough` with the preimage bytes). #7917: `recordAgentPageLowering` also files for derived publications and for callers that name a proposer; `prepareMaintenanceMutation` and `derivedMaintenanceTransaction` (rows carrying `prior`) call it. #7918: `derivationWriteTrust` rates a present but unreadable declaration `unknown`.
+- `src/core/trust/provenance-drift.ts`, `src/core/repair/provenance.ts`, `src/commands/doctor/checks/provenance-stamp-drift.ts`: #7891 / #7918. `analyzePageDrift` (pure) walks a page's `page_versions` plus its live row; each transition's writer is the older snapshot's `archived_write_request_id` (joined to `persistence_requests.id` for `authority.remote`, else the principal kind; none: `unattributed`). Verdicts: `remote`, `ambiguous`, `local`, `needs_review` (a later local write changed the same stamp) and `restamp` (a classified page whose live caps rank above its stored tier). A restore puts each stamp back to the server-written column or the value before the first non-local change, and stamps min(lost cap, live caps, stored tier) with `stampTrustMarker`, so it only lowers. `scanProvenanceDrift` is bounded (`DRIFT_SCAN_LIMIT` per source) and degrades to `pre_trust` / `pre_attribution`. The doctor check is read-only; the repair kind is explicit-only and preview-bound (`provenance-v1` hash, approved set) and writes through `trust_owner_page` mode `restore_provenance` (`restorePageProvenance` in `page-handlers.ts`, local CLI only, re-checked against `plannedDigest`, files `lower_page` with proposer `provenance_repair`) or `repair_marker` for `restamp`. A page sync holds is listed `held` by the preview and skipped `held` by the apply, both through `pageHolds` (#8009), so the apply writes what the preview counted. Both repair modes render the page to its file on a classic checkout (`writePageThrough` with the preimage bytes); #7960: when the database transaction then fails, `restoreOwnerRepairFile` puts the prior bytes back while the file still holds what the repair wrote, and commits that restore (`restore write-through`) when the write was committed. #7917: `recordAgentPageLowering` also files for derived publications and for callers that name a proposer; `prepareMaintenanceMutation` and `derivedMaintenanceTransaction` (rows carrying `prior`) call it. #7918: `derivationWriteTrust` rates a present but unreadable declaration `unknown`.
- `src/core/write-gate.ts` + `src/core/write-gate-patterns.ts` — the #5575 blocking write gate, separate from observe-only `guardrails.ts` (never imported). Deterministic and model-free (P8): `WRITE_GATE_PATTERNS` (bounded clones of the detection-grade `think/sanitize.ts` `INJECTION_DETECTION_PATTERNS`, the exported transcript `IMPERATIVE_RES`, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed to <address>" rules and direct cc/bcc) and credential patterns; families `override`, `standing_instruction`, `exfiltration`, `credential`). `detectInstructionLike` decodes tag characters, strips invisibles and NFKC-folds compatibility forms only when present, finds anchor words in one allocation-light hash pass (one tight loop per word), then runs each pattern only on 4 KB windows (overlap `MAX_MATCH_CHARS` + `MAX_PRECEDING_CHARS`) holding its anchors, tracked as sliding per-window anchor counts, and inside a window only within the pattern's longest match (`write-gate-regex.ts`, the analysis the regex lint uses) of its own anchor words, except `WHOLE_WINDOW_PATTERNS`; `preceded` regexes check context before a rare-token match, a `neg` group rejects negated matches. `assessPageForGate` (title, body minus managed fence table rows, frontmatter strings), `assessFactForGate` (fact, context, value, provenance, pre-sanitized `source_text`), `assessTakeForGate` and `assessTimelineForGate` scan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed; `external_untrusted` -> `write_gate.external_mode` (`flag` default per the paid eval, `quarantine` opt-in, `reject`, `off`), detector error -> quarantine; `agent_written`/`unknown` -> `flag` (`write_gate.agent_mode=off`), detector error -> allow. `writeGateOutcome` is the DX-1 `gate` shape; `writeHeldError` / `writeGateRejectedError` build the `write_held` / `write_gate_rejected` refusals (families only, no pattern names). `scripts/check-write-gate-regex.ts` (in verify) proves every pattern bounded. `assessPageForGate` / `assessWriteGate` take an optional `WriteGateWork` accumulator (`createWriteGateWork`) the detector fills per assessment with the work it did (normalization and anchor-pass input units, windows, pattern checks past the prefilter, regex executions, searched characters); nothing is kept between calls (#6490). Tests: `test/write-gate.test.ts`, `test/write-gate-perf.slow.test.ts` (quiet-round absolute p95 with the receipt insert, 5 MB linear bounds), `test/write-gate-work-counters-6490.test.ts` (the counters pinned per corpus; four mutants fail it: disabled prefilter, REACH x8, a per-window normalization pass, a pattern anchored on `the`), `test/write-gate-anchor-ranges.test.ts` (sampled matches of every narrowed pattern hold an anchor word within its longest match), and `test/write-gate-detector-differential.test.ts` (identical hits to the pre-optimization detector v2 kept as `test/helpers/write-gate-detector-reference.ts`, over the detector corpora, BrainBench fixtures, docs/skills and a seeded random corpus).
- `src/core/write-gate-store.ts` + `src/core/write-gate-schema.ts` — `write_gate_receipts` (flag/quarantine verdicts per persisted target, unique on target, content hash and detector version; pattern names only) and `write_gate_holds` (quarantined facts/takes kept out of `facts`/`takes`, unique on source, slug, fingerprint and detector version; re-arrival re-opens a decided hold). Writers record inside their publication transaction: `recordPageGateReceipt` resolves the live page row, `recordWriteGateReceipt`, `recordWriteGateHold`; `decideFactWrite` / `decideTakeWrite` return insert/hold/reject per row and `recordFlaggedRow` receipts an inserted flagged row. Owner review: `listWriteGateHolds`, `getWriteGateHold`, `releaseWriteGateHold` (returns the payload for the confirm path; authorization is the caller's), `dropWriteGateHold`; `pruneWriteGateReceipts` drops receipts unseen for 365 days except a pending hold's. Tests: `test/write-gate-store.test.ts` (+ Postgres arm `test/e2e/write-gate-store-postgres.test.ts`).
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.md
index 88cb2979d7..88caf117d0 100644
--- a/docs/architecture/key-files/shared-skills.md
+++ b/docs/architecture/key-files/shared-skills.md
@@ -2,7 +2,7 @@
- `src/core/shared-skills/{model,manifest,policy,catalog,compatibility,tool-access}.ts` defines source-incarnation-qualified skill keys, bounded declared files, versioned disclosure policy, sealed catalog reads, authorized opaque views and legacy response projections. Tool/resource requirements use the same scope, snapshot, surface and publication constraints as dispatch. Existing positive publication consent remains prose-only; metadata for unapproved files is not returned. `skillMetadata` refuses an empty or whitespace-only SKILL.md (A-NEW-5) and records `tools_declared` (#5150): a canonical skill published without `tools` inherits the caller's `sharedSkillToolAccess` as `usable_tools` in v2 list/detail and the v1 compatibility projection (which now reuses the catalog's computed lists), `tools: []` permits none, and revisions published before the flag re-read their SKILL.md on detail (`skillToolsDeclared`) while the list fails closed. `SHARED_SKILL_LIMITS.packFiles` (128, equal to the persistence `BUNDLE_FILE_LIMITS.files`) bounds one canonical publication; `files` (64) bounds one skill (#5476).
- `src/core/shared-skills/publication.ts` prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. `knowledge-guard.ts` keeps page/sync/restore aliases from changing declared skill paths; inside a screening batch (`persistence/screening-paths.ts`) it canonicalizes each pack root and resolves each source root's Git scope once. A relative or host-only `file://` alias names no local file and is ignored; an absolute file URI that cannot be resolved refuses with `invalid_source_uri` (not `skill_bundle_required`).
-- `src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts` supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects; the request and effect guards refuse `writer_coordinator_required` when the writing role cannot see the `persistence_brain` floor, and activation refuses any role that row-level security filters on `sources` or the request, effect, worktree and binding tables. Their function bodies are exported alone so a migration replaces them without re-creating triggers. `src/core/persistence/{protocol,skill-activation,bundle-files}.ts` implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.
+- `src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts` supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects, each with SQLSTATE 42501 and a fixed `<code>: <diagnostic>` message; the request and effect guards refuse `writer_coordinator_required: writer state is unreadable to this database role` when the writing role cannot see the `persistence_brain` floor, and activation refuses with the same message any role that row-level security filters on `sources` or the request, effect, worktree and binding tables (only the table owner or a BYPASSRLS role activates). During publication `persistence/publication-failure.ts` types them by innermost guard frame plus exact diagnostic (#7777: `writer_upgrade_required`, `writer_not_quiesced`, `unsupported_mutation_protocol`, or `writer_coordinator_required` with relationship `unreadable_state`) and `connector-errors.ts` `guardRefusalHint` names the remedy (also the role remedy `UNREADABLE_STATE_HINT` for any guard's `unreadable_state`, whose raise's `state` table `guardDetail` keeps owner-only, #7780) (receipts via `receiptDeliveredHint`, docs anchor `protocol-guard`, and writer status `recent_failures[].next_action`; `test/protocol-guard-refusal-7777.test.ts`, both engines, checks every 42501 raise in `persistence-schema.ts` is typed); elsewhere the caller gets the raw 42501, which generic database output labels `permission_denied`. Their function bodies are exported alone so a migration replaces them without re-creating triggers. `src/core/persistence/{protocol,skill-activation,bundle-files}.ts` implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.
- `src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts` implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed. The adapter's leave treats a server `membership_inactive` (its own enrollment epoch was left or re-enrolled past) as remote cleanup complete (`remote_membership_reason: superseded`), so harness rotation converges; `gbrain bootstrap harness --refresh-skills` re-runs `join` to adopt the current epoch.
- `src/core/harness/{shared-skills,native-router}.ts` connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.
- `src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts` owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. `installPackagedSharedSkills` resumes (or keeps, once committed) the caller's newest packaged adoption of the source incarnation's `gbrain-memory` pack before admitting one, since the adoption key binds the release-stamped `skillpack.json` and README (#8453). Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. `src/commands/migrations/shared-content.ts` integrates previews and recurring pending-stage reconciliation into the migration runner. The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), moves a DB-only export checkpoint that stopped before its source was bound (stage `inventory` or `exported`, no started claim) to another absent `--content-root` and rechecks the checkpoint's inventory (#8528): a root inside a Git worktree is refused before any page is staged, the old staging directory is removed under the lock only when it holds nothing but the export's own bytes (else the move is refused, naming it), a filled earlier root is kept and named in `earlier_roots` and `pending_actions`, and every run refuses if the checkpoint changed while it waited for its lock, refuses at inventory a pack whose adoption would exceed `packFiles` (A-NEW-4), and accepts a post-inventory change only through `--accept-reviewed-inventory <source>=<inventoryDigest>` printed in the conflict reason (#5476).
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index 294644c8d7..c6b49ceca5 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -12,7 +12,7 @@ Key files:
## Shared-checkout git writer
-- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `commitPaths` returns the named paths HEAD still lacks (`unstagedPaths`: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path, passes each path as `:(literal)<path>` (a glob-named path never commits another file, #7792) and releases the commit lock before pushing under `brain-publish.lock`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). `--untrack` (#7753, GST-2519): `untrackPaths` removes the files HEAD holds under the named paths (`untrackTargets`; skip-worktree files refuse) with `git rm --cached` and commits from HEAD in a temporary index, taking back a commit that changed anything else; in a managed canonical worktree `untrackAdmitted` first requires each file to sit under a `storage.db_only` dir that `gbrain.yml` at HEAD declares and that `.gitignore` ignores (`untrack_not_db_only`, index untouched), and the commit stays local like every managed commit; `previewUntrack` is the dry run. The dry run of a commit is `previewPaths` (#7752): `admitPaths` (shared with `commitPaths`: source roots, `--base`, pre-staged files), the real staging (`stagePaths`) as `git add -n` against a copy of the index, and a staged rename's partner, so each refusal carries the real run's code and text, with no lock and no write. A not_staged path that is a hand-staged `git rm --cached` names `--untrack` in the `commit_paths_skipped` fix. Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, `test/git-commit-push-skipped-paths-gst2116.test.ts`, `test/git-commit-push-untrack-gst2519.test.ts`, `test/git-commit-push-door-wave2.test.ts`.
+- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `commitPaths` returns the named paths HEAD still lacks (`unstagedPaths`: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes (exported for a caller holding the commit lock: the derived write-through's rollback). `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path, passes each path as `:(literal)<path>` (a glob-named path never commits another file, #7792) and releases the commit lock before pushing under `brain-publish.lock`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). `--untrack` (#7753, GST-2519): `untrackPaths` removes the files HEAD holds under the named paths (`untrackTargets`; skip-worktree files refuse) with `git rm --cached` and commits from HEAD in a temporary index, taking back a commit that changed anything else; in a managed canonical worktree `untrackAdmitted` first requires each file to sit under a `storage.db_only` dir that `gbrain.yml` at HEAD declares and that `.gitignore` ignores (`untrack_not_db_only`, index untouched), and the commit stays local like every managed commit; `previewUntrack` is the dry run. The dry run of a commit is `previewPaths` (#7752): `admitPaths` (shared with `commitPaths`: source roots, `--base`, pre-staged files), the real staging (`stagePaths`) as `git add -n` against a copy of the index, and a staged rename's partner, so each refusal carries the real run's code and text, with no lock and no write. A not_staged path that is a hand-staged `git rm --cached` names `--untrack` in the `commit_paths_skipped` fix. Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, `test/git-commit-push-skipped-paths-gst2116.test.ts`, `test/git-commit-push-untrack-gst2519.test.ts`, `test/git-commit-push-door-wave2.test.ts`.
- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to, timeoutMs, progress)`, the secret gate for every push gbrain makes: `gbrain git commit-push` in every mode, `--untrack` included where it pushes (the CLI always sets `scanSecrets`; the post-commit hook, `scripts/brain-commit-push.sh` and the child `gbrain sources refresh` runs all go through it) scans `trackingRef..target` under the publish lock, right before a push that never follows tags or recurses into submodules (`--no-follow-tags --recurse-submodules=no`, on the `sources push` and `bootstrap repo` pushes too). Plumbing only (`rev-list`, then `cat-file --batch` and `diff-tree --stdin -p --root --cc` over batches of 256 commits, so the temporary patch file stays one batch in size), so log, diff and attribute settings never change what is scanned. The budget is 300 s unless `--scan-timeout` sets it; `progress` gets `secret scan:` lines (at once for a whole history, then every 10 s), and with `retryArgv` a timed-out scan refuses `publish_scan_unreadable` whose agent fix is that command with `--scan-timeout` four times longer (at least 1200 s). Commit messages, added lines and merge resolutions go through `scanText` with the `.gbrain-scan-allow` allowlist; a finding, added text over the scan cap or a change to `.gbrain-scan-allow`/`.gitattributes` refuses `publish_secret_found` (file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refuses `publish_scan_unreadable`. Commits the commit ledger records as page writes are not scanned: door and hosted-repository commits, and Git effect commits recorded `verified` (`effectCommit` in `effect-git.ts` builds the commit with `commit-tree` and moves HEAD with an `update-ref` compare-and-swap, so the recorded sha is gbrain's own; `verified` when each staged blob is the bytes whose sha256 the effect recorded); adopted records, records without `verified` and an unreadable ledger leave the commits scanned. Doctor `git_convergence`'s agent push fixes pass `--scan-secrets` too. `stagedScanPublishRefusal(root, base, target, opts)` is the same refusal for `gbrain sources push` (`workspace-push.ts`: origin's tip read from origin itself with `ls-remote` and a fetch, since the pull may follow another upstream remote, then `<tip>..HEAD` scanned and that exact sha pushed leased on the tip, no push when the local branch lacks the tip; a refusal is the `blocked_history` result, exit 5, printed by `--json` too) and both first pushes of `gbrain bootstrap repo` (`bootstrap/repo.ts`, the whole history; `scanHistory` is the runner-fake seam), with gate changes exempt in commits the ledger records as `workspace_push` or `bootstrap`, whose blobs those writers scanned staged with the same allowlist. The access-policy commit (`access/policy-git.ts`, which reports a scan refusal as `committed_not_pushed` with the refusal in its note) and the durability-scaffolding commit (`brain-repo-durability.ts`) publish through `commitAndPush` with `scanSecrets` (#8902). The helper's no-gbrain fallback commits and never pushes. `gbrain git scan` (`runScan` in `src/commands/git.ts`) runs `scanRange` and `rangeSecretRefusal` over `--from..--to` (default `@{upstream}..HEAD`) and writes nothing: the read-only preview of what a push would refuse, with each finding's fingerprint. Tests: `test/unmanaged-push-history-scan-8902.serial.test.ts`, `test/unmanaged-push-every-site-gst2456.serial.test.ts`.
- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.
- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files; only a missing file reads as empty, any other read error throws (GST-1623). Tests: `test/commit-ledger.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 84f44af5f2..df400a25cb 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1580,7 +1580,10 @@ again for the rest. Sync never removes ghost pages by itself.
A code or image page (a synced `.json`, `.ts` or `.png` file) is checked at
the file it records, never at `<slug>.md`: while that file is there the page
is not a ghost. It is a ghost only when its recorded file is gone and no file
-sits at its slug path either, and the preview lists it at the recorded path. A
+sits at its slug path either, and the preview lists it at the recorded path.
+The apply retires it at that recorded file too: a recorded file restored
+before publication keeps the page (`file_restored`), and the commit records the
+removal of the recorded file. A
page whose recorded path names no file inside the source (an absolute path, a
path with `..`) is never a ghost and is never removed: doctor, `gbrain pages
ghosts` and the preview list it apart with code `recorded_path_unresolvable`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 32a3c75147..986e666ced 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -58,7 +58,8 @@ of making a duplicate.
| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: wait for the source's running sync owner (`gbrain serve`, autopilot or a sync job) to import the commit, which the refusal's read-only fix `gbrain sync status --source <source> --json` shows, then read the page again and resubmit with a new request ID. Neither refusal tells the caller to start a sync, because a second sync beside a running owner competes with it; when status shows no owner running, ask the user to sync the source on its host. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. With `persistence.refresh_barrier` on, a `put_page`, `capture`, `remember` or `add_timeline_entry` waits for the import instead of being refused ([deferred writes](#pending_import_expired)). |
| <a id="sync_write_through_off"></a>`sync_write_through_off` | `unavailable` (`forget` / `forget_fact`, detail `sync_write_through_off`) | `sync.write_through` is off and a canonical file carries the claim. The struck row would not reach the file, so a brain rebuilt from Git would bring the claim back; nothing was withdrawn. A claim that only database-only pages carry is still withdrawn. A sandboxed subagent's forget of such a claim refuses the same way with `scope_denied`, detail `subagent_sandbox`. | `gbrain config set sync.write_through true`, then forget the fact again; from a subagent sandbox, forget it from the main session. |
| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals is retried once by the first purge run after the upgrade). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |
-| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636): the database role gbrain connects as cannot see the writer state the guard reads (the `persistence_brain` or `git_canonical_brain` row, or the source or page row the write names) because row-level security hides it, or a `persistence_brain` / `git_canonical_brain` row is missing, so the guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. A derived-state maintainer trigger raises the same refusal (#7637, raiser `gbrain_forget_page_retrievals`, `gbrain_queue_page_projection` and the others [listed in ENGINES.md](../ENGINES.md#derived-state-maintainers)) when row-level security applies to the role on a table it keeps up to date and the role holds no policy for it there, instead of leaving that derived state stale. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause: run gbrain as a role that can see that state (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though a change to which sources are Git-canonical passes only the first two; see [writer-protocol fences](../ENGINES.md#opt-in-rls-source-scope-binding-gbrain_rls_scope_binding), and for a maintainer's table the [policies a scoped writer needs](../ENGINES.md#derived-state-maintainers)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. |
+| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636), message "writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)": the database role gbrain connects as cannot fully read the writer state the guard reads, because row-level security hides the `persistence_brain` or `git_canonical_brain` row or the source or page row the write names, or row-level security applies to `sources` at all (the Git-canonical recount refuses then, even under a policy that shows every row), or a `persistence_brain` / `git_canonical_brain` row is missing. The guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. A derived-state maintainer trigger raises the same refusal (#7637, raiser `gbrain_forget_page_retrievals`, `gbrain_queue_page_projection` and the others [listed in ENGINES.md](../ENGINES.md#derived-state-maintainers)) when row-level security applies to the role on a table it keeps up to date and the role holds no policy for it there, instead of leaving that derived state stale. The owner-only `error_detail.state` in `gbrain sources writer status --probe --json` names the table (`persistence_brain`, `git_canonical_brain`, `sources` or `pages`; #7780); the public receipt does not carry it. A `write_error_detail.sqlstate` of `42501` is a persistence protocol guard, not the managed-writer guard: see [protocol guard](#protocol-guard). The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause, and the receipt's suggestion says so: run gbrain as a role that can read the table `error_detail.state` names (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though protocol activation and a change to which sources are Git-canonical pass only the first two; see [writer-protocol fences](../ENGINES.md#opt-in-rls-source-scope-binding-gbrain_rls_scope_binding), and for a maintainer's table the [policies a scoped writer needs](../ENGINES.md#derived-state-maintainers)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. |
+| <a id="protocol-guard"></a>`database_guard` with `write_error_detail.sqlstate` `42501` | `writer_upgrade_required`, `writer_not_quiesced`, `unsupported_mutation_protocol` or `writer_coordinator_required` | A persistence protocol guard (`write_error_detail.raiser`: `gbrain_require_persistence_protocol`, `gbrain_guard_request_protocol`, `gbrain_guard_effect_protocol`, `gbrain_guard_protocol_activation` or `gbrain_guard_skill_publication`) refused a row while a write was published, so nothing was committed (#7777). The error code is the guard's own: `writer_upgrade_required` (the gbrain process that ran the write does not declare the protocol the brain's floor requires: an older gbrain), `writer_not_quiesced` (shared skill publication is not active, or the canonical owner's protocol-2 capability changed after activation), `unsupported_mutation_protocol` (a request's target or protocol does not fit its operation), or `writer_coordinator_required`, either with relationship `unreadable_state` (the role gbrain connects as cannot read the `persistence_brain` writer state: row-level security hides it, or the row is missing; owner-only `error_detail.state` is `persistence_brain`) or without it (a shared-skill row outside the coordinated source capability). Only a guard's exact diagnostic, raised by that guard's own function, is typed; any other 42501 stays an ordinary permission error. Outside publication (write admission, protocol activation) the same refusal reaches the command as the database error itself, `Error [database_error]: <code>: <diagnostic>`, followed by the generic `permission_denied` grant advice; the code at the start of the message is the refusal. | Follow the receipt's suggestion. `unreadable_state`: upgrading does not help; run gbrain as a role that can read `persistence_brain` (the table owner, a role that bypasses RLS, or a scoped role with a `SELECT` policy on it), then retry with a **new** request ID. Protocol activation, like a change to which sources are Git-canonical, passes only the table owner (without `FORCE ROW LEVEL SECURITY`) or a role that bypasses RLS. `writer_upgrade_required`: compare `recent_failures[].error_detail.attempt.consumer_version` from `gbrain sources writer status --probe --json` with `gbrain --version`, upgrade or restart every older gbrain process sharing the database, then retry with a new request ID; never lower the protocol floor. `writer_not_quiesced`: see [writer_not_quiesced](#writer_not_quiesced). `unsupported_mutation_protocol` and the skill-capability case: upgrade or restart older processes and submit again with a new request ID, and report `error_detail` on the gbrain issue tracker if the builds match. Never edit SQL or disable the guard. |
| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. |
| <a id="owner_marker_missing"></a>`owner_marker_missing` | `owner_marker_missing` | The ownership marker `.gbrain-owner.json` is gone from the checkout root while the reservation beside the checkout still names this owner and identifies this exact directory: device, inode and birth time all equal (a cleanup or a restore that dropped dotfiles). A directory the reservation does not identify exactly, a birth time within the 1 µs tolerance included, keeps the generic `recovery_required` and its [recreated-root](#recreated-root) exit. No write publishes there, and a retry never brings the marker back, so the owner finishes each refused write `failed` (its outstanding-request slot is released); a sync stops `blocked_by_failures` on the refused file, without a hold. | Re-create the marker with the verified self-transfer on the brain host: `gbrain sources writer status --source <source> --json` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Then run the same `gbrain sync` again. Never create or copy the marker by hand. |
| `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |
@@ -169,7 +170,7 @@ a receipt can report has a row here.
| `proposal_expired` | `proposal_expired` | The owner's `gbrain memory-proposals approve` or `deny` came after the proposal's `expires_at` (`proposals.ttl_hours`, default 168). The proposal closes `expired` and nothing was written. | QM reads `expired` on `get_write_request` and sends a new [proposal](qm.md#proposed-writes) with a new `idempotency_key` if the change is still wanted. The brain operator raises `proposals.ttl_hours` to give owners longer. |
| `proposal_closed` | `proposal_closed` | `gbrain memory-proposals approve` or `deny` named a proposal that is no longer awaiting the owner (approved, denied, expired, cancelled, failed or in conflict). It is decided once, and its decision and receipt stay as they are. Nothing was written. | `gbrain memory-proposals show <request_id>` says how it ended; the proposer sends a new proposal if the change is still wanted. |
| `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |
-| `writer_upgrade_required` | `writer_upgrade_required` | The brain's schema is older than this operation needs. | Run `gbrain upgrade` (or `gbrain apply-migrations --yes`) on the brain host. |
+| `writer_upgrade_required` | `writer_upgrade_required` | The brain's schema is older than this operation needs. A receipt whose `write_error_detail.sqlstate` is `42501` is the persistence protocol floor instead: see [protocol guard](#protocol-guard). | Run `gbrain upgrade` (or `gbrain apply-migrations --yes`) on the brain host. |
| `skill_bundle_required` | `skill_bundle_required` | The write targets a shared-skill path, which only the shared skill publisher may write. | Publish the skill through the shared skill publisher instead. |
| `core_budget_exceeded` | `invalid_params` (detail `core_budget_exceeded`) | The write would make always-loaded core memory larger than `memory.core.max_chars`, or add a 51st core page. The message names the projected size, how far over it is and the largest core pages the caller can see. Nothing was written; writes that shrink core always pass. | Move detail into a linked non-core page and keep a one-line pointer, or ask the user to raise the budget. `gbrain core status --json` shows where the characters go. See [core memory budget](core-memory.md#budget). |
| `core_mark_owner_only` | `invalid_params` (detail `core_mark_owner_only`) | A remote caller tried to add or remove `always_load` or change `core_priority`. Only the owner designates core pages. Nothing was written. | Resubmit without changing those keys (omitted keys keep their stored values). If the marking itself should change, ask the user to run the `gbrain core add` or `remove` command the message names. See [owner only](core-memory.md#owner-only). |
diff --git a/llms-full.txt b/llms-full.txt
index 17bc03954f..15e0d5011f 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5141,9 +5141,16 @@ does not own a function, v277 names it on stderr and leaves it; `gbrain doctor`
**Writer-protocol fences.** The managed-writer guard, the persistence protocol floor, protocol
activation and the Git-canonical source counter also run as the writing role and read their state
under its RLS. Since migration v278 (#7636) they fail closed: a role that cannot see the
-`persistence_brain` row is refused with `writer_coordinator_required` (relationship
-`unreadable_state`) on every guarded write, managed brain or not, instead of being treated as
-unmanaged. On a managed brain the same refusal covers a hidden `git_canonical_brain` row or
+`persistence_brain` row is refused on every guarded write, managed brain or not, instead of being
+treated as unmanaged. The message is `writer_coordinator_required: writer state is unreadable to
+this database role`: the managed-writer guard raises it as P0001, the request, effect and
+activation guards of the persistence protocol as SQLSTATE 42501. During a coordinated write's
+publication either one is stored on the receipt as `writer_coordinator_required` (relationship
+`unreadable_state`, the role remedy, and the owner-only `error_detail.state` naming the table; since
+#7777 for the protocol guards, #7780 for the state and remedy). A protocol guard's
+refusal outside publication (write admission, protocol activation) reaches the command as that
+database error, which gbrain's generic database output labels `permission_denied` with grant
+advice: the code at the start of the message names the refusal. On a managed brain the same refusal covers a hidden `git_canonical_brain` row or
Git-canonical source row (for a writer without the git protocol) and a hidden page row behind a tag,
timeline entry or take. Protocol activation (row-level security on `sources`, `persistence_requests`,
`persistence_effects`, `persistence_worktrees` or `persistence_source_bindings`) and a change to
@@ -5685,7 +5692,7 @@ names — reasons may be added, never renamed or removed). All 16:
| `no_url` | nothing configured at all — `gbrain init --prefer-postgres` (or `gbrain init` for PGLite) |
| `env_shadowed` | a cwd-.env `DATABASE_URL` exists but the cwd-.env guard excludes it — export `GBRAIN_DATABASE_URL` |
| `auth_failed` | password/role rejected (28P01) — reset credentials, then `gbrain init --url <conn>` |
-| `permission_denied` | 28000/42501 — the role lacks a GRANT or hits RLS |
+| `permission_denied` | 28000/42501 — the role lacks a GRANT or hits RLS; a 42501 whose message starts with a writer code (`writer_coordinator_required:`, `writer_upgrade_required:`, `writer_not_quiesced:`, `unsupported_mutation_protocol:`) is a persistence protocol guard's refusal ([write refusals](guides/write-refusals.md#protocol-guard)) |
| `tenant_not_found` | Supavisor rejected the tenant — pooler usernames are `postgres.<project-ref>`; also raised by paused projects |
| `ssl_required` | the server demands SSL — `?sslmode=require` rewrite (rewrite tier) |
| `pool_exhausted` | 53300 / session-slot exhaustion — [pool sizing](#pool-sizing) guidance: `export GBRAIN_POOL_SIZE=6` per long-running process, fewer processes |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4d347214de..ba88dee396 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1568,6 +1568,16 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-230 lane G (#7752). `since` is stamped at the merge slot.
{ since: 'TBD', id: 'commit_push_dry_run_checks_paths', text: '`gbrain git commit-push --dry-run` now asks git about the planned paths the way the real run stages them, and runs the real run\'s checks before staging, so it exits 1 with the real run\'s code and text where that run would refuse (`commit_outside_source_root` for a path outside `gbrain.sourceRoot` unless `--allow-outside-source-root` is passed, `commit_prestaged_paths`, and `commit_paths_invalid` for a path outside a sparse-checkout definition or one that matches nothing) instead of exiting 0 and listing it. It still takes no lock and writes nothing.' },
{ since: 'TBD', id: 'schema_client_behind_7776', text: 'A gbrain binary older than the brain\'s schema (the database\'s schema version is above its newest migration because a newer gbrain on another host or install migrated it) now refuses schema setup with `client_behind` and changes nothing: `gbrain init` and `init --migrate-only`, the schema step of `gbrain upgrade`, and `gbrain apply-migrations` (before any orchestrator runs, and before the schema pass of `--force-schema` or `--force-all`; `--list` and `--dry-run` still work). Before, it replayed its own older schema, which reinstalled superseded function bodies (the writer-fence guards among them) over the newer ones, and reported success. Reads and ordinary commands on the older binary are unchanged; the fix is `gbrain upgrade` on that host. A new doctor check, `schema_function_bodies`, fails when a function of this gbrain\'s schema has another body installed (what an older replay leaves behind) and names each one: upgrade every gbrain that shares the database, then run `gbrain init --migrate-only`. PGLite and Postgres alike, with or without a git repo.' },
+ // GBRA-261 lane C (#7831, #8034, #8020). `since` is stamped at the merge slot.
+ { since: '0.60.529.0', id: 'purge_keeps_outcome_markers_7831', text: 'Purging a fact whose text is exactly `EXTRACTION_COMPLETE` or `EXTRACTION_NOT_APPLICABLE` (`gbrain forget <id> --purge`) no longer removes the conversation-facts outcome rows that carry the same text: the purge, its receipt, `--status` and a restore replay leave them in place, so those pages are not extracted again. The purged claim itself is still removed and tombstoned.' },
+ { since: '0.60.529.0', id: 'audit_secrets_glued_marker_8034', text: '`gbrain transcripts audit-secrets` and re-scans of stored pages again report a password glued to an importer redaction marker by punctuation (`<REDACTED:user-pattern>,<password>`, `<REDACTED:x>.<password>`): punctuation after a marker ends it only when a space or the line end follows. Pages that hold such a line show up as affected again; import-time redaction is unchanged.' },
+ { since: '0.60.529.0', id: 'fence_locators_skip_code_8020', text: 'A fence marker written inside markdown code (an inline `code` span or a fenced code block) no longer counts as a fence for concept republication, the Google connector\'s fence carry, `gbrain repair connector-fences` or `gbrain repair take-supersession`, matching how the fence readers already read the page. Pages that quote a marker in code are no longer held `concept_preservation_hold` or `connector_fence_below_timeline`, or skipped as unparsed, for that reason alone.' },
+ // GBRA-261 lane D (#7967, #8092, #7960).
+ { since: '0.60.529.0', id: 'ghost_code_page_recorded_file_7967', text: '`gbrain repair ghost-pages` on a managed brain now retires a code or image page (a JSON, YAML or image file indexed as a page) at its recorded file instead of at `<slug>.md` (#7967): when that file is restored after the request was prepared, publication refuses and the page is kept (outcome `file_restored`), and the door commits the removal of the recorded file, so on a git-canonical source HEAD stops holding the file of a page the database deleted.' },
+ { since: '0.60.529.0', id: 'derived_write_through_retry_8092', text: 'The dream cycle\'s atom and concept write-through (#8092) waits for a busy checkout commit lock without freezing the worker (up to 30 s, as before). After a refused commit, a rewrite of an existing atom or concept file and the removal of a retired atom\'s file are now retried on the next run like new files, instead of staying behind the database until the page changes again; the summary reads "N file(s) rolled back; the next run writes them again". The rollback runs under the commit lock and takes its files out of the pending write-through ledger, so a later hand edit at one of those paths is never swept into a gbrain commit; when the lock stays busy the files are left for that writer\'s commit.' },
+ { since: '0.60.529.0', id: 'owner_repair_file_restore_7960', text: 'On an unmanaged repository brain, `gbrain repair provenance --apply` or `gbrain trust backfill --repair-unknown-markers` whose database write fails after the page file was written now puts the file\'s previous bytes back, and when the write had been committed on a hardened checkout, commits that restore (`gbrain: restore write-through <slug>`), so a failed apply leaves the file, Git and the database unchanged (#7960).' },
+ // GBRA-261 lane F (#7777, #7780).
+ { since: '0.60.529.0', id: 'protocol_guard_refusal_typed_7777', text: 'A write refused during publication by a persistence protocol guard (SQLSTATE 42501) now fails with the guard\'s own code on its receipt, `writer_upgrade_required`, `writer_not_quiesced`, `unsupported_mutation_protocol` or `writer_coordinator_required` (relationship `unreadable_state` when the database role cannot read the writer state), with `write_error_detail` naming the guard and a suggestion for that refusal, instead of `storage_error` for an unexpected owner exception. `gbrain sources writer status` gives the same step in `recent_failures[].next_action`. Any other permission error is unchanged, and so is the same refusal outside publication (write admission, protocol activation), which still reports `permission_denied`. Every `unreadable_state` refusal (#7780) now reads "writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)", its receipt suggests running gbrain as a role that can read that state instead of upgrading, and `gbrain sources writer status` shows the table in `recent_failures[].error_detail.state`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.ts
index b0c8233473..414a00f218 100644
--- a/src/core/belief/purge-mirror.ts
+++ b/src/core/belief/purge-mirror.ts
@@ -32,6 +32,7 @@ import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers } from './purge.ts';
import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from '../facts/derivation-inputs.ts';
import { writeOriginDeletedMarker } from '../persistence/sync-markers.ts';
+import { outcomeMarkerSql } from '../facts/audit-sources.ts';
export const PURGE_MIRROR_FILE = 'purge-events.jsonl';
@@ -157,7 +158,7 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: boo
} else {
const scope = intent.facts[0] ?? { fact_hash: '', visibility: 'world', subject: '*' };
const rows = await tx.executeRaw<{ id: number; fact: string; slug: string | null }>(`SELECT id, fact, source_markdown_slug AS slug FROM facts WHERE source_id = $1
- AND gbrain_fact_fingerprint(fact) = $2 AND visibility = $3 AND ($4 = '*' OR entity_slug = $4)`, [src, scope.fact_hash, scope.visibility, scope.subject]);
+ AND gbrain_fact_fingerprint(fact) = $2 AND visibility = $3 AND ($4 = '*' OR entity_slug = $4) AND NOT ${outcomeMarkerSql('facts')}`, [src, scope.fact_hash, scope.visibility, scope.subject]);
const takes = await tx.executeRaw<{ id: number; claim: string; page_id: number }>(`SELECT k.id, k.claim, k.page_id FROM takes k JOIN pages p ON p.id = k.page_id
WHERE p.source_id = $1 AND gbrain_fact_fingerprint(k.claim) = $2 AND ($3 = '*' OR p.slug = $3)`, [src, scope.fact_hash, scope.subject]);
claims = [...new Set([...rows.map(r => r.fact), ...takes.map(t => t.claim)])];
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index 6a1cf17e93..1573b34851 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -707,7 +707,7 @@ export function commitWriteThroughFile(
repoPath: string,
absPath: string,
slug: string,
- action: 'write-through' | 'delete write-through' = 'write-through',
+ action: 'write-through' | 'delete write-through' | 'restore write-through' = 'write-through',
): boolean {
try {
const rel = relative(repoPath, absPath);
diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.ts
index 5d9e2cc977..8965f0d15c 100644
--- a/src/core/cycle/concept-publication.ts
+++ b/src/core/cycle/concept-publication.ts
@@ -15,6 +15,7 @@ import { assertInlineBody, isSegmentedPage, pageBodySegmentedError } from '../pa
import { serializeMarkdown, parseMarkdown } from '../markdown.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence, stripFactsFence } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, stripTakesFence } from '../takes-fence.ts';
+import { countOutsideCode, locateOutsideCode } from '../fence-scan.ts';
import { isDbOnly, loadStorageConfig } from '../storage-config.ts';
import { publishMaintenancePages, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import { withCoordinatedWrite } from '../persistence/context.ts';
@@ -198,8 +199,8 @@ export function conceptPreservationHold(page: Pick<Page, 'compiled_truth' | 'tim
const body = page.compiled_truth ?? '';
const timeline = page.timeline ?? '';
for (const [name, begin, end] of [['FACTS', FACTS_FENCE_BEGIN, FACTS_FENCE_END], ['TAKES', TAKES_FENCE_BEGIN, TAKES_FENCE_END]] as const) {
- if (timeline.includes(begin) || timeline.includes(end)) return `CONCEPT_${name}_FENCE_BELOW_SENTINEL: a ${name.toLowerCase()} fence marker sits in the timeline`;
- const begins = body.split(begin).length - 1, ends = body.split(end).length - 1;
+ if (countOutsideCode(timeline, begin) || countOutsideCode(timeline, end)) return `CONCEPT_${name}_FENCE_BELOW_SENTINEL: a ${name.toLowerCase()} fence marker sits in the timeline`;
+ const begins = countOutsideCode(body, begin), ends = countOutsideCode(body, end);
if (begins > 1 || ends > 1) return `CONCEPT_${name}_FENCE_DUPLICATE: more than one ${name.toLowerCase()} fence`;
if (begins !== ends) return `CONCEPT_${name}_FENCE_UNBALANCED: ${name.toLowerCase()} fence begin/end markers do not pair`;
}
@@ -220,10 +221,8 @@ export function conceptPublicationHold(page: Pick<Page, 'compiled_truth' | 'time
}
function fenceBlock(body: string, begin: string, end: string): string | null {
- const start = body.indexOf(begin);
- if (start === -1) return null;
- const stop = body.indexOf(end, start + begin.length);
- return stop === -1 ? null : body.slice(start, stop + end.length);
+ const { beginIdx: start, endIdx: stop } = locateOutsideCode(body, begin, end);
+ return start === -1 || stop === -1 ? null : body.slice(start, stop + end.length);
}
/**
diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.ts
index 357b7bb2a5..b5b083a1cb 100644
--- a/src/core/cycle/derived-write-through.ts
+++ b/src/core/cycle/derived-write-through.ts
@@ -38,7 +38,7 @@ import { deletePageThrough, isWriteThroughDisabled, resolvePageWriteTarget, writ
import { urlCloneReadOnly } from '../url-clone.ts';
import { gitChildEnv, literalPathspecs } from '../git-env.ts';
import { classifyGitCheckout, type GitCheckoutClass } from '../git-checkout.ts';
-import { checkoutRoot, commitAndPush, commitPathsLocked, notePending, scopePaths } from '../git/commit-push.ts';
+import { acquireCommitLockAsync, checkoutRoot, commitAndPush, commitPathsLocked, COMMIT_LOCK_ENV, notePending, scopePaths, settlePending } from '../git/commit-push.ts';
import { managedFilesystemRootFor, refreshManagedFilesystemRoots } from '../persistence/filesystem-guard.ts';
import { withSourceFilesystemLock } from '../minions/source-filesystem.ts';
import { fileDatabaseDriftToken, replaceableFile } from '../facts/file-body-guard.ts';
@@ -102,8 +102,29 @@ function checkoutClassOf(root: string): GitCheckoutClass {
return (derivedWriteSeams.checkoutClass ?? classifyGitCheckout)(root);
}
-/** How long a batch waits for the checkout's commit lock before it rolls back. */
+/** How long a batch waits, without blocking the event loop, for the checkout's commit lock before it rolls back. */
const DERIVED_COMMIT_LOCK_WAIT_MS = 30_000;
+/** #8092: the synchronous take once the lock was seen free, and the rollback's wait for it (as the classic write-through's). */
+const DERIVED_COMMIT_LOCK_TAKE_MS = 2_000;
+
+/** #8092: op_checkpoints op naming a generated page whose file change a refused commit rolled back or left unwritten; the phase's next hook retries it. */
+const RETRY_OP = 'derived-write-retry';
+const retryKey = (sourceId: string, slug: string) => `${sourceId}:${slug}`;
+
+async function markRetry(engine: BrainEngine, pages: ReadonlyArray<{ sourceId: string; slug: string }>): Promise<void> {
+ for (const { sourceId, slug } of pages) {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ($1, $2, $3::text::jsonb)
+ ON CONFLICT (op, fingerprint) DO UPDATE SET updated_at = now()`, [RETRY_OP, retryKey(sourceId, slug), JSON.stringify([{ source_id: sourceId, slug }])]);
+ }
+}
+
+async function clearRetry(engine: BrainEngine, sourceId: string, slugs: readonly string[]): Promise<void> {
+ if (slugs.length) await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1 AND fingerprint = ANY($2::text[])', [RETRY_OP, slugs.map(slug => retryKey(sourceId, slug))]);
+}
+
+/** The changes of `changes` a failure lists (rolled back, or left for the pending ledger). */
+const failedChanges = (changes: readonly DerivedFileChange[], failures: readonly DerivedCommitFailure[]) =>
+ changes.filter(c => failures.some(f => f.root === c.writeRoot && f.paths.includes(relative(c.writeRoot, c.filePath))));
/** The file write of `writeDerivedPageThrough`, uncommitted, with the change it made. */
async function writeDerivedFile(engine: BrainEngine, slug: string, sourceId: string,
@@ -155,7 +176,12 @@ export async function writeDerivedPageThrough(engine: BrainEngine, slug: string,
const { change, ...result } = await writeDerivedFile(engine, slug, sourceId, opts);
if (!change) return result;
const [failure] = await commitDerivedChanges(engine, 'synthesize_concepts', [change]);
- return failure ? { written: false, error: `${failure.code}: ${failure.message}` } : result;
+ if (!failure) {
+ await clearRetry(engine, sourceId, [slug]);
+ return result;
+ }
+ await markRetry(engine, [change]);
+ return { written: false, error: `${failure.code}: ${failure.message}` };
}
/**
@@ -199,8 +225,9 @@ async function commitDerivedChanges(engine: BrainEngine, label: string, changes:
const paths = batch.filter((c, i) => !ignored.has(rels[i]!) && (existsSync(c.filePath) || tracked.has(rels[i]!))).map(c => c.filePath);
if (!paths.length) return;
const message = `gbrain: ${label} write-through (${paths.length} generated file(s))`;
- if (managed) commitAndPush({ repo: root, cwd: root, paths, message, lockWaitMs: DERIVED_COMMIT_LOCK_WAIT_MS });
- else commitPathsLocked(root, paths, message, { lockWaitMs: DERIVED_COMMIT_LOCK_WAIT_MS });
+ if (!process.env[COMMIT_LOCK_ENV]) await (await acquireCommitLockAsync(checkoutRoot(root), DERIVED_COMMIT_LOCK_WAIT_MS)).release();
+ if (managed) commitAndPush({ repo: root, cwd: root, paths, message, lockWaitMs: DERIVED_COMMIT_LOCK_TAKE_MS });
+ else commitPathsLocked(root, paths, message, { lockWaitMs: DERIVED_COMMIT_LOCK_TAKE_MS });
};
if (managed) await commit();
else await withSourceFilesystemLock(engine, root, commit);
@@ -228,13 +255,33 @@ function gitPaths(root: string, args: string[], input?: string): string[] {
* again. A file changed since (another writer's edit) is left as it is and listed in `kept`. A file whose change HEAD
* already holds (another writer's locked commit swept it in from the pending ledger) is committed, not rolled back:
* restoring it would leave an uncommitted revert of HEAD. Null when every file of the batch is committed.
+ * #8092: it runs under the checkout's commit lock (a short wait), so no writer commits between the HEAD check and the
+ * restore, and it settles the restored paths out of the pending ledger, so a later edit at one of them is never swept into
+ * a gbrain commit. When the lock stays busy nothing is restored: every file stays in the ledger for that writer's commit.
*/
async function rollBackDerived(engine: BrainEngine, root: string, batch: readonly DerivedFileChange[], error: unknown): Promise<DerivedCommitFailure | null> {
const code = typeof (error as { code?: unknown }).code === 'string' ? (error as { code: string }).code : 'git_unavailable';
const message = error instanceof Error ? error.message : String(error);
+ const top = checkoutRoot(root);
+ const lock = await acquireCommitLockAsync(top, DERIVED_COMMIT_LOCK_TAKE_MS).catch(() => null);
+ try {
+ const pending = batch.filter(change => !headHolds(root, change));
+ if (!pending.length) return null;
+ const paths = pending.map(c => relative(root, c.filePath));
+ if (!lock) {
+ console.error(`[write-through] commit refused (${code}): the commit lock stayed busy, so ${pending.length} generated file(s) are left for the next locked commit`);
+ return { code, message, root, paths, kept: paths };
+ }
+ const kept = await restoreDerived(engine, root, pending);
+ settlePending(top);
+ console.error(`[write-through] commit refused (${code}): ${pending.length - kept.length} generated file(s) rolled back, ${kept.length} left as they are`);
+ return { code, message, root, paths, kept };
+ } finally { await lock?.release(); }
+}
+
+/** Puts back the prior bytes of each change still holding the bytes it wrote and clears the source_path it bound; returns the root-relative paths left as they are. */
+async function restoreDerived(engine: BrainEngine, root: string, pending: readonly DerivedFileChange[]): Promise<string[]> {
const kept: string[] = [];
- const pending = batch.filter(change => !headHolds(root, change));
- if (!pending.length) return null;
for (const change of pending) {
try {
if ((existsSync(change.filePath) ? readFileSync(change.filePath, 'utf-8') : null) !== change.after) throw new Error('file_changed');
@@ -252,8 +299,7 @@ async function rollBackDerived(engine: BrainEngine, root: string, batch: readonl
kept.push(relative(root, change.filePath));
}
}
- console.error(`[write-through] commit refused (${code}): ${pending.length - kept.length} generated file(s) rolled back, ${kept.length} left as they are`);
- return { code, message, root, paths: pending.map(c => relative(root, c.filePath)), kept };
+ return kept;
}
/** Whether HEAD of `root`'s checkout already holds the change's resulting bytes (absent for a removal); false when HEAD is unreadable. */
@@ -279,15 +325,18 @@ export function reportFileHolds(result: PhaseResult, held: readonly string[] | u
export function reportDerivedWriteThrough(result: PhaseResult, files: DerivedWriteThrough | null, noun: string): PhaseResult {
const reported = reportFileHolds(result, files?.held, noun);
if (!files?.failed.length) return reported;
- const count = files.failed.reduce((n, f) => n + f.paths.length - f.kept.length, 0);
+ const kept = files.failed.reduce((n, f) => n + f.kept.length, 0);
+ const count = files.failed.reduce((n, f) => n + f.paths.length, 0) - kept;
return { ...reported, status: reported.status === 'fail' ? 'fail' : 'warn',
details: { ...reported.details, write_through_failed: files.failed },
- summary: `${reported.summary} (${noun} file commit refused: ${files.failed[0]!.code}; ${count} file(s) rolled back, written again on the next run)` };
+ summary: `${reported.summary} (${noun} file commit refused: ${files.failed[0]!.code}; ${count} file(s) rolled back${kept ? `, ${kept} left as they are` : ''}; the next run writes them again)` };
}
/**
* The phase's write-through hook: `write` publishes pages and removes retired ones' files, one commit per call; `held`
- * reports each page left alone, `failed` each refused commit (after which the hook writes nothing more this run).
+ * reports each page left alone, `failed` each refused commit (after which the hook writes nothing more this run). #8092:
+ * a page whose change was rolled back, or not written after a refusal, is marked for retry (`RETRY_OP`) and the next run's
+ * hook writes or removes its file again, an update of an existing file included.
*/
export interface DerivedWriteThrough {
write(slugs: readonly string[], retired?: readonly string[]): Promise<void>;
@@ -313,7 +362,7 @@ export async function derivedWriteThrough(
const failed: DerivedCommitFailure[] = [];
const kept = (skipped: string | undefined) => skipped === 'file_database_drift' || skipped === 'file_changed';
const write = async (slugs: readonly string[], retired: readonly string[] = []) => {
- if (failed.length) return;
+ if (failed.length) return markRetry(engine, [...slugs, ...retired].map(slug => ({ sourceId, slug })));
const changes: DerivedFileChange[] = [];
for (const slug of slugs) {
const result = await writeDerivedFile(engine, slug, sourceId, {});
@@ -325,17 +374,23 @@ export async function derivedWriteThrough(
if (result.change) changes.push(result.change);
if (kept(result.skipped)) held.push(fileDatabaseDriftToken(slug, sourceId, 'before', 'the retired page\'s file was not removed'));
}
- failed.push(...await commitDerivedChanges(engine, phase, changes));
+ const failures = await commitDerivedChanges(engine, phase, changes);
+ failed.push(...failures);
+ const unsettled = failedChanges(changes, failures);
+ await markRetry(engine, unsettled);
+ await clearRetry(engine, sourceId, [...slugs, ...retired].filter(slug => !unsettled.some(c => c.slug === slug)));
};
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL AND source_path IS NULL
+ const rows = await engine.executeRaw<{ slug: string; retired: boolean }>(
+ `SELECT slug, deleted_at IS NOT NULL AS retired FROM pages p
+ WHERE source_id = $1
+ AND ((deleted_at IS NULL AND source_path IS NULL)
+ OR EXISTS (SELECT 1 FROM op_checkpoints c WHERE c.op = $4 AND c.fingerprint = p.source_id || ':' || p.slug))
AND type = $2 AND ($2 <> 'concept' OR frontmatter->>'synthesized_by' LIKE 'synthesize_concepts%')
AND COALESCE(frontmatter->>'source_hash', '') NOT LIKE 'pending:%'
ORDER BY id LIMIT $3`,
- [sourceId, phase === 'extract_atoms' ? 'atom' : 'concept', DERIVED_BACKFILL_LIMIT],
+ [sourceId, phase === 'extract_atoms' ? 'atom' : 'concept', DERIVED_BACKFILL_LIMIT, RETRY_OP],
);
- await write(rows.map(r => r.slug));
+ await write(rows.filter(r => !r.retired).map(r => r.slug), rows.filter(r => r.retired).map(r => r.slug));
return { write, held, failed };
}
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 7e36876f64..dd148b5705 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -35,6 +35,7 @@ import { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';
import { CARRYING_FIELDS } from '../belief/keys.ts';
import { relationExists } from '../persistence/rebuildable-cache.ts';
import { canonicalChangeReason } from '../persistence/change-reason.ts';
+import { outcomeMarkerSql } from './audit-sources.ts';
export type StoreCount = Record<string, number>;
export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';
@@ -499,7 +500,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
else if (result.count) stores.push({ store, removed: removedCount ?? 0, remaining: result.count, ...onRemaining });
else stores.push({ store, status: removedCount ? 'deleted' : 'not_present', removed: removedCount ?? 0 });
};
- await swept('facts', `SELECT 1 FROM facts WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4)`,
+ await swept('facts', `SELECT 1 FROM facts WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) AND NOT ${outcomeMarkerSql('facts')}`,
[src, target.visibility, target.fact_hash, plan.subject], plan.factIds.length, removed.facts);
await swept('takes', `SELECT 1 FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND gbrain_fact_fingerprint(k.claim)=$2 AND ($3='*' OR p.slug=$3)`,
[src, target.fact_hash, plan.subject], plan.takes.length, removed.takes);
@@ -551,7 +552,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
stores.push(await probeInventoryStore(engine, entry, src, [claim], deadline));
}
const [other] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND gbrain_fact_fingerprint(fact)=$2
- AND NOT (visibility=$3 AND ($4='*' OR entity_slug=$4))`, [src, target.fact_hash, target.visibility, plan.subject]);
+ AND NOT (visibility=$3 AND ($4='*' OR entity_slug=$4)) AND NOT ${outcomeMarkerSql('facts')}`, [src, target.fact_hash, target.visibility, plan.subject]);
const files = await pageFilePaths(engine, src, plan.pages.map(page => page.page_id));
stores.push(...onDiskReports(files.files, claim, dryRun));
let vacuumed: string | null = null;
@@ -746,7 +747,7 @@ export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteReques
let fingerprint: Record<string, number> | undefined;
if (purge?.fact_hash) {
const [probe] = await engine.executeRaw<{ facts: number; takes: number }>(`SELECT
- (SELECT count(*)::int FROM facts WHERE source_id=$1 AND gbrain_fact_fingerprint(fact)=$2 AND ($3='*' OR entity_slug=$3)) AS facts,
+ (SELECT count(*)::int FROM facts WHERE source_id=$1 AND gbrain_fact_fingerprint(fact)=$2 AND ($3='*' OR entity_slug=$3) AND NOT ${outcomeMarkerSql('facts')}) AS facts,
(SELECT count(*)::int FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND gbrain_fact_fingerprint(k.claim)=$2 AND ($3='*' OR p.slug=$3)) AS takes`,
[row.source_id, purge.fact_hash, purge.subject ?? '*']);
fingerprint = { facts: Number(probe?.facts ?? 0), takes: Number(probe?.takes ?? 0) };
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 5c4601710f..11f8b27ef9 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -169,7 +169,7 @@ export async function stagingsHoldingClaim(engine: BrainEngine, sourceId: string
export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, allSubjects: boolean): Promise<PurgePlan> {
const subject = allSubjects ? '*' : target.entity_slug ?? '*';
const facts = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id=$1 AND visibility=$2
- AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) ORDER BY id`, [target.source_id, target.visibility, target.fact_hash, subject]);
+ AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) AND NOT ${outcomeMarkerSql('facts')} ORDER BY id`, [target.source_id, target.visibility, target.fact_hash, subject]);
const factIds = facts.map(f => Number(f.id));
const takes = (await engine.executeRaw<{ id: number; page_id: number }>(`SELECT DISTINCT k.id,k.page_id FROM takes k JOIN pages p ON p.id=k.page_id
WHERE p.source_id=$1 AND (k.id IN (SELECT consolidated_into FROM facts WHERE id=ANY($2::bigint[]) AND consolidated_into IS NOT NULL)
diff --git a/src/core/fence-scan.ts b/src/core/fence-scan.ts
index 8df92d3563..f2a401e49c 100644
--- a/src/core/fence-scan.ts
+++ b/src/core/fence-scan.ts
@@ -356,6 +356,15 @@ export function indexOfOutsideCode(
return at;
}
+/** How many times `needle` occurs in `body` outside markdown code: the count the fence readers see (indexOfOutsideCode). */
+export function countOutsideCode(body: string, needle: string, code?: MarkdownCodeMap): number {
+ let n = 0;
+ if (!body.includes(needle)) return n;
+ code ??= scanMarkdownCode(body);
+ for (let at = indexOfOutsideCode(body, needle, 0, code); at !== -1; at = indexOfOutsideCode(body, needle, at + needle.length, code)) n++;
+ return n;
+}
+
/**
* Offset where an unclosed fenced code block opens (it runs to EOF), or -1.
* Fence writers insert a new fence above it so the fence is not rendered as
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index bcb9941bd3..b9ec2ac973 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -917,7 +917,7 @@ function dirtyPaths(root: string, paths: string[]): Set<string> {
}
/** Drop ledger entries whose file no longer differs from HEAD (the caller holds the commit lock). New lines appended meanwhile go to a fresh ledger file. */
-function settlePending(root: string): void {
+export function settlePending(root: string): void {
try {
const file = absGitPath(root, PENDING_NAME);
const settle = `${file}.settle`;
diff --git a/src/core/persistence/connector-errors.ts b/src/core/persistence/connector-errors.ts
index 11f8ddfa72..34cdd94ead 100644
--- a/src/core/persistence/connector-errors.ts
+++ b/src/core/persistence/connector-errors.ts
@@ -93,6 +93,46 @@ export const DATABASE_REFUSAL_HINT = 'This is not a content conflict: a gbrain p
+ '(serve, autopilot, sync jobs), then retry with a new request ID. If the builds match, report error_detail (it contains no page text) on the gbrain issue tracker. '
+ 'Do not force-write, edit SQL, or disable the guard; ask the user before changing which hosts own the brain.';
+/**
+ * #7636/#7780: a guard refused because the database role cannot fully read the writer state it checks. The cause is the
+ * role's visibility, never the build, whichever guard raised it; the owner-only `error_detail.state` names the table.
+ */
+export const UNREADABLE_STATE_HINT = 'A database guard refused this write and nothing was committed: the database role gbrain connects as cannot fully read the writer state the guard checks '
+ + '(row-level security hides it or applies to the role, or a singleton row is missing), so the guard refused instead of reading the brain as unmanaged or the row as absent. '
+ + 'Upgrading gbrain does not fix this. On the brain host run gbrain sources writer status --probe --json; recent_failures[].error_detail.state names the table. '
+ + 'Run gbrain as a role that can read it (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows; protocol activation and a change to '
+ + 'which sources are Git-canonical pass only the first two), then retry with a new request ID. A missing persistence_brain or git_canonical_brain row, which gbrain init '
+ + 'never leaves, is a defect: report it on the gbrain issue tracker. Ask the user before changing the database role gbrain connects as. Do not edit SQL or disable the guard.';
+
+/**
+ * The remedy and docs anchor of a database guard refusal whose cause the stored detail establishes: unreadable writer state
+ * (#7636/#7780, any guard) or a persistence protocol guard's typed code (#7777, SQLSTATE 42501). Null for any other refusal.
+ */
+export function guardRefusalHint(code: string | null | undefined, detail: Record<string, unknown> | null | undefined): { suggestion: string; docs: string } | null {
+ if (detail?.origin !== 'database_guard') return null;
+ const protocol = detail.sqlstate === '42501';
+ if (detail.relationship === 'unreadable_state') {
+ return { suggestion: UNREADABLE_STATE_HINT, docs: docsAnchor(protocol ? 'protocol_guard' : 'writer_coordinator_required') };
+ }
+ if (!protocol) return null;
+ const inspect = 'On the brain host run gbrain sources writer status --probe --json';
+ const never = 'Do not edit SQL or disable the guard.';
+ const suggestion = code === 'writer_upgrade_required'
+ ? 'The persistence protocol guard refused this write and nothing was committed: the gbrain process that ran it does not declare the persistence protocol this brain requires '
+ + `(an older gbrain sharing the database). ${inspect} and compare recent_failures[].error_detail.attempt.consumer_version with gbrain --version; `
+ + 'upgrade or restart every older gbrain process (serve, autopilot, sync jobs), then retry with a new request ID. Never lower the protocol floor, edit SQL or disable the guard.'
+ : code === 'writer_not_quiesced'
+ ? 'The persistence protocol guard refused this write and nothing was committed: shared skill publication is not active, or the canonical owner\'s protocol-2 capability '
+ + `changed after it was activated. ${inspect}; stop older writers and direct-file skill servers, then activate shared skill persistence on the canonical host again, `
+ + `and retry with a new request ID. ${never}`
+ : code === 'unsupported_mutation_protocol'
+ ? 'The persistence protocol guard refused a request whose target or protocol does not fit its operation, and nothing was committed: a gbrain defect or a version mismatch '
+ + `between gbrain processes sharing the database. ${inspect}, upgrade or restart every older gbrain process, then submit the write again with a new request ID; `
+ + `an accepted request's target cannot change. ${never}`
+ : code === 'writer_coordinator_required' ? DATABASE_REFUSAL_HINT : null;
+ return suggestion ? { suggestion, docs: docsAnchor('protocol_guard') } : null;
+}
+
/** #5974: another database trigger (named in write_error_detail.raiser) refused the write. */
/** #6719: an owner exception's recorded identity (class, errno, frame, build) does not name its cause; nothing proves the database refused it. */
export const ownerExceptionHint = (requestId: string) => 'An unexpected owner exception ended this write and nothing was committed; its cause is unknown from the recorded identity alone. '
@@ -112,6 +152,8 @@ export function receiptDeliveredHint(receipt: { error_code?: string | null; erro
error_detail?: Record<string, unknown> | null }):
{ suggestion: string; detail?: string; docs: string } | null {
const source = receipt.source_id ?? '<source>';
+ const guard = guardRefusalHint(receipt.error_code, receipt.error_detail);
+ if (guard) return { detail: 'database_guard', ...guard };
switch (receipt.error_code) {
case 'connector_intent_outdated': {
const preUpgrade = receipt.error_message === CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE;
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 9e90a65128..0217d65462 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -12,7 +12,7 @@ import { listHostConsumers, type ConsumerPool, type ListedConsumer } from './con
import type { WriteRequestState } from './types.ts';
import { preparationBudgetMs } from './preparation-budget.ts';
import { readWriteSwitchSnapshot } from './switches.ts';
-import { DATABASE_REFUSAL_HINT, DATABASE_TRIGGER_HINT, ownerExceptionHint, unknownOriginHint } from './connector-errors.ts';
+import { DATABASE_REFUSAL_HINT, DATABASE_TRIGGER_HINT, guardRefusalHint, ownerExceptionHint, unknownOriginHint } from './connector-errors.ts';
import { readQueuedHeadBlockers } from './head-blocker.ts';
import { SOURCE_CHANGED_ORIGINS } from './publication-failure.ts';
@@ -136,8 +136,11 @@ export function capacityDiagnostics(counters: Counter[], limits: JournalLimits)
});
});
}
-/** #6719: the next step a recorded origin supports; only a database origin reads as a database refusal. */
-function recentFailureNextAction(origin: unknown, requestId: string): string {
+/** #6719: the next step a recorded origin supports; only a database origin reads as a database refusal. #7777/#7780: a guard refusal whose cause is known names its own. */
+function recentFailureNextAction(row: { error_code: string | null; error_detail: Record<string, unknown>; request_id: string }): string {
+ const origin = row.error_detail?.origin, requestId = row.request_id;
+ const guard = guardRefusalHint(row.error_code, row.error_detail)?.suggestion;
+ if (guard) return guard;
if (origin === 'database_guard') return DATABASE_REFUSAL_HINT;
if (origin === 'database_trigger' || origin === 'database') return DATABASE_TRIGGER_HINT;
return origin === 'owner_exception' ? ownerExceptionHint(requestId) : unknownOriginHint(requestId);
@@ -200,7 +203,7 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
return { ...brain, sampled_at: new Date().toISOString(), publication_concurrency: publicationConcurrency(engine),
local_process_ingress, worktrees, counters, queue, effects,
limits: Object.fromEntries(Object.entries(limits).filter(([, value]) => Number.isFinite(value))), capacity: capacityDiagnostics(counters, limits), preparation_policy,
- recent_failures: failures.map(row => ({ ...row, next_action: recentFailureNextAction(row.error_detail?.origin, row.request_id) })),
+ recent_failures: failures.map(row => ({ ...row, next_action: recentFailureNextAction(row) })),
backend_visibility: backends.visibility,
blockers: blockers.map(({ id: rowId, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }, index) => {
const health = writeHealth(row);
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index d95a14a95a..ba0de5cfdc 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -34,6 +34,8 @@ export interface PublicationFailureDetail {
reason?: PublicationReason;
/** Owner-only, #6904: the relation or column a `schema_missing` refusal names (an identifier, never a value). */
missing?: string;
+ /** Owner-only, #7780: the table an `unreadable_state` refusal could not fully read (`UNREADABLE_STATES`). */
+ state?: string;
/** Owner-only: source identifiers can name private sources. */
sources?: { target: string | null; old: string | null; allowed: string[] };
stage?: PublicationStage;
@@ -121,10 +123,38 @@ const RELATIONSHIP_TEXT: Record<string, string> = {
old_source_outside: 'a row moved from a source this publication does not own',
checkpoint_outside_owner: 'a source sync checkpoint outside owner publication',
topology_outside_administration: 'a source topology change outside writer administration',
- unreadable_state: 'writer state this database role cannot read (row-level security hides it, or its row is missing)',
+ unreadable_state: 'writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)',
};
+/** #7780: the tables an unreadable_state raise names in its DETAIL `state` (writer-guard-schema.ts, git-canonical-schema.ts). */
+const UNREADABLE_STATES: ReadonlySet<unknown> = new Set(['persistence_brain', 'git_canonical_brain', 'sources', 'pages']);
-function guardDetail(raw: unknown): Pick<PublicationFailureDetail, 'op' | 'relationship' | 'sources'> {
+/**
+ * #7777: the persistence protocol guards (shared-skills/persistence-schema.ts) raise SQLSTATE 42501, which is also
+ * ordinary permission denial (a missing GRANT, row-level security). A 42501 is typed only when the innermost PL/pgSQL
+ * frame is one of these guards and the message is one of that guard's own fixed diagnostics, verbatim; its code is the
+ * message prefix. Anything else at 42501 stays unclassified.
+ */
+const PROTOCOL_GUARD_SQLSTATE = '42501';
+const PROTOCOL_UNREADABLE = 'writer_coordinator_required: writer state is unreadable to this database role';
+const PROTOCOL_DISABLED = 'writer_not_quiesced: shared publication is disabled';
+const PROTOCOL_GUARD_DIAGNOSTICS = new Map<string, readonly string[]>([
+ ['gbrain_require_persistence_protocol', ['writer_upgrade_required: this mutation requires persistence protocol 2']],
+ ['gbrain_guard_request_protocol', [PROTOCOL_UNREADABLE, PROTOCOL_DISABLED,
+ 'unsupported_mutation_protocol: a request target is immutable',
+ 'unsupported_mutation_protocol: skill operations require a typed target',
+ 'unsupported_mutation_protocol: invalid skill target',
+ 'unsupported_mutation_protocol: invalid page target',
+ 'unsupported_mutation_protocol: recovery target mismatch',
+ 'writer_not_quiesced: canonical owner capability must be revalidated']],
+ ['gbrain_guard_effect_protocol', [PROTOCOL_UNREADABLE]],
+ ['gbrain_guard_protocol_activation', [PROTOCOL_UNREADABLE,
+ 'writer_upgrade_required: the protocol floor cannot be lowered',
+ 'writer_not_quiesced: drain and verify all canonical owners before activation']],
+ ['gbrain_guard_skill_publication', [PROTOCOL_DISABLED,
+ 'writer_coordinator_required: canonical skill writes require a coordinated source capability']],
+]);
+
+function guardDetail(raw: unknown): Pick<PublicationFailureDetail, 'op' | 'relationship' | 'state' | 'sources'> {
if (typeof raw !== 'string' || raw.length > 4096) return {};
let parsed: Record<string, unknown>;
try { parsed = JSON.parse(raw) as Record<string, unknown>; } catch { return {}; }
@@ -132,6 +162,7 @@ function guardDetail(raw: unknown): Pick<PublicationFailureDetail, 'op' | 'relat
const allowed = Array.isArray(parsed.allowed) ? parsed.allowed.map(ident).filter((v): v is string => !!v).slice(0, 32) : [];
const target = ident(parsed.target_source) ?? null, old = ident(parsed.old_source) ?? null;
return { op: ident(parsed.op), relationship: ident(parsed.relationship),
+ ...(UNREADABLE_STATES.has(parsed.state) ? { state: parsed.state as string } : {}),
...(target || old || allowed.length ? { sources: { target, old, allowed } } : {}) };
}
@@ -175,12 +206,21 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {
}
if (sqlstate === READ_ONLY_SQLSTATE) return { code: 'connection_inherited_read_only', detail: { origin: 'database', sqlstate },
message: `The database refused this write as read-only (SQLSTATE ${sqlstate}${typeof e.message === 'string' ? `: ${e.message}` : ''}), so nothing was committed: the server connection defaults to read-only transactions (pooler session state left by another client, a role or database default, or a read-only server).` };
- if (sqlstate !== 'P0001' && sqlstate !== GRADUATION_SQLSTATE) return null;
+ if (sqlstate !== 'P0001' && sqlstate !== GRADUATION_SQLSTATE && sqlstate !== PROTOCOL_GUARD_SQLSTATE) return null;
const where = typeof e.where === 'string' ? e.where : '';
const raiser = ident(/PL\/pgSQL function (?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)[( ]/.exec(where)?.[1]);
const table = ident(e.table_name ?? e.table);
const constraint = typeof (e.constraint_name ?? e.constraint) === 'string' ? String(e.constraint_name ?? e.constraint) : '';
const message = typeof e.message === 'string' ? e.message : '';
+ if (sqlstate === PROTOCOL_GUARD_SQLSTATE) {
+ if (!raiser || !PROTOCOL_GUARD_DIAGNOSTICS.get(raiser)?.includes(message)) return null;
+ const separator = message.indexOf(': ');
+ return { code: message.slice(0, separator),
+ message: `The persistence protocol guard (${raiser}) refused this write: ${message.slice(separator + 2)}. Nothing was committed.`,
+ detail: { origin: 'database_guard', sqlstate, raiser,
+ ...(message === PROTOCOL_UNREADABLE ? { branch: 'unreadable_state', relationship: 'unreadable_state' } : {}),
+ ...(message === PROTOCOL_UNREADABLE && raiser !== 'gbrain_guard_protocol_activation' ? { state: 'persistence_brain' } : {}) } };
+ }
if (sqlstate === GRADUATION_SQLSTATE) {
const reason = publicationReason(sqlstate, raiser, message);
return { code: 'storage_error', detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}), reason },
diff --git a/src/core/repair/connector-fences.ts b/src/core/repair/connector-fences.ts
index 4c4adec019..5f6a8c813d 100644
--- a/src/core/repair/connector-fences.ts
+++ b/src/core/repair/connector-fences.ts
@@ -19,11 +19,10 @@ import { conceptPreservationHold } from '../cycle/concept-publication.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
import { segmentedRegionContains } from '../page-body/segment-lines.ts';
+import { countOutsideCode, locateOutsideCode } from '../fence-scan.ts';
import { SEGMENTED_SAMPLE } from './timeline.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';
-const count = (text: string, marker: string) => text.split(marker).length - 1;
-
/**
* The page with every below-sentinel fence moved into its body, or null when
* nothing needs moving or the move would be ambiguous or lossy.
@@ -33,10 +32,10 @@ export function relocateTimelineFences(page: { compiled_truth: string | null; ti
let timeline = page.timeline ?? '';
let moved = false;
for (const [begin, end] of [[FACTS_FENCE_BEGIN, FACTS_FENCE_END], [TAKES_FENCE_BEGIN, TAKES_FENCE_END]] as const) {
- if (!timeline.includes(begin) && !timeline.includes(end)) continue;
- if (count(timeline, begin) !== 1 || count(timeline, end) !== 1 || count(body, begin) || count(body, end)) return null;
- const start = timeline.indexOf(begin);
- const stop = timeline.indexOf(end, start);
+ const inTimeline = [countOutsideCode(timeline, begin), countOutsideCode(timeline, end)];
+ if (!inTimeline[0] && !inTimeline[1]) continue;
+ if (inTimeline[0] !== 1 || inTimeline[1] !== 1 || countOutsideCode(body, begin) || countOutsideCode(body, end)) return null;
+ const { beginIdx: start, endIdx: stop } = locateOutsideCode(timeline, begin, end);
if (stop === -1) return null;
const block = timeline.slice(start, stop + end.length);
timeline = `${timeline.slice(0, start)}${timeline.slice(stop + end.length)}`.replace(/\n{3,}/g, '\n\n').trim();
diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index edd37e7a14..1a560ad2ef 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -47,6 +47,7 @@ import { authorizeWrite } from '../persistence/authority.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
+import { nativeFileTarget } from '../persistence/native-file-target.ts';
import { clearDeletionHold, readSyncImportProvenance } from '../persistence/sync-holds.ts';
import { readRevisionAttestations } from '../persistence/sync-pass.ts';
import { readDeletionProvenance } from '../persistence/sync-origin-evidence.ts';
@@ -304,9 +305,10 @@ export async function retireGhost(ctx: OperationContext, ghost: GhostPage, owner
* Preparer for `managed_maintenance_retire_ghost_page`: re-runs the classifier under the approved owner, prepares a
* `delete_page` with `allowMissingFile`, and refuses unless the prepared file target is the approved path with no
* bytes (a file restored in between refuses here, or at filesystem publication when it appears later). #7736: a page
- * whose approved path is a recorded non-Markdown file is prepared at its slug path, which must hold no bytes either;
- * the classifier re-checks the recorded file here; one restored after preparation is not seen at publication, and
- * the soft delete stays undoable with `gbrain restore <slug> --force` until the purge.
+ * whose approved path is a recorded non-Markdown file is prepared at its slug path, which must hold no bytes either.
+ * #7967: its file target is then moved to the recorded file, still expecting no bytes, so filesystem publication refuses
+ * a recorded file restored after preparation and the door commits the recorded file's removal (on a git-canonical
+ * source HEAD drops it with the page), never a removal of `<slug>.md`.
*/
export async function prepareGhostPageRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const ghost = row.intent!.ghost as GhostPage | undefined;
@@ -332,7 +334,8 @@ export async function prepareGhostPageRetirement(engine: BrainEngine, row: Write
const recordedFile = !/\.mdx?$/i.test(ghost.path) && target === `${ghost.slug}.md`;
if (!page.file || (target !== ghost.path && !recordedFile)) throw refuse(changed('its canonical file target moved'));
if (page.file.expectedBeforeHash !== null) throw refuse(restored(ghost));
- return { ...page, validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); },
+ const file = recordedFile ? { ...page.file, path: nativeFileTarget(page.file.root, join(page.file.root, ghost.path)) } : page.file;
+ return { ...page, file, validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); },
// GBRA-133: the soft delete is the decision a held deletion of this file waited for, so its hold clears with it.
apply: async (tx, preimage) => {
const outcome = await page.apply(tx, preimage);
diff --git a/src/core/repair/take-supersession.ts b/src/core/repair/take-supersession.ts
index 6c197c990c..06f1c184ed 100644
--- a/src/core/repair/take-supersession.ts
+++ b/src/core/repair/take-supersession.ts
@@ -46,6 +46,7 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
import { TAKES_FENCE_BEGIN, parseTakesFence, type ParsedTake } from '../takes-fence.ts';
+import { countOutsideCode } from '../fence-scan.ts';
import { takesPreparation } from '../takes-write.ts';
import { afterCursor, repairRequestId, type RepairCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairScope } from './core.ts';
@@ -162,7 +163,7 @@ async function readPage(engine: BrainEngine, page: TakePage): Promise<PageState>
const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
if (!snapshot) return null;
const content = serializePageToMarkdown(snapshot.page, snapshot.tags);
- if (content.split(TAKES_FENCE_BEGIN).length !== 2) return { skipped: 'unparsed' };
+ if (countOutsideCode(content, TAKES_FENCE_BEGIN) !== 1) return { skipped: 'unparsed' };
const parsed = parseTakesFence(content);
if (parsed.warnings.length || !parsed.takes.length) return { skipped: 'unparsed' };
const stored = await engine.executeRaw<{ row_num: number; superseded_by: number | null }>(
diff --git a/src/core/secret-scan-labeled.ts b/src/core/secret-scan-labeled.ts
index 955f757d32..772e1692fb 100644
--- a/src/core/secret-scan-labeled.ts
+++ b/src/core/secret-scan-labeled.ts
@@ -95,10 +95,11 @@ export const LABELED_CREDENTIAL_PATTERNS: readonly LabeledPattern[] = [
* #7997: an importer redaction marker (`<REDACTED:kind>`) with its colon swapped, the same length, so the label
* patterns read it as one word. Its colon used to split it into a claimed `user:pass` pair, while a credential written
* beside a marker (`login <REDACTED:user-pattern> / s3cret!`) still matches. A marker glued to more text
- * (`<REDACTED:x>s3cret!`) is left alone, so that text is still claimed as it was before.
+ * (`<REDACTED:x>s3cret!`) is left alone, so that text is still claimed as it was before. Punctuation after a marker
+ * ends it only when whitespace or the line end follows (`<REDACTED:x>.` ends a sentence; `<REDACTED:x>,s3cret!` is glued).
*/
export function neutralizeRedactionMarkers(line: string): string {
- return line.includes('<REDACTED:') ? line.replace(/<REDACTED:(?=[A-Za-z0-9_-]{1,64}>[*_]{0,2}(?:[\s/:"'`.,;!?)\]}]|$))/g, '<REDACTED_') : line;
+ return line.includes('<REDACTED:') ? line.replace(/<REDACTED:(?=[A-Za-z0-9_-]{1,64}>[*_]{0,2}(?:[\s/:"'`]|[.,;!?)\]}]{1,8}(?:\s|$)|$))/g, '<REDACTED_') : line;
}
/** Cheap gate before the label regexes run on a line. */
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index 43c4243eb2..f35804c09a 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -47,6 +47,7 @@ import type { PageType } from '../types.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
import type { PageVersion } from '../page-state/version-types.ts';
+import type { WriteThroughResult } from '../write-through.ts';
import { maintenanceAttribution, principalAttribution, withWriteAttribution } from '../persistence/attribution.ts';
import { withCoordinatedWrite, withTrustKeep, withTrustPromotion } from '../persistence/context.ts';
import type { OwnerConfirmation } from './confirm.ts';
@@ -358,27 +359,62 @@ async function publishOwnerPage(engine: BrainEngine, input: PageActionInput, int
'Fix the checkout (gbrain sources status), then preview the repair again.');
}
const writeThrough = file?.ok && file.target ? await import('../write-through.ts') : null;
- await engine.transaction(tx => withWriteAttribution(tx, { ...attribution, trust }, () => withTrustPromotion(tx, tier, () =>
- withTrustKeep(tx, FENCE_TABLES, async () => {
- if ((await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision !== input.expectedRevision) {
- throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
- }
- // forceRechunk: the trust_tier marker is hash-ephemeral, so removing it alone would read as unchanged content.
- const prior = intent.mode === 'restore_provenance' ? await readPageTrustState(tx, input.sourceId, input.slug) : null;
- await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, preserveGateMarkers: intent.mode !== 'revert', forceRechunk: true, allowEmptyOverwrite: intent.mode === 'revert' });
- if (prior) await recordAgentPageLowering(tx, { operation: TRUST_OWNER_PAGE_OPERATION, source_id: input.sourceId, slug: input.slug }, { tier: prior.tier, revision: prior.revision }, PROVENANCE_PROPOSER);
- if (writeThrough && file?.ok && file.target) {
- const written = await writeThrough.writePageThrough(tx, input.slug, { sourceId: input.sourceId, expectedFileBytes: file.target.expectedFileBytes });
- if (written.skipped === 'file_changed') throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
- if (!written.written) {
- throw opError('unavailable', `The page file of ${pageRef(input.sourceId, input.slug)} could not be written (${written.skipped ?? written.error}); nothing was changed.`,
- 'Fix the checkout (gbrain sources status), then preview the repair again.');
+ // #7960: the file is written (and on a hardened checkout committed) inside the transaction, Git first; when the
+ // database commit then fails, the file and its commit are put back so a failed apply leaves both sides unchanged.
+ let rendered = null as WriteThroughResult | null;
+ try {
+ await engine.transaction(tx => withWriteAttribution(tx, { ...attribution, trust }, () => withTrustPromotion(tx, tier, () =>
+ withTrustKeep(tx, FENCE_TABLES, async () => {
+ if ((await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision !== input.expectedRevision) {
+ throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
}
- }
- await closeProposal(tx, intent.proposal, input.by);
- }))));
+ // forceRechunk: the trust_tier marker is hash-ephemeral, so removing it alone would read as unchanged content.
+ const prior = intent.mode === 'restore_provenance' ? await readPageTrustState(tx, input.sourceId, input.slug) : null;
+ await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, preserveGateMarkers: intent.mode !== 'revert', forceRechunk: true, allowEmptyOverwrite: intent.mode === 'revert' });
+ if (prior) await recordAgentPageLowering(tx, { operation: TRUST_OWNER_PAGE_OPERATION, source_id: input.sourceId, slug: input.slug }, { tier: prior.tier, revision: prior.revision }, PROVENANCE_PROPOSER);
+ if (writeThrough && file?.ok && file.target) {
+ const written = await writeThrough.writePageThrough(tx, input.slug, { sourceId: input.sourceId, expectedFileBytes: file.target.expectedFileBytes });
+ if (written.skipped === 'file_changed') throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
+ if (!written.written) {
+ throw opError('unavailable', `The page file of ${pageRef(input.sourceId, input.slug)} could not be written (${written.skipped ?? written.error}); nothing was changed.`,
+ 'Fix the checkout (gbrain sources status), then preview the repair again.');
+ }
+ rendered = written;
+ }
+ await closeProposal(tx, intent.proposal, input.by);
+ }))));
+ } catch (error) {
+ if (rendered?.path && file?.ok && file.target) await restoreOwnerRepairFile(engine, input.slug, file.target, rendered);
+ throw error;
+ }
}
+/**
+ * #7960: puts back the bytes an owner repair's file held before `rendered` replaced them (removes a file it created), only
+ * while the file still holds what the repair wrote, and commits that restore when the repair's write was committed.
+ * Best-effort: the caller rethrows the database failure either way.
+ */
+async function restoreOwnerRepairFile(engine: BrainEngine, slug: string, target: OwnerRepairTarget, rendered: WriteThroughResult): Promise<void> {
+ const { existsSync, readFileSync, rmSync } = await import('node:fs');
+ const { atomicWriteFileSync } = await import('../atomic-write.ts');
+ const { commitWriteThroughFile } = await import('../brain-repo-durability.ts');
+ const { withSourceFilesystemLock } = await import('../minions/source-filesystem.ts');
+ const path = rendered.path!;
+ try {
+ await withSourceFilesystemLock(engine, target.writeRoot, async () => {
+ if ((existsSync(path) ? readFileSync(path, 'utf-8') : null) !== rendered.content) return;
+ if (target.expectedFileBytes === null) rmSync(path, { force: true });
+ else atomicWriteFileSync(path, target.expectedFileBytes);
+ if (rendered.committed) commitWriteThroughFile(target.writeRoot, path, slug, 'restore write-through');
+ });
+ } catch (error) {
+ console.error(`[trust] ${slug}: the page file could not be restored after the database write failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+/** The checkout file an owner repair renders: the bytes it must still find, and the write root its commit goes through. */
+type OwnerRepairTarget = { expectedFileBytes: string | null; writeRoot: string };
+
/** Write-through outcomes that leave a repair database-only on purpose: no checkout, write-through off, an ignored or db_only target. */
const DATABASE_ONLY_TARGETS = ['no_repo_configured', 'disabled_by_config', 'not_canonical'];
@@ -390,7 +426,7 @@ const DATABASE_ONLY_TARGETS = ['no_repo_configured', 'disabled_by_config', 'not_
* next pull would undo a database-only repair). Read-only.
*/
export async function ownerRepairFile(engine: BrainEngine, sourceId: string, slug: string):
- Promise<{ ok: true; target: { expectedFileBytes: string | null } | null } | { ok: false; reason: string }> {
+ Promise<{ ok: true; target: OwnerRepairTarget | null } | { ok: false; reason: string }> {
const { derivedFileTarget } = await import('../cycle/derived-write-through.ts');
const resolved = await derivedFileTarget(engine, slug, sourceId);
if (!resolved.ok) return DATABASE_ONLY_TARGETS.includes(resolved.skipped) ? { ok: true, target: null } : { ok: false, reason: resolved.skipped };
@@ -398,7 +434,7 @@ export async function ownerRepairFile(engine: BrainEngine, sourceId: string, slu
if (await urlCloneReadOnly(engine, sourceId)) return { ok: false, reason: 'url_clone' };
const { replaceableFile } = await import('../facts/file-body-guard.ts');
const file = await replaceableFile(engine, sourceId, slug, resolved.target.filePath);
- return file.ok ? { ok: true, target: { expectedFileBytes: file.expectedFileBytes } } : { ok: false, reason: 'file_database_drift' };
+ return file.ok ? { ok: true, target: { expectedFileBytes: file.expectedFileBytes, writeRoot: resolved.target.writeRoot } } : { ok: false, reason: 'file_database_drift' };
}
/** Admits the journaled owner page mutation and waits for its publication (the decide_proposal precedent). */
diff --git a/test/conversation-facts-outcome-marker-purge-7778.test.ts b/test/conversation-facts-outcome-marker-purge-7778.test.ts
index 1ffd7bd139..8acc82ad8a 100644
--- a/test/conversation-facts-outcome-marker-purge-7778.test.ts
+++ b/test/conversation-facts-outcome-marker-purge-7778.test.ts
@@ -26,8 +26,14 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { TERMINAL_AUDIT_SOURCE, outcomeMarkerSql } from '../src/core/facts/audit-sources.ts';
import { GUARD_OUTCOME_MARKER_SQL } from '../src/core/facts/insert-guard-schema.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { replayPurgesInRestore, type PurgeMirrorLine } from '../src/core/belief/purge-mirror.ts';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
let engine: BrainEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-outcome-marker-purge-'));
const KEPT = 'Owner Example sends the quarterly plan on Thursday';
const PURGED = 'Alice Example reviews plans on Mondays';
@@ -71,6 +77,23 @@ async function markerTombstones() {
return Number(row?.n ?? 0);
}
+const PROSE = (title: string) => ['---', `title: ${title}`, 'type: meeting', 'date: 2026-09-28', '---',
+ '**Date:** 2026-09-28', '**Attendees:** Alice Example, Owner Example', '', '## Notes', 'Hiring, the support backlog and the launch dates.', ''].join('\n');
+
+async function outcomeRows() {
+ return (await engine.executeRaw<{ id: number | string; fact: string; slug: string }>(`SELECT id, fact, source_markdown_slug AS slug FROM facts
+ WHERE source_id='default' AND expired_at IS NULL AND ${outcomeMarkerSql('facts')} ORDER BY id`)).map(r => ({ ...r, id: Number(r.id) }));
+}
+
+/** #7831: the owner's confirmed purge_fact (dry run, then confirm with its token and revision). */
+async function confirmedPurge(id: number) {
+ return withEnv({ GBRAIN_HOME: home }, async () => {
+ const dry = await call('purge_fact', { id, dry_run: true });
+ expect(dry.confirm_token).toBeDefined();
+ return call('purge_fact', { id, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ });
+}
+
/** Seeds the pre-#7778 wildcard marker tombstone, then runs twice: the first run completes both pages, the second makes no provider call. */
async function convergesDespiteMarkerTombstone(put: (slug: string, title: string) => Promise<void>) {
const slugs = ['meetings/run-1', 'meetings/run-2'];
@@ -105,7 +128,7 @@ for (const backend of testBackends()) {
if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
}, 120_000);
- afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await template?.dispose(); await pglite?.disconnect(); });
+ afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await template?.dispose(); await pglite?.disconnect(); rmSync(home, { recursive: true, force: true }); });
beforeEach(async () => {
if (pglite) { engine = pglite; await disposePersistenceConsumer(engine); await resetPgliteState(pglite); }
else { const c = await template!.clone(); engine = c.engine; close = c.close; }
@@ -174,6 +197,69 @@ for (const backend of testBackends()) {
expect(await completed(['meetings/run-1'])).toEqual(['meetings/run-1']);
});
+ for (const marker of ['EXTRACTION_COMPLETE', 'EXTRACTION_NOT_APPLICABLE']) {
+ test(`#7831: purging a user claim whose text is ${marker} leaves every outcome row in place`, async () => {
+ await call('put_page', { slug: 'meetings/run-1', content: transcript('Run 1') });
+ await call('put_page', { slug: 'meetings/notes', content: PROSE('Planning notes') });
+ await extract(['meetings/run-1', 'meetings/notes'], [KEPT, marker], { n: 0 });
+ const before = await outcomeRows();
+ expect(before.map(r => [r.slug, r.fact])).toEqual([['meetings/run-1', 'EXTRACTION_COMPLETE'], ['meetings/notes', 'EXTRACTION_NOT_APPLICABLE']]);
+ const [claim] = await engine.executeRaw<{ id: number | string }>(`SELECT id FROM facts WHERE source_id='default' AND fact=$1 AND NOT ${outcomeMarkerSql('facts')}`, [marker]);
+ expect(claim).toBeDefined();
+ const done = await confirmedPurge(Number(claim!.id));
+ expect(done.state).toBe('committed');
+ expect(done.subject).toBe('*');
+ expect(done.stores.find((s: any) => s.store === 'facts')).toMatchObject({ status: 'deleted', removed: 1 });
+ expect(done.residuals.find((s: any) => s.store === 'facts_other_scope')).toBeUndefined();
+ expect(['committed', 'complete']).toContain(done.completion);
+ expect(await outcomeRows()).toEqual(before);
+ expect(await engine.executeRaw(`SELECT 1 FROM facts WHERE source_id='default' AND fact=$1 AND NOT ${outcomeMarkerSql('facts')}`, [marker])).toHaveLength(0);
+ const [tombstones] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*)::int AS n FROM fact_purges WHERE source_id='default' AND subject='*' AND fact_hash=gbrain_fact_fingerprint($1)`, [marker]);
+ expect(Number(tombstones?.n)).toBe(1);
+ const status = await withEnv({ GBRAIN_HOME: home }, () => call('purge_fact', { status: true, request_id: done.request_id }));
+ expect(status.fingerprint_probe).toEqual({ facts: 0, takes: 0 });
+ const again = { n: 0 };
+ expect((await extract(undefined, [KEPT], again)).pages_processed).toBe(0);
+ expect(again.n).toBe(0);
+ expect(await completed(['meetings/run-1'])).toEqual(['meetings/run-1']);
+ });
+ }
+
+ test('#7831: a restore replay of a purge of the marker text leaves the restored outcome rows in place', async () => {
+ await call('put_page', { slug: 'meetings/run-1', content: transcript('Run 1') });
+ await call('put_page', { slug: 'meetings/notes', content: PROSE('Planning notes') });
+ await extract(['meetings/run-1', 'meetings/notes'], [KEPT, 'EXTRACTION_COMPLETE'], { n: 0 });
+ const before = await outcomeRows();
+ expect(before).toHaveLength(2);
+ const [claim] = await engine.executeRaw<{ visibility: string; fact_hash: string }>(`SELECT visibility, gbrain_fact_fingerprint(fact) AS fact_hash FROM facts
+ WHERE source_id='default' AND fact='EXTRACTION_COMPLETE' AND NOT ${outcomeMarkerSql('facts')}`);
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ const request = randomUUID();
+ const lines: PurgeMirrorLine[] = [
+ { kind: 'intent', request, request_id: request, source_id: 'default', source_incarnation: source!.incarnation, scope: 'fact', recorded_at: new Date().toISOString(),
+ purge_epoch: 1, facts: [{ fact_hash: claim!.fact_hash, visibility: claim!.visibility, subject: '*' }], takes: [], lifetimes: [] },
+ { kind: 'committed', request, recorded_at: new Date().toISOString() },
+ ];
+ const result = await engine.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt: new Date(Date.now() - 60_000).toISOString(), restoreId: randomUUID() }));
+ expect(result.replays.map(r => [r.request, r.outcome])).toEqual([[request, 'complete']]);
+ expect(await engine.executeRaw(`SELECT 1 FROM facts WHERE source_id='default' AND fact='EXTRACTION_COMPLETE' AND NOT ${outcomeMarkerSql('facts')}`)).toHaveLength(0);
+ expect(await outcomeRows()).toEqual(before);
+ });
+
+ test('a wildcard EXTRACTION_NOT_APPLICABLE tombstone does not keep a not-extractable page from recording its outcome', async () => {
+ await tombstone('EXTRACTION_NOT_APPLICABLE');
+ await call('put_page', { slug: 'meetings/notes', content: PROSE('Planning notes') });
+ const first = { n: 0 };
+ const run1 = await extract(['meetings/notes'], [KEPT], first);
+ expect(run1.pages_failed).toBe(0);
+ expect(run1.facts_skipped_purged ?? 0).toBe(0);
+ expect((await outcomeRows()).map(r => [r.slug, r.fact])).toEqual([['meetings/notes', 'EXTRACTION_NOT_APPLICABLE']]);
+ const second = { n: 0 };
+ expect((await extract(undefined, [KEPT], second)).pages_processed).toBe(0);
+ expect(first.n + second.n).toBe(0);
+ expect(await markerTombstones()).toBe(1);
+ });
+
test('the facts insert guard exempts only the exact outcome row: another claim under the audit source is still refused', async () => {
await call('put_page', { slug: 'meetings/run-1', content: transcript('Run 1') });
await extract(['meetings/run-1'], [KEPT], { n: 0 });
diff --git a/test/cycle/derived-write-through-commit.test.ts b/test/cycle/derived-write-through-commit.test.ts
index 929a14f4a9..02fa460376 100644
--- a/test/cycle/derived-write-through-commit.test.ts
+++ b/test/cycle/derived-write-through-commit.test.ts
@@ -24,10 +24,10 @@
* call). PGLite always, Postgres when DATABASE_URL is set.
*/
import { describe, expect, test } from 'bun:test';
-import { execFileSync } from 'node:child_process';
+import { execFileSync, spawn } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';
import { derivedWriteSeams } from '../../src/core/cycle/derived-write-through.ts';
import { commitPathsLocked } from '../../src/core/git/commit-push.ts';
@@ -281,5 +281,69 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
.toEqual({ commits: 1, paths: ['concepts/flywheel.md'], dirty: '', body: true });
});
}, 180_000);
+
+ test('#8092: a refused rewrite of a tracked concept file is written again on the next run, though the concept did not change', async () => {
+ await withBrain(databaseUrl, 'git', async b => {
+ const atoms = (n: number) => Array.from({ length: n }, (_, i) => ({ slug: `atoms/a${i}`, title: `A${i}`, body: `b${i}`, concept_refs: ['flywheel'], visibility: 'world' as const }));
+ await b.engine.setConfig('cycle.synthesize_concepts.write_through', 'true');
+ await runPhaseSynthesizeConcepts(b.engine, { _atoms: atoms(2), sourceId: 'default' });
+ refuseCommits(b);
+ await runPhaseSynthesizeConcepts(b.engine, { _atoms: atoms(3), sourceId: 'default' });
+ const page = await b.engine.getPage('concepts/flywheel', { sourceId: 'default' });
+ expect({ db: page!.compiled_truth.includes('3 atoms reference this.'), dirty: dirty(b),
+ head: b.git('show', 'HEAD:concepts/flywheel.md').includes('3 atoms reference this.') }).toEqual({ db: true, dirty: '', head: false });
+ rmSync(join(b.root, '.git', 'hooks', 'pre-commit'));
+ await runPhaseSynthesizeConcepts(b.engine, { _atoms: atoms(3), sourceId: 'default' });
+ expect({ dirty: dirty(b), head: b.git('show', 'HEAD:concepts/flywheel.md').includes('3 atoms reference this.') }).toEqual({ dirty: '', head: true });
+ });
+ }, 180_000);
+
+ test('#8092: a refused removal of a retired atom\'s file is removed again on the next run, so HEAD stops holding the retired page', async () => {
+ await withBrain(databaseUrl, 'git', async b => {
+ await b.extract(['Renders vs proof'], 'hash-one');
+ const [old] = (await b.atoms()).map(a => a.slug);
+ refuseCommits(b);
+ const refused = await b.extract(['A different lesson'], 'hash-two');
+ expect({ status: refused.status, retired: (await b.atoms(false)).map(a => a.slug), oldFile: existsSync(b.path(old!)), dirty: dirty(b) })
+ .toEqual({ status: 'warn', retired: [old!], oldFile: true, dirty: '' });
+ rmSync(join(b.root, '.git', 'hooks', 'pre-commit'));
+ const retry = await b.extract([], null);
+ expect({ failed: retry.failed, oldFile: existsSync(b.path(old!)), tracked: b.git('ls-files', '--', relOf(old!)), dirty: dirty(b) })
+ .toEqual({ failed: [], oldFile: false, tracked: '', dirty: '' });
+ });
+ }, 180_000);
+
+ test('#8092: a rolled-back path leaves the pending ledger, so a later hand edit there is not swept into another gbrain commit', async () => {
+ await withBrain(databaseUrl, 'git', async b => {
+ refuseCommits(b);
+ await b.extract(['Renders vs proof'], 'hash-one');
+ const [atom] = (await b.atoms()).map(a => a.slug);
+ expect(existsSync(b.path(atom!))).toBe(false);
+ rmSync(join(b.root, '.git', 'hooks', 'pre-commit'));
+ mkdirSync(dirname(b.path(atom!)), { recursive: true });
+ writeFileSync(b.path(atom!), 'A hand-written note at this path.\n');
+ writeFileSync(join(b.root, 'notes.md'), 'writer B\n');
+ commitPathsLocked(b.root, ['notes.md'], 'writer B', { lockWaitMs: 5_000 });
+ expect({ paths: lastCommitPaths(b), dirty: dirty(b) }).toEqual({ paths: ['notes.md'], dirty: `?? ${relOf(atom!)}` });
+ });
+ }, 180_000);
+
+ test('#8092: a busy commit lock is waited for without blocking the event loop', async () => {
+ await withBrain(databaseUrl, 'git', async b => {
+ const holder = spawn('flock', [join(b.root, '.git', 'brain-commit.lock'), 'sleep', '4'], { stdio: 'ignore' });
+ let last = performance.now(), gap = 0;
+ const tick = () => { const now = performance.now(); gap = Math.max(gap, now - last); last = now; };
+ const timer = setInterval(tick, 20);
+ let phase: Awaited<ReturnType<Brain['extract']>>;
+ try {
+ await Bun.sleep(300);
+ phase = await b.extract(['Renders vs proof'], 'hash-one');
+ } finally { tick(); clearInterval(timer); holder.kill('SIGKILL'); }
+ const [atom] = await b.atoms();
+ expect({ status: phase.status, failed: phase.failed, paths: lastCommitPaths(b), dirty: dirty(b) })
+ .toEqual({ status: 'ok', failed: [], paths: [relOf(atom!.slug)], dirty: '' });
+ expect(gap).toBeLessThan(1_000);
+ });
+ }, 180_000);
});
}
diff --git a/test/e2e/protocol-guard-refusal-7777-postgres.test.ts b/test/e2e/protocol-guard-refusal-7777-postgres.test.ts
new file mode 100644
index 0000000000..cb539f2bd8
--- /dev/null
+++ b/test/e2e/protocol-guard-refusal-7777-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../protocol-guard-refusal-7777.test.ts'));
diff --git a/test/e2e/unreadable-state-detail-7780-postgres.test.ts b/test/e2e/unreadable-state-detail-7780-postgres.test.ts
new file mode 100644
index 0000000000..90fc51ae8a
--- /dev/null
+++ b/test/e2e/unreadable-state-detail-7780-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../unreadable-state-detail-7780.test.ts'));
diff --git a/test/fence-locators-code-quoted-8020.test.ts b/test/fence-locators-code-quoted-8020.test.ts
new file mode 100644
index 0000000000..5e83ab8b25
--- /dev/null
+++ b/test/fence-locators-code-quoted-8020.test.ts
@@ -0,0 +1,53 @@
+/**
+ * #8020: fence locators that counted or spliced markers as raw text while the fence readers skip a marker inside
+ * markdown code (an inline span or a fenced block, `locateOutsideCode`). A page that quotes a marker in code, which
+ * the content-repair lane's quoted-marker fix produces by wrapping the marker in backticks, was held by the concept
+ * preservation check (CONCEPT_FACTS_FENCE_DUPLICATE: concept republication, the Google connector's fence carry and
+ * the connector-fences repair all refuse) and its timeline fence could not be relocated. The readers' rule is
+ * unchanged; these locators now find the same fence the readers parse. Pure functions; no database.
+ */
+import { describe, expect, test } from 'bun:test';
+import { conceptPreservationHold, preserveCanonicalFences } from '../src/core/cycle/concept-publication.ts';
+import { relocateTimelineFences } from '../src/core/repair/connector-fences.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../src/core/facts-fence.ts';
+import { TAKES_FENCE_BEGIN, parseTakesFence } from '../src/core/takes-fence.ts';
+
+const FACTS = [FACTS_FENCE_BEGIN,
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ '| 1 | Acme example ships in Q3 | fact | 1.0 | world | medium | 2026-01-01 | | notes | |',
+ FACTS_FENCE_END].join('\n');
+const QUOTED = `Writers quote the markers as \`${FACTS_FENCE_BEGIN}\` and \`${FACTS_FENCE_END}\` when they explain the format.`;
+const BLOCK = ['\`\`\`', TAKES_FENCE_BEGIN, '\`\`\`'].join('\n');
+
+describe('#8020: a marker quoted in code is not a fence to the locators either', () => {
+ test('the concept preservation check does not hold a page whose only extra markers sit in code', () => {
+ const page = { compiled_truth: `# Acme example\n\n${QUOTED}\n\n${BLOCK}\n\n## Facts\n\n${FACTS}\n`, timeline: '', body_storage: 'inline' as const };
+ expect(parseFactsFence(page.compiled_truth).facts.map(f => f.claim)).toEqual(['Acme example ships in Q3']);
+ expect(parseTakesFence(page.compiled_truth).takes).toEqual([]);
+ expect(conceptPreservationHold(page)).toBeNull();
+ const republished = preserveCanonicalFences(page, '# Acme example\n\nA new narrative.');
+ expect(parseFactsFence(republished).facts.map(f => f.claim)).toEqual(['Acme example ships in Q3']);
+ expect(republished).toContain(FACTS);
+ expect(republished).not.toContain(TAKES_FENCE_BEGIN);
+ });
+
+ test('a real duplicate fence outside code is still held', () => {
+ const page = { compiled_truth: `# Acme example\n\n${QUOTED}\n\n${FACTS}\n\n${FACTS}\n`, timeline: '' };
+ expect(conceptPreservationHold(page)).toMatch(/^CONCEPT_FACTS_FENCE_DUPLICATE/);
+ });
+
+ test('a timeline that only quotes a marker in code is not a fence below the sentinel', () => {
+ const page = { compiled_truth: `# Acme example\n\n## Facts\n\n${FACTS}\n`, timeline: `- **2026-10-01** | ${QUOTED}` };
+ expect(conceptPreservationHold(page)).toBeNull();
+ });
+
+ test('connector-fences relocates the timeline fence when the body quotes its marker in code', () => {
+ const page = { compiled_truth: `# Acme example\n\n${QUOTED}\n`, timeline: `- **2026-10-01** | Kickoff\n\n${FACTS}\n` };
+ const moved = relocateTimelineFences(page);
+ expect(moved).not.toBeNull();
+ expect(moved!.timeline).toBe('- **2026-10-01** | Kickoff');
+ expect(moved!.compiled_truth).toContain(QUOTED);
+ expect(parseFactsFence(moved!.compiled_truth).facts.map(f => f.claim)).toEqual(['Acme example ships in Q3']);
+ });
+});
diff --git a/test/ghost-pages-6696.test.ts b/test/ghost-pages-6696.test.ts
index 658155da2c..d27f40329b 100644
--- a/test/ghost-pages-6696.test.ts
+++ b/test/ghost-pages-6696.test.ts
@@ -317,6 +317,22 @@ for (const backend of testBackends()) describe(`#6696 B5 ghost pages (${backend}
}, { managed }));
}
+ test('#7967: a code page whose recorded JSON file is restored at consumer:prepared is refused at publication and kept', () => fixture(async f => {
+ await seedCodePage(f);
+ const bytes = readFileSync(join(f.root, CODE_PATH), 'utf8');
+ unlinkSync(join(f.root, CODE_PATH));
+ const preview = await repair(f.sourceId);
+ expect(preview.sample).toEqual([`${f.sourceId}:${CODE_SLUG}`]);
+ installFaultHook((at, detail) => {
+ if (at === 'consumer:prepared' && detail.operation === 'submit_job') writeFileSync(join(f.root, CODE_PATH), bytes);
+ });
+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ applied: 0, outcomes: { file_restored: 1 } });
+ expect(await live(f.sourceId, CODE_SLUG)).toBe(true);
+ expect(readFileSync(join(f.root, CODE_PATH), 'utf8')).toBe(bytes);
+ expect(existsSync(join(f.root, `${CODE_SLUG}.md`))).toBe(false);
+ }));
+
test('#7736: a code page whose recorded path names no file inside the source is reported unresolvable and never removed', () => fixture(async f => {
await seed(f);
await seedCodePage(f);
diff --git a/test/ghost-pages-git-canonical-7967.test.ts b/test/ghost-pages-git-canonical-7967.test.ts
new file mode 100644
index 0000000000..723f138479
--- /dev/null
+++ b/test/ghost-pages-git-canonical-7967.test.ts
@@ -0,0 +1,63 @@
+/**
+ * #7967 item 2: retiring a code ghost on a git-canonical source (`sources.config.canonical = "git"`).
+ *
+ * A JSON file is committed and indexed as a code page, then removed from the worktree without a commit, so HEAD still
+ * holds it. The ghost repair's soft delete must go through the door at the recorded file, not at `<slug>.md`: the
+ * request commits, its Git effect settles (never parks), and HEAD drops the file in the same door commit, so Git and the
+ * database agree. Before the fix the door committed a removal of `<slug>.md` (a path Git never held), HEAD kept the
+ * recorded file and the worktree was left with an uncommitted deletion. Runs on PGLite and, with DATABASE_URL, Postgres.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { importCodeFile } from '../src/core/import-file.ts';
+import { slugifyCodePath } from '../src/core/sync.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+const CODE_PATH = 'projects/example/decisions.active.json';
+const CODE_SLUG = slugifyCodePath(CODE_PATH);
+const JSON_BYTES = '{"decision":"keep"}\n';
+const repair = async (engine: BrainEngine, opts: { apply?: boolean; expect?: string } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))
+ .run('ghost-pages', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', expect: opts.expect });
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'projects/example'), { recursive: true });
+ writeFileSync(join(root, CODE_PATH), JSON_BYTES);
+ durableGitRepo(root, [CODE_PATH]);
+};
+
+for (const backend of testBackends()) describe(`[${backend}] #7967 code ghost on a git-canonical source`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test('the retirement commits the recorded file\'s removal through the door and its Git effect settles', () => managedBrain(async ({ engine, root }) => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await importCodeFile(engine, CODE_PATH, JSON_BYTES, { noEmbed: true, sourceId: 'default' });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);
+ unlinkSync(join(root, CODE_PATH));
+ expect(git(root, 'ls-tree', '--name-only', '-r', 'HEAD').trim()).toBe(CODE_PATH);
+
+ const preview = await repair(engine);
+ expect(preview.sample).toEqual([`default:${CODE_SLUG}`]);
+ const applied = await repair(engine, { apply: true, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ applied: 1, failed: [], outcomes: { soft_deleted: 1 } });
+ await settleManagedGitEffects(engine);
+
+ const requests = await engine.executeRaw<{ state: string }>(
+ "SELECT state FROM persistence_requests WHERE source_id='default' AND intent->>'kind'='managed_maintenance_retire_ghost_page'");
+ expect(requests).toEqual([{ state: 'committed' }]);
+ const effects = await engine.executeRaw<{ state: string; path: string }>(
+ "SELECT state, data->>'relative_path' AS path FROM persistence_effects WHERE source_id='default' AND kind='git'");
+ expect(effects).toEqual([{ state: 'committed', path: CODE_PATH }]);
+ const [page] = await engine.executeRaw<{ live: boolean }>("SELECT deleted_at IS NULL AS live FROM pages WHERE source_id='default' AND slug=$1", [CODE_SLUG]);
+ expect(page).toEqual({ live: false });
+ expect(git(root, 'ls-tree', '--name-only', '-r', 'HEAD').trim()).toBe('');
+ expect(git(root, 'status', '--porcelain').trim()).toBe('');
+ expect(existsSync(join(root, `${CODE_SLUG}.md`))).toBe(false);
+ }, { databaseUrl, setup }), 120_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 8844966e9f..41010b473e 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -129,6 +129,7 @@ test/g4-forget-fence-edit.test.ts
test/gated-hold-strict-page-gst2535.test.ts
test/get-chunks-paging.test.ts
test/git-canonical-conversion-evidence-d4.test.ts
+test/ghost-pages-git-canonical-7967.test.ts
test/git-canonical-conversion-g8a.test.ts
test/git-canonical-conversion-live-writer.test.ts
test/git-canonical-conversion-no-checkout-7885.test.ts
diff --git a/test/protocol-guard-refusal-7777.test.ts b/test/protocol-guard-refusal-7777.test.ts
new file mode 100644
index 0000000000..87fc0dc588
--- /dev/null
+++ b/test/protocol-guard-refusal-7777.test.ts
@@ -0,0 +1,235 @@
+/**
+ * #7777: the persistence protocol guards (shared-skills/persistence-schema.ts) raise SQLSTATE 42501 with a fixed
+ * `<code>: <diagnostic>` message. 42501 is also ordinary permission denial, so `databaseRefusal` left them unclassified
+ * and a refusal during publication was stored as an unexpected owner exception (`storage_error`) whose hint says its
+ * cause is unknown. Contract: a 42501 is typed only when the innermost PL/pgSQL frame is a known protocol guard and the
+ * message is one of that guard's own diagnostics, verbatim; the receipt, `writeResponse` and writer status then carry
+ * the guard's remedy. Anything else at 42501 stays unclassified.
+ * Runs on PGLite, and on an isolated Postgres database through test/e2e/protocol-guard-refusal-7777-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite, receiptFor } from '../src/core/persistence/journal.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { databaseRefusal } from '../src/core/persistence/publication-failure.ts';
+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';
+import { writeResponse } from '../src/core/persistence/service.ts';
+import { DATABASE_REFUSAL_HINT } from '../src/core/persistence/connector-errors.ts';
+import {
+ EFFECT_PROTOCOL_GUARD_SQL, PROTOCOL_ACTIVATION_GUARD_SQL, REQUEST_PROTOCOL_GUARD_SQL, SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS,
+} from '../src/core/shared-skills/persistence-schema.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const sourceId = 'source-a';
+const hostId = randomUUID();
+const ROLLBACK = 'protocol-probe-rollback';
+const NO_PROTOCOL = "SELECT set_config('gbrain.persistence_protocol','',true)";
+const QUIESCED = "SELECT set_config('gbrain.persistence_protocol','2',true),set_config('gbrain.writer_quiesced','true',true)";
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const engine of engines) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ }
+}, 180_000);
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+});
+
+/** Replaces the singleton (the activation guard forbids lowering the floor by UPDATE), keeping its other columns. */
+async function singleton(engine: BrainEngine, enabled: boolean, floor: 1 | 2) {
+ await engine.executeRaw(`WITH old AS (DELETE FROM persistence_brain WHERE singleton = 1 RETURNING *)
+ INSERT INTO persistence_brain SELECT (jsonb_populate_record(NULL::persistence_brain, to_jsonb(old)
+ || jsonb_build_object('enabled', $1::boolean, 'writer_protocol_floor', $2::int, 'skill_bundles_enabled', false))).* FROM old`, [enabled, floor]);
+}
+
+type Statement = string | [string, unknown[]];
+/** Runs the statements in a transaction that always rolls back and returns what it threw. */
+async function refusal(engine: BrainEngine, statements: Statement[]): Promise<unknown> {
+ try {
+ await engine.transaction(async tx => {
+ for (const statement of statements) await (typeof statement === 'string' ? tx.executeRaw(statement) : tx.executeRaw(...statement));
+ throw new Error(ROLLBACK);
+ });
+ } catch (error) { return error; }
+ return null;
+}
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, config: { engine: engine.kind }, sourceId, remote: false,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } });
+const input = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: {} });
+async function claimed(engine: BrainEngine, slug: string) {
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);
+ const authority = await submissionAuthority(ctx(engine), 'put_page', sourceId, source!.incarnation, slug);
+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId, sourceIncarnation: source!.incarnation, slug,
+ pageId: null, requestId: randomUUID(), callerIntent: { content: slug }, intent: { content: slug }, authority });
+ return (await claimNextWrite(engine, hostId))!;
+}
+function refusedResponse(row: Parameters<typeof writeResponse>[0]): Record<string, unknown> {
+ try { writeResponse(row); } catch (error) { return error as Record<string, unknown>; }
+ throw new Error('expected writeResponse to refuse');
+}
+
+for (const backend of backends) describe(`${backend}: protocol guard refusals during publication (#7777)`, () => {
+ const engine = () => engines.find(e => e.kind === backend)!;
+
+ test('a writer without protocol 2 on a floor-2 brain fails writer_upgrade_required with the upgrade remedy', async () => {
+ const db = engine();
+ await singleton(db, true, 2);
+ try {
+ const slug = `notes/protocol-floor-${backend}`;
+ const row = await claimed(db, slug);
+ const done = await publishMutation(db, row, { observedRevision: null, apply: async tx => {
+ await tx.putPage(slug, input('must roll back'), { sourceId });
+ // An older gbrain declares no protocol: the request guard calls gbrain_require_persistence_protocol, which raises.
+ await tx.executeRaw(NO_PROTOCOL);
+ await tx.executeRaw('UPDATE persistence_requests SET updated_at=now() WHERE id=$1::uuid', [row.id]);
+ return { status: 'created' };
+ } }, hostId);
+
+ expect(done.state).toBe('failed');
+ expect(done.error_code).toBe('writer_upgrade_required');
+ expect(done.error_message).toBe('The persistence protocol guard (gbrain_require_persistence_protocol) refused this write: this mutation requires persistence protocol 2. Nothing was committed.');
+ expect(done.error_detail).toMatchObject({ origin: 'database_guard', sqlstate: '42501', raiser: 'gbrain_require_persistence_protocol', stage: 'publication' });
+ expect(await db.readPageSnapshot(slug, { sourceId })).toBeNull();
+ expect((receiptFor(done) as Record<string, unknown>).write_error_detail)
+ .toEqual({ origin: 'database_guard', sqlstate: '42501', raiser: 'gbrain_require_persistence_protocol', stage: 'publication' });
+
+ const refused = refusedResponse(done);
+ expect(refused).toMatchObject({ code: 'writer_upgrade_required', detail: 'database_guard', docs: 'docs/guides/write-refusals.md#protocol-guard' });
+ expect(refused.suggestion).toContain('does not declare the persistence protocol this brain requires');
+ expect(refused.suggestion).toContain('Never lower the protocol floor');
+ const failure = (await readWriterDiagnostics(db)).recent_failures.find(f => f.request_id === done.request_id)!;
+ expect(failure.next_action).toBe(refused.suggestion as string);
+ } finally {
+ await singleton(db, false, 1);
+ }
+ });
+
+ test('writer state the role cannot read fails writer_coordinator_required (unreadable_state) with the role remedy', async () => {
+ const db = engine();
+ await singleton(db, true, 1);
+ try {
+ const slug = `notes/protocol-unreadable-${backend}`;
+ const row = await claimed(db, slug);
+ const done = await publishMutation(db, row, { observedRevision: null, apply: async tx => {
+ await tx.putPage(slug, input('must roll back'), { sourceId });
+ // The request guard reads persistence_brain as the writing role; a missing row is what row-level security shows it.
+ await tx.executeRaw('DELETE FROM persistence_brain WHERE singleton=1');
+ await tx.executeRaw('UPDATE persistence_requests SET updated_at=now() WHERE id=$1::uuid', [row.id]);
+ return { status: 'created' };
+ } }, hostId);
+
+ expect(done.state).toBe('failed');
+ expect(done.error_code).toBe('writer_coordinator_required');
+ expect(done.error_detail).toMatchObject({ origin: 'database_guard', sqlstate: '42501', raiser: 'gbrain_guard_request_protocol',
+ branch: 'unreadable_state', relationship: 'unreadable_state', stage: 'publication' });
+ expect(await db.readPageSnapshot(slug, { sourceId })).toBeNull();
+ expect(await db.executeRaw('SELECT count(*)::int AS n FROM persistence_brain')).toEqual([{ n: 1 }]);
+
+ const refused = refusedResponse(done);
+ expect(refused).toMatchObject({ code: 'writer_coordinator_required', detail: 'database_guard' });
+ expect(refused.suggestion).not.toBe(DATABASE_REFUSAL_HINT);
+ expect(refused).toMatchObject({ docs: 'docs/guides/write-refusals.md#protocol-guard' });
+ expect(refused.suggestion).toContain('cannot fully read the writer state the guard checks');
+ expect(done.error_detail).toMatchObject({ state: 'persistence_brain' });
+ const failure = (await readWriterDiagnostics(db)).recent_failures.find(f => f.request_id === done.request_id)!;
+ expect(failure.next_action).toBe(refused.suggestion as string);
+ } finally {
+ await singleton(db, false, 1);
+ }
+ });
+
+ test('real guard raises outside publication map to their own typed codes', async () => {
+ const db = engine();
+ const [request] = await db.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,
+ source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation)
+ SELECT 'application','protocol-7777',gen_random_uuid(),'put_page',id,incarnation,'notes/protocol-7777','digest','{}'::jsonb,0,0
+ FROM sources WHERE id=$1 RETURNING id::text AS id`, [sourceId]);
+ const on = (sql: string): Statement => [sql, [request!.id]];
+ const cases: Array<{ statements: Statement[]; code: string; raiser: string; unreadable?: boolean }> = [
+ { statements: [NO_PROTOCOL, on("UPDATE persistence_requests SET target_kind='skill_bundle' WHERE id=$1::uuid")],
+ code: 'writer_upgrade_required', raiser: 'gbrain_require_persistence_protocol' },
+ { statements: [QUIESCED, on("UPDATE persistence_requests SET target_kind='skill_bundle' WHERE id=$1::uuid")],
+ code: 'unsupported_mutation_protocol', raiser: 'gbrain_guard_request_protocol' },
+ { statements: ['DELETE FROM persistence_brain WHERE singleton=1', on('UPDATE persistence_requests SET updated_at=now() WHERE id=$1::uuid')],
+ code: 'writer_coordinator_required', raiser: 'gbrain_guard_request_protocol', unreadable: true },
+ { statements: ['DELETE FROM persistence_brain WHERE singleton=1', on("INSERT INTO persistence_effects(request_id,kind,data) VALUES($1::uuid,'embedding','{}'::jsonb)")],
+ code: 'writer_coordinator_required', raiser: 'gbrain_guard_effect_protocol', unreadable: true },
+ { statements: [QUIESCED, 'UPDATE persistence_brain SET writer_protocol_floor=2 WHERE singleton=1'],
+ code: 'writer_not_quiesced', raiser: 'gbrain_guard_protocol_activation' },
+ ];
+ try {
+ for (const probe of cases) {
+ const error = await refusal(db, probe.statements);
+ expect((error as { code?: unknown }).code, probe.raiser).toBe('42501');
+ expect(databaseRefusal(error), probe.raiser).toEqual({ code: probe.code,
+ message: expect.stringMatching(new RegExp(`^The persistence protocol guard \\(${probe.raiser}\\) refused this write: .+\\. Nothing was committed\\.$`)),
+ detail: { origin: 'database_guard', sqlstate: '42501', raiser: probe.raiser,
+ ...(probe.unreadable ? { branch: 'unreadable_state', relationship: 'unreadable_state', state: 'persistence_brain' } : {}) } });
+ }
+ await singleton(db, false, 2);
+ const lowered = await refusal(db, ['UPDATE persistence_brain SET writer_protocol_floor=1 WHERE singleton=1']);
+ expect(databaseRefusal(lowered)).toMatchObject({ code: 'writer_upgrade_required', detail: { raiser: 'gbrain_guard_protocol_activation' } });
+ } finally {
+ await singleton(db, false, 1);
+ await db.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid', [request!.id]);
+ }
+ });
+});
+
+const GUARD_SQL = [REQUEST_PROTOCOL_GUARD_SQL, EFFECT_PROTOCOL_GUARD_SQL, PROTOCOL_ACTIVATION_GUARD_SQL, ...SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS];
+/** Every 42501 diagnostic the guard functions raise, paired with the function that raises it. */
+const DIAGNOSTICS: Array<[string, string]> = [...new Set(GUARD_SQL.flatMap(sql => {
+ const raiser = /^CREATE OR REPLACE FUNCTION ([a-z_]+)\(/.exec(sql)?.[1];
+ return raiser ? [...sql.matchAll(/RAISE EXCEPTION '([^']+)' USING ERRCODE='42501'/g)].map(m => `${raiser}\t${m[1]}`) : [];
+}))].map(entry => entry.split('\t') as [string, string]);
+const raised = (message: string, where: string, code = '42501') => Object.assign(new Error(message), { code, where, routine: 'exec_stmt_raise' });
+const frame = (fn: string) => `PL/pgSQL function ${fn}() line 3 at RAISE`;
+
+describe('protocol guard classification is closed (#7777)', () => {
+ test('every 42501 diagnostic a protocol guard raises is typed by its own code', () => {
+ expect(new Set(DIAGNOSTICS.map(([raiser]) => raiser))).toEqual(new Set(['gbrain_guard_request_protocol', 'gbrain_guard_effect_protocol',
+ 'gbrain_guard_protocol_activation', 'gbrain_require_persistence_protocol', 'gbrain_guard_skill_publication']));
+ expect(DIAGNOSTICS.length).toBe(15);
+ for (const [raiser, message] of DIAGNOSTICS) {
+ const failure = databaseRefusal(raised(message, frame(raiser)));
+ expect(failure?.code, message).toBe(message.slice(0, message.indexOf(':')));
+ expect(failure?.detail, message).toMatchObject({ origin: 'database_guard', sqlstate: '42501', raiser });
+ }
+ });
+
+ test('ordinary permission denial, unknown raisers, mismatched pairs and altered text stay unclassified', () => {
+ const unreadable = 'writer_coordinator_required: writer state is unreadable to this database role';
+ for (const error of [
+ Object.assign(new Error('permission denied for table pages'), { code: '42501' }),
+ raised('permission denied for table pages', ''),
+ raised(unreadable, ''),
+ raised(unreadable, frame('operator_hook')),
+ raised(unreadable, `${frame('operator_hook')}\nSQL statement "SELECT operator_hook()"\n${frame('gbrain_guard_request_protocol')}`),
+ raised(unreadable, frame('gbrain_require_persistence_protocol')),
+ raised(`${unreadable} for alice-example`, frame('gbrain_guard_request_protocol')),
+ raised('writer_upgrade_required: acme-example', frame('gbrain_guard_request_protocol')),
+ raised(unreadable, frame('constructor')),
+ ]) expect(databaseRefusal(error)).toBeNull();
+ expect(databaseRefusal(raised(unreadable, frame('gbrain_guard_request_protocol'), '23505'))).toBeNull();
+ });
+});
diff --git a/test/provenance-drift-7891.test.ts b/test/provenance-drift-7891.test.ts
index 51b8cc616b..39d0f49c52 100644
--- a/test/provenance-drift-7891.test.ts
+++ b/test/provenance-drift-7891.test.ts
@@ -39,6 +39,7 @@ import { requirePostgresTestDatabase, testBackends } from './helpers/test-backen
import { managedBrain, settleManagedGitEffects, type ManagedBrain } from './helpers/managed-brain.ts';
import { operationsByName } from '../src/core/operations.ts';
import { withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
const STORED = { source_kind: 'webhook', ingested_via: 'webhook', ingested_at: '2026-01-02T03:04:05.000Z' };
const stampsOf = (fm: Record<string, unknown>) => ({ source_kind: fm.source_kind, ingested_via: fm.ingested_via, ingested_at: fm.ingested_at });
@@ -239,6 +240,36 @@ for (const kind of testBackends()) {
}
}, 120_000);
+ test.skipIf(!repo)('#7960: a database commit that fails after the page file was committed puts the file and HEAD back; both sides stay unchanged', async () => {
+ const slug = 'inbox/commit-fails';
+ const rel = `${slug}.md`;
+ await seed(slug, STORED);
+ await rewrite(slug, {}, 'oauth_client');
+ durableGitRepo(brainDir, [rel]);
+ const before = { file: fs.readFileSync(fileOf(slug), 'utf8'), head: git(brainDir, 'rev-parse', 'HEAD').trim(), tier: await tierOf(slug), revision: (await page(slug)).revision };
+ const dry = await run(false);
+ expect(dry.affected).toBe(1);
+ const outer = engine;
+ const transaction = Object.getPrototypeOf(outer).transaction as BrainEngine['transaction'];
+ let forced = false;
+ outer.transaction = async function (this: BrainEngine, fn: (tx: BrainEngine) => Promise<unknown>, opts?: Parameters<BrainEngine['transaction']>[1]) {
+ if (this !== outer) return transaction.call(this, fn, opts);
+ return transaction.call(outer, async tx => {
+ const result = await fn(tx);
+ if (!forced && fs.readFileSync(fileOf(slug), 'utf8') !== before.file) { forced = true; throw new Error('forced database commit failure'); }
+ return result;
+ }, opts);
+ } as BrainEngine['transaction'];
+ try {
+ await run(true, { expect: dry.preview_hash }).catch(() => undefined);
+ } finally { delete (outer as { transaction?: unknown }).transaction; }
+ expect(forced).toBe(true);
+ expect({ file: fs.readFileSync(fileOf(slug), 'utf8'), headFile: git(brainDir, 'show', `HEAD:${rel}`), status: git(brainDir, 'status', '--porcelain').trim(),
+ tier: await tierOf(slug), revision: (await page(slug)).revision, proposals: await proposals(slug) })
+ .toEqual({ file: before.file, headFile: before.file, status: '', tier: before.tier, revision: before.revision, proposals: [] });
+ expect(git(brainDir, 'rev-list', '--count', `${before.head}..HEAD`).trim()).toBe('2');
+ }, 120_000);
+
test('#7918: a classified page whose file would re-read higher gets its stored tier as the marker; the row keeps its tier', async () => {
const slug = 'inbox/derived-unmarked';
await seed(slug, {}, 'agent_written');
diff --git a/test/repair-take-supersession.test.ts b/test/repair-take-supersession.test.ts
index 7b77d731b5..70beb1e60e 100644
--- a/test/repair-take-supersession.test.ts
+++ b/test/repair-take-supersession.test.ts
@@ -215,4 +215,17 @@ for (const backend of testBackends()) {
});
} finally { rmSync(home, { recursive: true, force: true }); }
}, 120_000);
+
+ test(`${backend}: #8020: a page that quotes the takes marker in code is repaired, not skipped as unparsed`, async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const quoted = page('Quoted', CHAIN).replace('Prose.', 'Writers quote the opener as `<!--- gbrain:takes:begin -->` when they explain the format.');
+ await submit(ctx, 'put_page', { slug: 'notes/quoted', content: quoted });
+ expect(parseTakesFence((await engine.readPageSnapshot('notes/quoted', { sourceId: 'default' }))!.page.compiled_truth).takes).toHaveLength(4);
+ const preview = await repair(engine, false);
+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1, residuals: { links: 2, unparsed_pages: 0 } });
+ expect(await repair(engine, true)).toMatchObject({ applied: 1, outcomes: { repaired: 1 } });
+ expect((await takeRows(engine, 'default', 'notes/quoted')).map(r => r.superseded_by)).toEqual([2, 3, null, null]);
+ expect((await engine.readPageSnapshot('notes/quoted', { sourceId: 'default' }))!.page.compiled_truth).toContain('`<!--- gbrain:takes:begin -->`');
+ }, { databaseUrl });
+ }, 120_000);
}
diff --git a/test/secret-scan-redaction-marker-7997.test.ts b/test/secret-scan-redaction-marker-7997.test.ts
index 969e15804e..79b73172a5 100644
--- a/test/secret-scan-redaction-marker-7997.test.ts
+++ b/test/secret-scan-redaction-marker-7997.test.ts
@@ -28,6 +28,8 @@ const MARKERS: Array<[string, string]> = [
['a marker pair joined by a colon', 'login <REDACTED:user-pattern>:<REDACTED:user-pattern>'],
['a marker pair joined by a slash', 'login <REDACTED:user-pattern> / <REDACTED:labeled_credential>'],
['a marker ending a sentence', 'login: <REDACTED:labeled_credential>.'],
+ ['a marker ending a clause before more prose', 'login: <REDACTED:labeled_credential>, then the deploy notes'],
+ ['a parenthesized marker ending a sentence', '(credentials <REDACTED:user-pattern>).'],
];
const BESIDE: Array<[string, string]> = [
@@ -43,6 +45,9 @@ const GLUED: Array<[string, string]> = [
['a password glued onto a marker user', `login <REDACTED:user-pattern>${PW}`],
['a password glued onto a bold marker', `login: **<REDACTED:secret>**${PW}`],
['a password glued onto a marker after a user name', `creds alice<REDACTED:x>${PW}`],
+ ['#8034: a password glued onto a marker by a comma', `login: <REDACTED:user-pattern>,${PW}`],
+ ['#8034: a password glued onto a marker by a period', `creds <REDACTED:x>.${PW}`],
+ ['#8034: a password glued onto a bold marker by a closing paren', `login: **<REDACTED:secret>**)${PW}`],
];
describe('#7997: importer redaction markers and labeled_credential', () => {
@@ -89,5 +94,7 @@ describe('#7997: audit-secrets on a redacted corpus', () => {
expect(await auditTranscriptSecrets(engine)).toMatchObject({ pages_scanned: 1, pages_affected: 0, hits_total: 0 });
await conversation('conversations/sessions/2026-10-30-codex-bbbbbbbbbbbb', `intro\n${BESIDE[0]![1]}`);
expect(await auditTranscriptSecrets(engine)).toMatchObject({ pages_scanned: 2, pages_affected: 1, hits_total: 1, by_pattern: { labeled_credential: 1 } });
+ await conversation('conversations/sessions/2026-10-30-codex-cccccccccccc', `intro\nlogin: <REDACTED:user-pattern>,${PW}`);
+ expect(await auditTranscriptSecrets(engine)).toMatchObject({ pages_scanned: 3, pages_affected: 2, hits_total: 2, by_pattern: { labeled_credential: 2 } });
});
});
diff --git a/test/unreadable-state-detail-7780.test.ts b/test/unreadable-state-detail-7780.test.ts
new file mode 100644
index 0000000000..e6c622dff2
--- /dev/null
+++ b/test/unreadable-state-detail-7780.test.ts
@@ -0,0 +1,151 @@
+/**
+ * #7780: one `unreadable_state` refusal covers four raises: the managed-writer guard's hidden or missing
+ * `persistence_brain` or `git_canonical_brain` singleton, a source or page row-level security hides, and the git-canonical
+ * recount, which refuses whenever row-level security applies to `sources`, even under a policy that shows every row.
+ * The text claimed "row-level security hides it" for all of them, and the detail dropped the `state` each raise names, so
+ * an operator could not tell which table to fix. Contract: the text holds for every raise, the owner-only detail keeps
+ * `state` (never on the public receipt), and an unreadable_state receipt gets the role remedy, not the version-mismatch one.
+ * Runs on PGLite, and on an isolated Postgres database through test/e2e/unreadable-state-detail-7780-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite, receiptFor } from '../src/core/persistence/journal.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { databaseRefusal, publicFailureDetail } from '../src/core/persistence/publication-failure.ts';
+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';
+import { writeResponse } from '../src/core/persistence/service.ts';
+import { DATABASE_REFUSAL_HINT } from '../src/core/persistence/connector-errors.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const sourceId = 'source-a';
+const hostId = randomUUID();
+const ROLLBACK = 'unreadable-probe-rollback';
+const UNREADABLE = 'writer_coordinator_required: writer state is unreadable to this database role';
+const TEXT = 'writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)';
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const engine of engines) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ }
+}, 180_000);
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+});
+
+async function refusal(engine: BrainEngine, statements: string[]): Promise<unknown> {
+ try {
+ await engine.transaction(async tx => {
+ for (const statement of statements) await tx.executeRaw(statement);
+ throw new Error(ROLLBACK);
+ });
+ } catch (error) { return error; }
+ return null;
+}
+async function managed<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); }
+}
+const newPage = `INSERT INTO pages(source_id,slug,type,title,compiled_truth) VALUES('${sourceId}','notes/unreadable-probe','note','Probe','body')`;
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, config: { engine: engine.kind }, sourceId, remote: false,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } });
+const input = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: {} });
+
+for (const backend of backends) describe(`${backend}: unreadable_state names its table (#7780)`, () => {
+ const engine = () => engines.find(e => e.kind === backend)!;
+
+ test('each real unreadable_state raise keeps its state owner-side under a text true for all of them', async () => {
+ const db = engine();
+ const brain = databaseRefusal(await refusal(db, ['DELETE FROM persistence_brain WHERE singleton=1', newPage]))!;
+ expect(brain).toEqual({ code: 'writer_coordinator_required',
+ message: `The managed-writer database guard refused an INSERT on pages: ${TEXT}. Nothing was committed.`,
+ detail: { origin: 'database_guard', sqlstate: 'P0001', raiser: 'gbrain_require_managed_writer', table: 'pages', op: 'INSERT',
+ branch: 'unreadable_state', relationship: 'unreadable_state', state: 'persistence_brain' } });
+ expect(publicFailureDetail(brain.detail)).not.toHaveProperty('state');
+
+ const git = await managed(db, () => refusal(db, [
+ `SELECT set_config('gbrain.write_sources','["${sourceId}"]',true),set_config('gbrain.git_protocol','',true)`,
+ 'DELETE FROM git_canonical_brain WHERE singleton=1', newPage]));
+ expect(databaseRefusal(git)).toMatchObject({ code: 'writer_coordinator_required',
+ detail: { sqlstate: 'P0001', relationship: 'unreadable_state', state: 'git_canonical_brain' } });
+
+ const [request] = await db.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,
+ source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation)
+ SELECT 'application','unreadable-7780',gen_random_uuid(),'put_page',id,incarnation,'notes/unreadable-7780','digest','{}'::jsonb,0,0
+ FROM sources WHERE id=$1 RETURNING id::text AS id`, [sourceId]);
+ try {
+ const floor = databaseRefusal(await refusal(db, ['DELETE FROM persistence_brain WHERE singleton=1',
+ `UPDATE persistence_requests SET updated_at=now() WHERE id='${request!.id}'::uuid`]));
+ expect(floor).toMatchObject({ code: 'writer_coordinator_required',
+ detail: { sqlstate: '42501', raiser: 'gbrain_guard_request_protocol', relationship: 'unreadable_state', state: 'persistence_brain' } });
+ } finally {
+ await db.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid', [request!.id]);
+ }
+ });
+
+ test('an unreadable_state publication receipt carries the role remedy, and its state stays owner-only', async () => {
+ const db = engine();
+ await managed(db, async () => {
+ const slug = `notes/unreadable-publication-${backend}`;
+ const [source] = await db.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);
+ const authority = await submissionAuthority(ctx(db), 'put_page', sourceId, source!.incarnation, slug);
+ await admitWrite(db, { principal: authority.principal, operation: 'put_page', sourceId, sourceIncarnation: source!.incarnation, slug,
+ pageId: null, requestId: randomUUID(), callerIntent: { content: slug }, intent: { content: slug }, authority });
+ const row = (await claimNextWrite(db, hostId))!;
+ const done = await publishMutation(db, row, { observedRevision: null, apply: async tx => {
+ await tx.putPage(slug, input('must roll back'), { sourceId });
+ // The managed-writer guard reads persistence_brain as the writing role; a missing row is what row-level security shows it.
+ await tx.executeRaw('DELETE FROM persistence_brain WHERE singleton=1');
+ await tx.putPage(`${slug}-second`, input('refused'), { sourceId });
+ return { status: 'created' };
+ } }, hostId);
+
+ expect(done.state).toBe('failed');
+ expect(done.error_code).toBe('writer_coordinator_required');
+ expect(done.error_detail).toMatchObject({ origin: 'database_guard', sqlstate: 'P0001', relationship: 'unreadable_state', state: 'persistence_brain' });
+ expect(await db.readPageSnapshot(slug, { sourceId })).toBeNull();
+ expect((receiptFor(done) as Record<string, unknown>).write_error_detail).not.toHaveProperty('state');
+
+ let refused: Record<string, unknown> = {};
+ try { writeResponse(done); } catch (error) { refused = error as Record<string, unknown>; }
+ expect(refused).toMatchObject({ code: 'writer_coordinator_required', detail: 'database_guard',
+ docs: 'docs/guides/write-refusals.md#writer-coordinator-required' });
+ expect(refused.suggestion).not.toBe(DATABASE_REFUSAL_HINT);
+ expect(refused.suggestion).toContain('Upgrading gbrain does not fix this');
+ expect(refused.suggestion).toContain('recent_failures[].error_detail.state names the table');
+ expect(refused.suggestion).toContain('Ask the user before changing the database role');
+ const failure = (await readWriterDiagnostics(db)).recent_failures.find(f => f.request_id === done.request_id)!;
+ expect(failure.error_detail).toMatchObject({ state: 'persistence_brain' });
+ expect(failure.next_action).toBe(refused.suggestion as string);
+ });
+ });
+});
+
+describe('unreadable_state state is a closed set (#7780)', () => {
+ const raised = (state: unknown) => Object.assign(new Error(UNREADABLE), { code: 'P0001', table: 'sources',
+ constraint: 'managed_writer_guard:unreadable_state', where: 'PL/pgSQL function gbrain_count_git_canonical_sources() line 5 at RAISE',
+ detail: JSON.stringify({ op: 'UPDATE', relationship: 'unreadable_state', state }) });
+
+ test('the recount refusal names sources; a state outside the four guard tables is dropped', () => {
+ expect(databaseRefusal(raised('sources'))?.detail).toMatchObject({ relationship: 'unreadable_state', state: 'sources' });
+ for (const state of ['alice-example', 'pages; DROP', 42, null]) expect(databaseRefusal(raised(state))?.detail).not.toHaveProperty('state');
+ });
+});