Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1a (wip): derived census guard, docs, behavior notice

garrytanc89338baafb6
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 6d2be191de..adad8a960c 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -24,7 +24,7 @@ link it here rather than raising the cap.
| Subsystem | Entry range / scope |
|---|---|
| [Page identity and writer administration](key-files/page-identity-and-administration.md) | Opaque result IDs, current grants, state-bound ownership changes |
-| [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, retained originals, derived atom state, sync discovery and the origin rule (`sync-origin.ts`, `file-claims.ts`) |
+| [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, retained originals, derived generations, sync discovery and the origin rule (`sync-origin.ts`, `file-claims.ts`) |
| [Company-brain ingestion](key-files/company-brain.md) | Inspection, admission, receipts, derived relationships and schema; [operator guide](../guides/company-brain-ingestion.md) |
| [Agent operator contract](key-files/agent-contract.md) | `agent-output.ts`, error registry + docs, notice ledger, `isCallable`, `--json` guard, contract scanner |
| [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` |
diff --git a/docs/architecture/derived-census.tsv b/docs/architecture/derived-census.tsv
new file mode 100644
index 0000000000..1dd66d256a
--- /dev/null
+++ b/docs/architecture/derived-census.tsv
@@ -0,0 +1,27 @@
+# Derived-retirement census (GBRA-161 PR 1a). Enforced by scripts/check-derived-census.ts (bun run check:derived-census, in verify).
+# Rows: path<TAB>ceiling<TAB>class<TAB>note. Ceilings only shrink (--prune lowers them); a new soft-delete site needs a reviewed row.
+# class: primitive | engine | canonical | pending:inventory (a derived or mixed writer each later GBRA-161 PR reviews onto the generation primitive).
+src/commands/sync/deletes.ts 1 canonical sync deletes a page whose canonical file was removed
+src/core/chronicle/publish.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/company-brain/profile.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/cycle/phantom-redirect.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/engine-sql/pages.ts 5 engine the shared soft-delete SQL both engines delegate to
+src/core/engine.ts 3 engine BrainEngine interface declarations of softDeletePage/softDeletePages
+src/core/facts/derivation-inputs.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/generations/adapters/atoms.ts 1 primitive the unmanaged atom adapter retires through retireDerivedPagesInTransaction inside the generation activation (publish.ts)
+src/core/minions/handlers/ingest-capture.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/ops/extraction.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/page-body/segment-rewrite.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/persistence/connector-sync.ts 1 canonical connector sync applies an upstream deletion of a connected item
+src/core/persistence/derived-retirement-hold.ts 4 primitive retireDerivedPagesInTransaction: versions, soft-deletes and stamps retired_by; the helper every generation adapter retires through
+src/core/persistence/page-prepare.ts 2 canonical coordinated delete_page preparation (an operator or agent deletion)
+src/core/persistence/sync-image.ts 1 canonical sync image publication applies a committed file deletion
+src/core/persistence/sync-prepare.ts 1 canonical managed sync prepares the soft delete of a page whose file was removed
+src/core/persistence/twin-merge.ts 1 canonical origin-twin merge retires the losing duplicate of one canonical file
+src/core/pglite-engine.ts 4 engine PGLite engine soft-delete methods
+src/core/postgres-engine.ts 4 engine Postgres engine soft-delete methods
+src/core/repair/ghost-pages.ts 1 canonical repair ghost-pages soft-deletes a live page whose canonical file is gone, after operator agreement
+src/core/repair/rename-identity.ts 2 canonical repair rename-identity closes the old page of a rename pair, after operator agreement
+src/core/repair/stale-atoms.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/schema-pack/page-to-alias.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
+src/core/schema-pack/page-to-link.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR
diff --git a/docs/architecture/generations.md b/docs/architecture/generations.md
new file mode 100644
index 0000000000..8e671848c1
--- /dev/null
+++ b/docs/architecture/generations.md
@@ -0,0 +1,75 @@
+# Generations
+
+GBRA-161. A derived producer (atom extraction today; synthesis, fences and projections in later releases) replaces the
+set of items one input owns through one primitive, `publishGeneration` (`src/core/generations/publish.ts`). The
+generation ledger records which items each generation owns, so a bad result can be held before it lands and a landed
+one can be undone.
+
+## The ledger
+
+Migration v265 (a placeholder number, restamped when the change merges) adds three tables. Nothing existing changes.
+
+- `derived_generations`: one row per generation of a key (source, kind, owner key). At most one is `live` and at most
+ one is `held`; earlier live rows become `superseded` and keep their items. A row records the input pin and size it
+ was derived from, the item-set hash, the operation id an identical replay matches, and for a held row the reason, the
+ attempts and the proposal it would publish (at most 4 MiB, else no releasable copy).
+- `derived_generation_items`: each item a generation published, kept, adopted, revived or retired, with its identity
+ hash (a digest of what the page says, leaving out completion, extraction and retirement stamps) and, for an item it
+ overwrote or retired, a bounded preimage (at most the inline page size; none for a segmented page).
+- `derived_generation_valve`: retirements counted per run window, for the retirement valve.
+
+## Publishing
+
+Under the item page locks (slug order) and then the key's advisory lock, `publishGeneration`:
+
+1. replays an identical operation as `unchanged`;
+2. refuses a producer that planned against another live generation or whose input moved (`generation_fenced`);
+3. plans the result (`plan.ts`, pure): an item is the key's when the live generation recorded it, or when it carries
+ the key's origin metadata and either the result reproduces it or a retained page version the producer wrote shows it
+ unedited (legacy adoption). Any other row naming the key is protected: never retired, listed in the outcome;
+4. holds the result instead of publishing it, in this order: `segmented_unsupported` (it would rewrite or retire a
+ segmented page), `no_proof` (an empty result without an empty-source proof, `proofs.ts`), `oversize` (more puts
+ or retirements than `generations.max_items`), `shrunk` (a model-produced result keeping fewer than
+ `generations.shrink_floor` of the owned items, scaled by how much the input shrank), `valve` (the run window would
+ retire more than `generations.valve.max_per_run`, or more than 25 and over `generations.valve.max_ratio` of the
+ kind's owned items). A held result writes nothing and retires nothing; the previous generation stays live;
+5. otherwise, in one attributed transaction: writes the new and changed items, marks them complete (an atom's
+ `source_hash`), rechecks each is live at the identity just written (`generation_live_conflict` otherwise), versions,
+ soft-deletes and stamps what the new generation no longer has (`retired_by` the adapter's stamp, held from the
+ purge for `generations.restore_days`), supersedes the previous row and activates the new one.
+
+A partial result (an input cut at its cap, #6503) publishes additively: it writes its items, carries the rest of the
+live generation forward, retires nothing and completes nothing.
+
+Adapters (`contract.ts`) own one kind each: `adapters/atoms.ts` (unmanaged atoms, one key per origin page or
+transcript) in this release. Managed brains keep the coordinator path until PR 1b.
+
+## Repair
+
+`gbrain repair generations --kind <kind>` is explicit-only and preview-bound (docs/guides/repair.md#generations):
+`--mode restore` (the default) republishes the item set the selected live generation replaced, `--mode release-held`
+publishes a held result once. Doctor reports `generation_retirements` (ok, with the restorable count) and
+`generation_held` (warn).
+
+## Purge
+
+A page purge nulls the purged item's preimages and every held proposal naming it; a fact purge nulls every preimage and
+proposal carrying the claim (`ledger-scrub.ts`). Restore then refuses that item (`no_preimage`).
+
+## Census
+
+`scripts/check-derived-census.ts` counts the code that soft-deletes pages per file against
+`docs/architecture/derived-census.tsv`. A new site needs a reviewed row; ceilings only shrink. Rows classed
+`pending:inventory` are the derived writers later GBRA-161 PRs move onto the primitive.
+
+## Settings
+
+| Key | Default | Range |
+| --- | --- | --- |
+| `generations.restore_days` | 30 | 3 to 365 |
+| `generations.shrink_floor` | 0.5 | 0.05 to 1 |
+| `generations.max_items` | 64 | 8 to 1024 |
+| `generations.valve.max_per_run` | 500 | 1 to 100000 |
+| `generations.valve.max_ratio` | 0.5 | 0.01 to 1 |
+
+`gbrain config set` refuses a value out of range; a stored value out of range reads as the default.
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index c6639636db..ab4d892969 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -8,7 +8,9 @@
- `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/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. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
+- `src/core/generations/{contract,plan,publish,proofs,config,repair,ledger-scrub}.ts` + `adapters/{page,atoms,index}.ts` (GBRA-161) — the generation primitive: one ledger row per derived key generation (`derived_generations`, items and bounded preimages in `derived_generation_items`); `publishGeneration` holds a shrunk, oversize, unproven-empty, valve or segmented result and otherwise writes, completes, rechecks, retires (versioned, stamped) and activates in one transaction. `gbrain repair generations` restores or releases from previews; doctor `generation_retirements` / `generation_held`. Reference: [generations](../generations.md). Tests: `test/pathological/g1-generations.test.ts`, `test/pathological/g1-atom-generations.test.ts`.
+
+- `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 publish and complete as one generation ([generations](../generations.md)); managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
- `src/core/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. Pages under a declared `storage.db_only` dir without a local cache file publish database-only. The committed revision is returned so the migration's verify phase can tell a later rewrite from a lost write. `admitCanonicalGrandfather` splits admission from `complete()` (wait, then settle the checkpoint exactly as the serial `grandfatherCanonicalPage` does); the migration admits a 50-page window before waiting, so the pages' Git effects coalesce (#5530). The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 00ebd4406f..6f68c7ab83 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -23,7 +23,8 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.) The refusal carries an additive `withdrawn` object (`factWithdrawnRefusal` in `facts/single-prepare.ts`, from `fact_withdrawals` only: the named entity's row over `all_entities`, then the newest, omitted when the caller cannot read the forgotten rows); `withdrawalFailureDetail`/`withdrawnFromDetail` in `facts/withdrawal.ts` keep it in the failed receipt's `error_detail` for `get_write_request` and replay. Tests: `test/withdrawn-detail.test.ts`, `test/e2e/withdrawn-detail-postgres.test.ts`.
- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete, after the belief-ledger expiry of recorded sources' tombstones: each is its own transaction and item (ItemRun site `purge.recorded_tombstones`), a run-scoped failure or a systemic run stops the purge, and any other failure lists the tombstone in `blocked` with its classified code, counts it in `failed` (no `error`, so the phase warns) and keeps it out of the bulk delete (`purgeDeletedPages` `excludeIds`); a content failure counts toward the same park as the managed purge, a transient one is retried next run, and parked tombstones are skipped as `purge_parked` unless `retryParked` (the unmanaged preview excludes them too). A managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (retention is not an owner purge; see [belief ledger](belief-ledger.md)). Writer state is read once per run (`writerOnboardingPreflight`): a source whose writer is `recovery_required` submits nothing and its tombstones are listed in `blocked` as `writer_not_active` (counted in `inactive`). Revision races are deferred to the next run; a parked tombstone (`purge-parks.ts`) is skipped as `purge_parked` (counted in `parked`) unless `retryParked`, and any other failure is listed in `blocked` and sets `error`. `selectPurgeCandidates` is the one eligibility selector (preview, consent, `purge_deleted_pages` op, run); #6884: the run submits only while the writer has outstanding-request room (`readOutstandingRoom` in `journal.ts`, at `persistence.capacity.background_pause_pct` of the cap for a background run); the rest, and the rest after a `queue_capacity` refusal, is `blocked` as `write_capacity_deferred` and counted in `capacity_deferred`, never a failure or a park. `purgePhaseStatus`/`purgePhaseNote` shape the cycle purge phase (fail on `error`; warn on `writer_not_active`, parked, capacity-deferred or an unmanaged `failed` tombstone). The engine bulk delete (`engine-sql/pages.ts` `purgeDeletedPages`) also deletes, in its transaction, the purged pages' stagings (by source and slug) and the segment texts only their manifests referenced. Tests: `test/managed-writers-w3.test.ts`, `test/purge-deleted-parks.test.ts`, `test/purge-deleted-capacity-6884.test.ts`, `test/pathological/a49-unmanaged-purge-tombstones.test.ts`.
-- `src/core/persistence/derived-retirement-hold.ts` — GBRA-161: the purge hold for every derived retirement. `DERIVED_RETIRED_BY` lists the `retired_by` stamps derived writers put on the pages they retire (extract-atoms, managed-reextract, stale-atoms, life-chronicle); `derivedRetirementPurgeHold(alias)` keeps a stamped page out of every purge route (engine bulk purge and its preview, the coordinated selection and delete) until `DERIVED_RETIREMENT_HOLD_DAYS` (30) after `deleted_at` (the database clock, never the `retired_at` text); `retireDerivedPages` versions, soft-deletes and stamps a batch in one attributed transaction (unmanaged extract_atoms). `assertRetirementStampUnchanged` is the page preparer's refusal (`reserved_frontmatter_key`) of a remote write that adds or changes one of `RESERVED_RETIREMENT_KEYS`. An explicit `gbrain delete --purge` is not held.
+- `src/core/persistence/derived-retirement-hold.ts` — GBRA-161: the purge hold for every derived retirement. `DERIVED_RETIRED_BY` lists the `retired_by` stamps derived writers put on the pages they retire (extract-atoms, managed-reextract, stale-atoms, life-chronicle); `derivedRetirementPurgeHold(alias)` keeps a stamped page out of every purge route (engine bulk purge and its preview, the coordinated selection and delete) until `DERIVED_RETIREMENT_HOLD_DAYS` (30) after `deleted_at` (the database clock, never the `retired_at` text); `retireDerivedPages` versions, soft-deletes and stamps a batch in one attributed transaction (unmanaged extract_atoms). `assertRetirementStampUnchanged` is the page preparer's refusal (`reserved_frontmatter_key`) of a remote write that adds or changes one of `RESERVED_RETIREMENT_KEYS`. The hold length follows `generations.restore_days` (`RESTORE_DAYS_SQL`, read inside the purge statement; 30 by default) and `retireDerivedPagesInTransaction` is the in-transaction form generation adapters retire through. An explicit `gbrain delete --purge` is not held.
+- `src/core/generations/ledger-scrub.ts` — GBRA-161: purge reaches the generation ledger. A page purge (`page-purge.ts`) nulls the purged item's preimages in `derived_generation_items` and every held proposal in `derived_generations` naming it; a fact purge (`facts/purge.ts`) nulls every preimage, proposal and held context carrying the claim. Both are `swept` (`generation_ledger`) in the deletion inventory, so the verification probes them; `gbrain repair generations` then refuses a scrubbed item with `no_preimage`.
- `src/core/persistence/atom-retirement-hold.ts` — #7013: the one SQL rule for atoms `gbrain repair atoms-restore` restores. `atomRetirementsSql(scope)` is set-based (CTEs over `pages` joined on source and origin key, linear in the atoms in scope) and returns every non-imported atom soft-deleted with `retired_by: managed-reextract` with `origin_live` (a live page origin in its source, or a transcript), `replaced` (a live atom of the same origin carries another stripped source hash), `latest` (its hash is the hash of the origin's latest `managed-reextract` retirement) and `restorable` (all three right); `atomOriginScopeSql` narrows it to one atom's source and origin through the frontmatter GIN index for the apply recheck; `atomRetirementPurgeHold`, which keeps such an atom out of every batch purge selection (engine `purgeDeletedPages` preview and delete, the belief-ledger expiry, `selectPurgeCandidates`) for `ATOM_RESTORE_HOLD_DAYS` (30) after `deleted_at`, next to the #6729 `identityDowngradePurgeHold`. An explicit `delete --purge` is not held. Static strings only, so `engine-sql/pages.ts` imports it.
- `src/core/repair/atoms-restore.ts` — `gbrain repair atoms-restore` (#7013), explicit-only and preview-bound: lists atoms an empty managed re-extraction retired (`retired_by: managed-reextract`) that `atomRetirementsSql` (`persistence/atom-retirement-hold.ts`) marks `restorable`, each with origin, stripped source hash and `retired_at`, and residuals `restorable`, `origins`, `origin_gone`, `replaced`, `older_generation`; `--apply --expect <hash>` restores the approved set, rechecking each atom (id, incarnation, revision, origin, hash, `retired_at`, rule match) and reporting `changed_since_preview` otherwise. Managed: one `managed_maintenance_restore_reextract_atom` request per atom (`deleted_page: true`, bound to the deleted revision, request id in the outcome detail); `prepareAtomRestore` (dispatched from `prepared-maintenance.ts`) rechecks the rule under the atom and origin page locks and publishes a revision-bound `revert_version` to `version_id`, the newest live version of the atom at its source hash without `retired_by` (the one the coordinated delete archived; file written back, `allowMissingFile`); none is `no_version`, lowered to the `derive:atoms` tier of its origin with taint edges. Unmanaged: `createVersion`, `restorePage` and the two keys dropped in one `maintenanceTransaction`. Extraction state is not touched. Test: `test/pathological/h5-atoms-restore.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index e5ce5e24b2..9a5843a77c 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1484,6 +1484,50 @@ their count, origins, oldest and newest retirement and the date the first hold
ends; its fix is the read-only preview. Show the user the preview before
running the apply.
+### Generations
+
+Unmanaged atom extraction publishes each page's or transcript's atoms as one
+generation (GBRA-161, [generations](../architecture/generations.md)). A result
+that would shrink the atom set below `generations.shrink_floor`, retire items
+without proof that the input is empty, change more than `generations.max_items`
+items, trip the retirement valve or touch a segmented page is held: nothing is
+written or retired, and the previous atoms stay live. A complete result retires
+what it no longer has (versioned, stamped `retired_by: extract-atoms`, held from
+the purge for `generations.restore_days`, 30 by default). `gbrain repair
+generations` undoes or releases them. It is explicit-only and preview-bound,
+and nothing runs on upgrade.
+
+```bash
+gbrain repair generations --kind atom --since 30d --json # --mode defaults to restore
+gbrain repair generations --kind atom --mode release-held --held --json
+gbrain repair generations --kind atom --key source_slug:<slug> --source <id> --apply --expect <hash> --yes
+```
+
+`--kind` names the ledger kind (`atom` in this release); one selector bounds
+the set: `--run <id>` (one extraction run), `--since <ISO-8601|7d>` (resolved
+once to an instant the preview and apply carry), `--key <owner>`
+(`source_slug:<page>` or `source_path:<transcript>`), `--generation <id>`, or
+`--held` (with `--mode release-held`).
+
+- `--mode restore` republishes the item set the selected live generation
+ replaced, as a new generation: atoms it retired come back from their ledger
+ preimages, atoms it overwrote return to their earlier content, and atoms it
+ added are versioned and retired (`retired_by: generation-restore`). A key with
+ an atom edited since, or one whose preimage is missing (segmented, too large,
+ or purged), is refused whole and listed `refused`; the apply exits incomplete
+ and nothing of that key changes.
+- `--mode release-held` publishes a held result once: `shrunk`, `valve` and
+ `attempts_exhausted` always, `oversize` after `generations.max_items` was
+ raised. `no_proof`, `fence_absent` and `segmented_unsupported` are refused,
+ because releasing them would supply the proof they lack.
+
+The preview saves the set under its hash; `--apply --expect <hash> --yes`
+applies exactly that set and rechecks each key under its locks
+(`changed_since_preview` otherwise). Doctor `generation_held` warns while a
+held result waits, with the read-only release preview as its fix;
+`generation_retirements` reports what is restorable. Show the user the preview
+before running the apply. Managed brains keep their coordinator path for now.
+
### Extractor facts
A managed write by a gbrain older than v0.60.11.0 to a conversation page
diff --git a/package.json b/package.json
index 48604d68db..8d7f0fdfe1 100644
--- a/package.json
+++ b/package.json
@@ -163,6 +163,7 @@
"check:schema-error-predicates": "bun scripts/check-schema-error-predicates.ts",
"check:windows-hide": "bun scripts/check-windows-hide.ts",
"check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts",
+ "check:derived-census": "bun scripts/check-derived-census.ts",
"check:chunk-visibility": "bun scripts/check-chunk-visibility.ts",
"check:page-body-readers": "bun scripts/check-page-body-readers.ts",
"check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts",
diff --git a/scripts/check-derived-census.ts b/scripts/check-derived-census.ts
new file mode 100644
index 0000000000..458e18fa1b
--- /dev/null
+++ b/scripts/check-derived-census.ts
@@ -0,0 +1,91 @@
+#!/usr/bin/env bun
+/**
+ * Derived-retirement census (GBRA-161 PR 1a; docs/architecture/generations.md#census).
+ *
+ * Every derived producer is moving onto the generation primitive (src/core/generations/), the one path that retires a
+ * derived item only inside the activation of a complete successor. Until each has moved, this guard keeps the set of
+ * code that soft-deletes pages from growing unnoticed. It counts, per src file (generated files excluded):
+ *
+ * - calls to softDeletePage(, softDeletePages(, retireDerivedPages( and retireDerivedPagesInTransaction(;
+ * - SQL that sets pages.deleted_at (`UPDATE pages ... deleted_at =`).
+ *
+ * Rules (every violation is reported, then one exit):
+ * 1. growth: a file with more sites than its reviewed ceiling, or with sites and no row -> FAIL
+ * 2. stale: a row whose file is gone or now has fewer sites than its ceiling -> FAIL
+ * 3. class: a row whose class is not one of CLASSES, or a malformed row -> FAIL
+ *
+ * Baseline: docs/architecture/derived-census.tsv, rows `path<TAB>ceiling<TAB>class<TAB>note`. Ceilings only shrink.
+ * `--prune` lowers each ceiling to the current count and drops rows that reached zero; nothing ever adds rows.
+ * GBRAIN_GUARD_ROOT points the scan at a fixture tree (scripts/guard-self-test.sh).
+ */
+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const root = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
+const BASELINE = 'docs/architecture/derived-census.tsv';
+/** primitive: the generation primitive and its retirement helper; engine: the storage method itself; canonical: deletes
+ * of canonical pages a user or sync asked for; pending:inventory: a derived or mixed writer not yet reviewed onto the primitive. */
+const CLASSES = new Set(['primitive', 'engine', 'canonical', 'pending:inventory']);
+const CALL = /(?<![\w$])(?:softDeletePages?|retireDerivedPages(?:InTransaction)?)\s*(?:\?\.)?\s*\(/g;
+const SQL = /\bUPDATE\s+pages\b[^;`]{0,400}?\bdeleted_at\s*=/gi;
+
+function files(directory: string): string[] {
+ if (!existsSync(directory)) return [];
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? files(join(directory, entry.name))
+ : entry.name.endsWith('.ts') && !entry.name.endsWith('.generated.ts') ? [join(directory, entry.name)] : []);
+}
+
+const counts = new Map<string, number>();
+for (const file of files(join(root, 'src'))) {
+ const body = readFileSync(file, 'utf8');
+ const sites = [...body.matchAll(CALL)].length + [...body.matchAll(SQL)].length;
+ if (sites) counts.set(relative(root, file), sites);
+}
+
+const baselinePath = join(root, BASELINE);
+const lines = existsSync(baselinePath) ? readFileSync(baselinePath, 'utf8').split('\n') : [];
+const problems: string[] = [];
+const rows = new Map<string, { ceiling: number; cls: string; note: string; line: string }>();
+for (const line of lines) {
+ if (!line.trim() || line.startsWith('#')) continue;
+ const [path, ceiling, cls, note] = line.split('\t');
+ if (!path || !/^\d+$/.test(ceiling ?? '') || !cls || !note) { problems.push(`malformed row: ${line}`); continue; }
+ if (rows.has(path)) { problems.push(`duplicate row: ${path}`); continue; }
+ if (!CLASSES.has(cls)) problems.push(`${path}: class "${cls}" is not one of ${[...CLASSES].join(', ')}`);
+ rows.set(path, { ceiling: Number(ceiling), cls, note, line });
+}
+
+if (process.argv.includes('--prune')) {
+ const kept = lines.filter(line => {
+ if (!line.trim() || line.startsWith('#')) return true;
+ const path = line.split('\t')[0]!;
+ return (counts.get(path) ?? 0) > 0;
+ }).map(line => {
+ if (!line.trim() || line.startsWith('#')) return line;
+ const [path, ceiling, ...rest] = line.split('\t');
+ const now = counts.get(path!) ?? 0;
+ return now < Number(ceiling) ? [path, String(now), ...rest].join('\t') : line;
+ });
+ writeFileSync(baselinePath, kept.join('\n'));
+ console.log(`check-derived-census: pruned ${BASELINE}`);
+ process.exit(0);
+}
+
+for (const [path, sites] of counts) {
+ const row = rows.get(path);
+ if (!row) problems.push(`growth: ${path} has ${sites} derived-retire site(s) and no reviewed row`);
+ else if (sites > row.ceiling) problems.push(`growth: ${path} has ${sites} derived-retire site(s); reviewed ceiling ${row.ceiling}`);
+}
+for (const [path, row] of rows) {
+ const sites = counts.get(path) ?? 0;
+ if (sites < row.ceiling) problems.push(`stale: ${path} has ${sites} derived-retire site(s); its ceiling ${row.ceiling} must shrink (bun scripts/check-derived-census.ts --prune)`);
+}
+
+if (problems.length) {
+ for (const problem of problems) console.error(`FAIL: ${problem}`);
+ console.error('Why: a derived producer retires items only through the generation primitive (publishGeneration); a new soft-delete site needs a reviewed row.');
+ console.error('See: docs/architecture/generations.md#census');
+ console.error(`check-derived-census: ${problems.length} violation(s)`);
+ process.exit(1);
+}
+console.log(`check-derived-census: ok (${rows.size} reviewed rows)`);
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 783738097d..b8baae764d 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -101,3 +101,4 @@ check-recipe-pricing.ts scanner yes X1 (wave 9 lane A, D22): every model a recip
check-write-gate-regex.ts scanner yes #5575 ENG-16: write-gate detector patterns (WRITE_GATE_PATTERNS) are bounded (no * + {n,}, bound <= 200, no nested repeats, no backrefs), longest match <= MAX_MATCH_CHARS, preceded contexts $-anchored and <= MAX_PRECEDING_CHARS, non-global with lowercase anchors; GBRAIN_GUARD_ROOT reads <root>/patterns.json
check-chunk-visibility.ts scanner yes Wave B segmented storage (spec 4.2, TS AST): every FROM/JOIN content_chunks statement in src uses chunkVisibleFilter (or its generation siblings) or carries -- chunk-visibility-ok: <reason>; per-file uncovered counts in scripts/chunk-visibility-baseline.tsv only shrink; --prune lowers rows
check-file-url-pathname.sh scanner yes #6845: a file URL .pathname in test/ keeps %20 escapes; GBRAIN_GUARD_ROOT seam; skips test/fixtures/guards/
+check-derived-census.ts scanner yes GBRA-161: per-file soft-delete sites (softDeletePage(s), retireDerivedPages(InTransaction), UPDATE pages ... deleted_at =) need a reviewed row with a class in docs/architecture/derived-census.tsv; growth, stale (ceiling above count) and unknown classes fail; --prune lowers ceilings
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 1837bcd2fc..9b10122ad5 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -187,6 +187,9 @@ CHECKS=(
# Goal (a) (refactor wave 1): engine SQL only shrinks; baseline
# scripts/engine-sql-baseline.tsv.
"check:engine-sql-ratchet"
+ # GBRA-161: derived-retire writers only shrink; reviewed ceilings in
+ # docs/architecture/derived-census.tsv.
+ "check:derived-census"
# Wave B segmented storage (spec 1.5 layer 4): whole-body page readers only
# shrink; baseline scripts/page-body-readers-baseline.tsv.
"check:page-body-readers"
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9abce4a300..70e316611f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1081,6 +1081,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7263 (a background doctor refresh held a one-job worker for up to 2 h).
{ since: '0.60.348.0', text: 'The background `doctor-refresh` job now queues behind sync, the autopilot cycles, global maintenance, embed backfill and loops extract (priority 10), and measures for at most 10 minutes: past that it starts no further check, records what it finished and completes, and the rest stays unknown until the next hourly refresh. Its timeout drops from 2 hours to 15 minutes. `gbrain config set doctor.background_refresh false` stops doctor from queueing it.' },
{ since: 'TBD', text: 'Pages a derived writer retires (an atom a completed re-extraction no longer produces, a chronicle event a re-judged meeting no longer yields, an atom `gbrain repair stale-atoms` retired) now stay restorable for 30 days instead of 72 hours: the purge, automatic and `gbrain pages purge-deleted` alike, skips a page stamped `retired_by` extract-atoms, managed-reextract, stale-atoms or life-chronicle until 30 days after its deletion, and `gbrain restore <slug>` brings it back with its body. The unmanaged extract_atoms and chronicle retirements now save a page version first and stamp the page. A remote page write that adds or changes `retired_by`, `retired_at` or `retired_generation` is refused with `reserved_frontmatter_key`; carrying the stored value unchanged, or dropping the key, still writes.' },
+ { since: 'TBD', text: 'Unmanaged atom extraction now publishes each page\'s or transcript\'s atoms as one generation: the atoms, their provenance edges and the completion stamp land together or not at all (a failed write leaves no provisional atom), and the atoms a complete re-extraction no longer produces are retired in the same transaction. A re-extraction that would keep fewer than half of an origin\'s atoms (`generations.shrink_floor`), retire them all without proof the input is empty, change more than 64 atoms (`generations.max_items`) or trip the retirement valve is held instead: nothing changes, doctor `generation_held` warns, and `gbrain repair generations --kind atom --mode release-held --held` previews it. An atom from before this release is retired only when the extraction reproduces it or a retained page version the extractor wrote shows it unedited; a hand-written or hand-edited atom naming the origin stays live. `gbrain repair generations --kind atom --since 30d` previews restoring what a generation replaced. The derived purge hold now follows `generations.restore_days` (default 30).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/fixtures/guards/check-derived-census.ts/bad-class/docs/architecture/derived-census.tsv b/test/fixtures/guards/check-derived-census.ts/bad-class/docs/architecture/derived-census.tsv
new file mode 100644
index 0000000000..b0a53e31d9
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/bad-class/docs/architecture/derived-census.tsv
@@ -0,0 +1,2 @@
+# fixture census
+src/core/retire.ts 1 bogus fixture: an unknown class
diff --git a/test/fixtures/guards/check-derived-census.ts/bad-class/src/core/retire.ts b/test/fixtures/guards/check-derived-census.ts/bad-class/src/core/retire.ts
new file mode 100644
index 0000000000..8b08b7c7f9
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/bad-class/src/core/retire.ts
@@ -0,0 +1,5 @@
+type Engine = { softDeletePage: (slug: string) => Promise<void> };
+
+export async function retire(engine: Engine): Promise<void> {
+ await engine.softDeletePage('derived/example');
+}
diff --git a/test/fixtures/guards/check-derived-census.ts/bad-stale/docs/architecture/derived-census.tsv b/test/fixtures/guards/check-derived-census.ts/bad-stale/docs/architecture/derived-census.tsv
new file mode 100644
index 0000000000..50521cd237
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/bad-stale/docs/architecture/derived-census.tsv
@@ -0,0 +1,2 @@
+# fixture census
+src/core/retire.ts 2 pending:inventory fixture: a ceiling above the current count
diff --git a/test/fixtures/guards/check-derived-census.ts/bad-stale/src/core/retire.ts b/test/fixtures/guards/check-derived-census.ts/bad-stale/src/core/retire.ts
new file mode 100644
index 0000000000..8b08b7c7f9
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/bad-stale/src/core/retire.ts
@@ -0,0 +1,5 @@
+type Engine = { softDeletePage: (slug: string) => Promise<void> };
+
+export async function retire(engine: Engine): Promise<void> {
+ await engine.softDeletePage('derived/example');
+}
diff --git a/test/fixtures/guards/check-derived-census.ts/bad/docs/architecture/derived-census.tsv b/test/fixtures/guards/check-derived-census.ts/bad/docs/architecture/derived-census.tsv
new file mode 100644
index 0000000000..81b101e224
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/bad/docs/architecture/derived-census.tsv
@@ -0,0 +1 @@
+# fixture census
diff --git a/test/fixtures/guards/check-derived-census.ts/bad/src/core/retire.ts b/test/fixtures/guards/check-derived-census.ts/bad/src/core/retire.ts
new file mode 100644
index 0000000000..8b08b7c7f9
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/bad/src/core/retire.ts
@@ -0,0 +1,5 @@
+type Engine = { softDeletePage: (slug: string) => Promise<void> };
+
+export async function retire(engine: Engine): Promise<void> {
+ await engine.softDeletePage('derived/example');
+}
diff --git a/test/fixtures/guards/check-derived-census.ts/good/docs/architecture/derived-census.tsv b/test/fixtures/guards/check-derived-census.ts/good/docs/architecture/derived-census.tsv
new file mode 100644
index 0000000000..87334c639b
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/good/docs/architecture/derived-census.tsv
@@ -0,0 +1,2 @@
+# fixture census
+src/core/retire.ts 1 pending:inventory fixture: one reviewed soft-delete site
diff --git a/test/fixtures/guards/check-derived-census.ts/good/src/core/retire.ts b/test/fixtures/guards/check-derived-census.ts/good/src/core/retire.ts
new file mode 100644
index 0000000000..8b08b7c7f9
--- /dev/null
+++ b/test/fixtures/guards/check-derived-census.ts/good/src/core/retire.ts
@@ -0,0 +1,5 @@
+type Engine = { softDeletePage: (slug: string) => Promise<void> };
+
+export async function retire(engine: Engine): Promise<void> {
+ await engine.softDeletePage('derived/example');
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 3e6652e9f2..10d146e04d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -314,6 +314,8 @@ test/pathological/d8-patterns-reverse-write.test.ts
test/pathological/d9-dream-summary-overwrite.test.ts
test/pathological/facts-mirror-failures.test.ts
test/pathological/g0-derived-retirement-hold.test.ts
+test/pathological/g1-atom-generations.test.ts
+test/pathological/g1-generations.test.ts
test/pathological/h1-zero-yield-atom-reextract.test.ts
test/pathological/h2-git-effect-moved-remote.test.ts
test/pathological/h3-chronicle-partial-generation.test.ts