Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 1a (wip): purge scrub, inventories, baselines, adapted tests
garrytan9e6739cba847
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex dbff95f368..47a5401ec3 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -3,6 +3,8 @@src/core/persistence/activation.ts 0 coordinator Trusted private administration requires explicit quiescence and durable refusal records before enabling managed canonical writer enforcement.src/core/persistence/canonical-projections.ts 10 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits; a take whose claim changed in place loses its stored resolution there, and a fence row without resolution cells keeps it.src/core/persistence/derived-retirement-hold.ts 2 contract retireDerivedPages versions, soft-deletes and stamps retired_by/retired_at on derived pages (unmanaged extract_atoms retirement) inside maintenanceTransaction behind the canonical table trigger; it never revives or rewrites content, and the purge hold it defines only keeps rows longer.+src/core/generations/adapters/page.ts 1 contract GBRA-161: importPageItem writes a derived page item through importFromContent inside the generation activation's maintenanceTransaction (publish.ts), behind the canonical table trigger; managed brains keep the coordinator path.+src/core/generations/adapters/atoms.ts 1 contract GBRA-161: the unmanaged atom completion flip (source_hash) runs in the generation activation's maintenanceTransaction after every atom and provenance edge was written and before the items are rechecked live; managed brains keep the coordinator path.src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.src/core/persistence/origin-guard.ts 2 engine_guard #6948 bindOrigin records a page origin (and drops an origin_twin marker) only after assertOriginUnclaimed holds the origin advisory lock inside the caller's engine.transaction(); callers are the guarded publication applies and repairs.@@ -46,9 +48,8 @@ src/core/company-brain/demo.ts 2 isolated_eval Fictional source registration usesrc/core/company-brain/profile.ts 2 engine_guard Company-profile legacy deletes use withCompanyBrainSource to lock and validate source incarnation, path, receipt and policy; calls without that context retain engine guards, and managed sync routes to the coordinator before this legacy path. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.src/core/cycle/drift.ts 1 coordinator A managed brain preflights maintenance authority before judge spend and publishes the report through publishMaintenancePage; the unmanaged putPage stays behind the canonical table trigger.-src/core/cycle/extract-atoms.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle/extract-atoms.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/extract-facts.ts 7 coordinator Managed and unmanaged reconciliation key rows by fence row number, update matched rows in place, expire and detach removed rows instead of deleting them, and expire fence-owned rows of soft-deleted pages; on a managed brain each changed page publishes a managed_maintenance_fence_facts request and each soft-deleted page a managed_maintenance_deleted_page_facts_expire request, whose preparers replan or recheck the deletion under the page key inside the coordinator publication.-src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.src/core/cycle/extract-takes.ts 4 coordinator On a managed brain the DB-source walk publishes each fenced page that needs a change as a managed_maintenance_takes_reextract request whose preparer re-reads the page under its key and writes the canonical projection's superseded_by while leaving resolution columns untouched; the file walk and unmanaged brains keep direct SQL, which the trigger refuses on managed brains. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.src/core/cycle/grade-takes.ts 1 coordinator A managed brain applies auto-resolutions through the coordinated takes_resolve page mutation; the unmanaged resolveTake stays behind the canonical table trigger.src/core/cycle/patterns.ts 2 coordinator Managed local patterns use admitted page operations and validate canonical outputs; the legacy reverse-file path runs only unmanaged. Quote grounding writes verified pattern pages back through publishMaintenancePage (revision-checked) on a managed brain; the unmanaged importFromContent write-back stays behind the canonical table trigger. #6302: on that unmanaged path only, the timeline row of a quarantined appended entry is deleted in the same transaction as the import (an import does not reconcile timeline rows; a managed publish projects them from the Markdown).diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex fa0e931bab..cd08494199 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -232,7 +232,6 @@ or a physical projection that leaves attribution untouched):- `src/core/cycle/dream-provenance.ts` (1): the dream provenance frontmatter stamp runs per page in `maintenanceTransaction`, or `derivedMaintenanceTransaction` at the child's derived tier when the ref carries its taint (unmanaged brains only; managed synthesis publishes through maintenance requests).- `src/core/cycle/dream-taint.ts` (3): the unmanaged dream summary page, its frontmatter tags, and the page_versions row of the different body it replaces (#6982), run in `derivedMaintenanceTransaction` at the tier of the pages it indexes; managed brains publish it through a maintenance request.- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.-- `src/core/cycle/extract-atoms-page-state.ts` (1): the atom completion stamp runs in `maintenanceTransaction`.- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication. Both reconcile paths write at the page's tier and gate new rows.- `src/core/cycle/extract-takes.ts` (1): one projected-takes writer stamps each page's tier and runs the write gate: inside a receipted `managed_maintenance_takes_reextract` request per changed page on managed brains, one `maintenanceTransaction` per page tier for the unmanaged batch upsert.- `src/core/enrichment-service.ts` (2): the enrichment stub fallback write and its auto-timeline entry run in `maintenanceTransaction` at the source page's derived tier (the stub import is lowered to it afterwards).@@ -259,6 +258,7 @@ or a physical projection that leaves attribution untouched):- `src/core/persistence/twin-merge.ts` (5): the #6948 twin merge runs in the `managed_maintenance_resolve_origin_twin` preparer's coordinated transaction on managed brains and in one `maintenanceTransaction` on unmanaged brains (`gbrain repair origin-twins` and the post-sync heal); `gbrain repair legacy-twins` calls it from a receipted `managed_maintenance_merge_legacy_twin` request on managed brains and from one `maintenanceTransaction` under both page locks on unmanaged brains.- `src/core/trust/timeline-projection.ts` (2): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback write through it: one `maintenanceTransaction` per page tier.- `src/core/facts/write-single.ts` (2): the legacy single-fact insert and its supersession link each run in `maintenanceTransaction`; managed brains publish through the fact request.+- `src/core/generations/adapters/atoms.ts` (1): the unmanaged atom completion stamp (`source_hash`) runs inside the generation activation's `maintenanceTransaction` (`publish.ts`, GBRA-161).- `src/core/import-file.ts` (12): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.- `src/core/minions/handlers/ingest-capture.ts` (1): the capture ingest tombstone soft delete runs in `maintenanceTransaction`.- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete) each run in `maintenanceTransaction`.diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 2dc6177ca9..0718e53554 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -601,3 +601,11 @@ src/core/persistence/page-edit.ts applyPageEdits call:serializePageToMarkdown SEsrc/core/persistence/page-edit.ts applyPageEdits field SEGW within's stored-offset mapping on the materialized snapshot, as pageSegments; a segmented page takes prepareSegmentedEditMutation firstsrc/core/persistence/page-edit.ts prepareSegmentedEditMutation call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segmentssrc/core/persistence/page-edit.ts assertSegmentedFencesCompile field NONE the fields hold only the stored fence text laid out at its lines (scanCanonicalFences input); no page body is read+src/core/generations/adapters/page.ts pageIdentityHash field INLINE identity hash of a derived page item: a segmented row hashes its empty inline body and is held segmented_unsupported before any write, so no segmented page is rewritten or retired+src/core/generations/adapters/page.ts markdownItem field NONE reads the compiled_truth parseMarkdown returns for the producer's proposed markdown; no stored page body is read+src/core/generations/adapters/page.ts readPageRows sql INLINE reads derived page items (atoms) with body_storage; a segmented row is marked segmented and held segmented_unsupported, with no preimage+src/core/generations/adapters/page.ts pagePreimage field INLINE bounded preimage copy for the generation ledger; a segmented or oversize page stores no preimage (json null) and a restore refuses it+src/core/generations/adapters/page.ts preimageIdentity field NONE hashes a ledger preimage JSON copy, never a stored page body+src/core/generations/adapters/page.ts preimageMarkdown call:serializeMarkdown NONE serializes a ledger preimage JSON copy for restore; segmented and oversize pages have no preimage+src/core/generations/adapters/page.ts preimageMarkdown field NONE reads the body field of a ledger preimage JSON copy; segmented and oversize pages have no preimage+src/core/generations/adapters/page.ts pageVersionEvidence sql INLINE legacy-adoption evidence: hashes retained page_versions copies of derived atom pages and compares identity hashes only; segmented versions (compiled_truth NULL) are skippeddiff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex fa25b7ac08..98c1069cfb 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -1304,7 +1304,7 @@ export async function runPhaseExtractAtoms(context.links = provenanceLinks;context.embed = isAvailable('embedding');const outcome = await publishGeneration(engine, atomGenerationAdapter, { key, items: unmanagedAtoms.map(atom => markdownItem(atom.slug, atom.content)),- input: { pin: atomInputPin(item), size: Buffer.byteLength(item.kind === 'transcript' ? item.content : sourcePage?.compiled_truth ?? '') },+ input: { pin: atomInputPin(item), size: Buffer.byteLength(item.content) },partial: truncated, context, runId });for (const complete of context.postCommit ?? []) await complete().catch(error => console.error(`[extract_atoms] ${originLabel}: post-commit embedding failed (the embedding backfill retries it): ${error instanceof Error ? error.message : String(error)}`));if (outcome.state === 'held') {diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 2cbac77b73..1d362965c2 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -63,6 +63,9 @@ const ROWS: readonly Row[] = [['decide_sweep_deferred', 'out_of_scope', 'no_memory_text', 'source_id slot reason'],['decision_receipts', 'out_of_scope', 'probed_reported', 'decision_id source_id slot mode provider model_alias model_resolved question_kind state_hash question_hash answer_choice outcome subject_ref call_site lane policy_fingerprint calibration_ref error_reason run_meta', 'run_meta'],['derivation_inputs', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id input_table input_id source_id'],+ ['derived_generation_items', 'swept', 'generation_ledger', 'item_key identity_hash action preimage', 'preimage'],+ ['derived_generation_valve', 'out_of_scope', 'no_memory_text', 'source_id kind window_key'],+ ['derived_generations', 'swept', 'generation_ledger', 'source_id kind owner_key state run_id operation_id hold_id input_pin completeness item_set_hash held_reason held_context proposal', 'held_context proposal'],['dream_synthesis_completions', 'out_of_scope', 'no_memory_text', 'source_id idempotency_key'],['dream_verdicts', 'out_of_scope', 'probed_reported', 'file_path content_hash reasons content_type segments entities model', 'segments entities reasons'],['drift_decisions', 'out_of_scope', 'probed_reported', 'reasoning applied_by', 'reasoning'],diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 02648007d0..7abaf119f0 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -526,6 +526,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recconst inline = pageIds.filter(id => !bodies.segmented.includes(id));const chunks = inline.length ? (await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[]) RETURNING 1', [inline])).length : 0;const versions = await redactPageVersions(tx, p.sourceId, current.fact, pageIds);+ const ledger = await (await import('../generations/ledger-scrub.ts')).scrubGenerationLedger(tx, p.sourceId, { needles: [current.fact] });prose = versions.prose;const segments = await purgeSegmentStorage(tx, p.sourceId, current.fact, plan, [...new Set([...bodies.segmented, ...versions.segmentedPages])],[...bodies.replaced, ...versions.replaced], admitted.id);@@ -540,7 +541,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Reccommit_subject: `gbrain: purge fact ${token}`, commit_line: `purge fact ${token}`,targets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,- query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,+ query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices, ...ledger,write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts,page_body_stagings: segments.stagings, page_body_staging_parts: segments.parts, persistence_requests_cancelled: segments.cancelled,derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };diff --git a/src/core/generations/ledger-scrub.ts b/src/core/generations/ledger-scrub.tsnew file mode 100644index 0000000000..8b254970aa--- /dev/null+++ b/src/core/generations/ledger-scrub.ts@@ -0,0 +1,29 @@+/**+ * GBRA-161: purge reaches the generation ledger. Superseded generations keep bounded item preimages and held rows keep+ * the proposal they would publish; both copy memory text, so a page purge nulls every preimage of the purged item and+ * every held proposal naming it, and a fact purge nulls every preimage and proposal carrying the claim. The ledger rows+ * themselves stay (keys, identity hashes and actions only), so restore refuses a scrubbed item with `no_preimage`.+ */+import type { BrainEngine } from '../engine.ts';++export interface LedgerScrub { derived_generation_items: number; derived_generations: number }++/** Nulls the preimages and held proposals that carry the purged page (`slug`) or text (`needles`) in `sourceId`. */+export async function scrubGenerationLedger(tx: BrainEngine, sourceId: string, target: { slug: string } | { needles: readonly string[] }): Promise<LedgerScrub> {+ if ('slug' in target) {+ const items = await tx.executeRaw(`UPDATE derived_generation_items i SET preimage=NULL FROM derived_generations g+ WHERE g.id=i.generation_id AND g.source_id=$1 AND i.item_key=$2 AND i.preimage IS NOT NULL RETURNING 1`, [sourceId, target.slug]);+ const held = await tx.executeRaw(`UPDATE derived_generations SET proposal=NULL, updated_at=now()+ WHERE source_id=$1 AND proposal IS NOT NULL AND (right(owner_key, length($2) + 1) = ':' || $2 OR proposal @> jsonb_build_array(jsonb_build_object('key', $2::text)))+ RETURNING 1`, [sourceId, target.slug]);+ return { derived_generation_items: items.length, derived_generations: held.length };+ }+ const needles = target.needles.filter(Boolean).flatMap(needle => [needle.toLowerCase(), JSON.stringify(needle).slice(1, -1).toLowerCase()]);+ if (!needles.length) return { derived_generation_items: 0, derived_generations: 0 };+ const carries = (column: string) => `EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(${column}::text), n) > 0)`;+ const items = await tx.executeRaw(`UPDATE derived_generation_items i SET preimage=NULL FROM derived_generations g+ WHERE g.id=i.generation_id AND g.source_id=$1 AND i.preimage IS NOT NULL AND ${carries('i.preimage')} RETURNING 1`, [sourceId, needles]);+ const held = await tx.executeRaw(`UPDATE derived_generations SET proposal=NULL, held_context=NULL, updated_at=now()+ WHERE source_id=$1 AND (proposal IS NOT NULL AND ${carries('proposal')} OR held_context IS NOT NULL AND ${carries('held_context')}) RETURNING 1`, [sourceId, needles]);+ return { derived_generation_items: items.length, derived_generations: held.length };+}diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex 02383b0f2a..478af4f449 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -57,6 +57,9 @@ export const GRADUATION_INVENTORY: Inventory = {carry('decide_sweep_deferred', 'operational', 'Deferred System One sweep work with its schedule.'),carry('decision_receipts', 'user_data', 'Durable System One decision receipts.'),carry('derivation_inputs', 'user_data', 'Derivation dependency edges (#5575); purge needs them to find artifacts derived from purged content.'),+ carry('derived_generation_items', 'user_data', 'Generation ledger items (GBRA-161): which derived items each generation owns, with the bounded preimages a restore republishes.'),+ carry('derived_generation_valve', 'operational', 'Generation retirement valve counters per run window (GBRA-161).'),+ carry('derived_generations', 'user_data', 'Generation ledger (GBRA-161): the live, superseded and held generations of each derived key; restore and release-held read it.'),carry('dream_synthesis_completions', 'user_data', 'Dream synthesis idempotency ledger.'),carry('dream_verdicts', 'operational', 'Paid dream triage verdict cache.'),carry('drift_decisions', 'user_data', 'Take drift decisions and when they were applied.'),diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 297d503b21..7e46f8cd24 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -330,6 +330,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,const files = await tx.executeRaw<{ storage_path: string }>(`DELETE FROM files WHERE (page_id=$1 OR (page_slug=$2 AND (source_id=$3 OR source_id IS NULL)))RETURNING storage_path`, [page.id, slug, sourceId]);removed.files = files.length;+ Object.assign(removed, await (await import('../generations/ledger-scrub.ts')).scrubGenerationLedger(tx, sourceId, { slug }));const [cascade] = await tx.executeRaw<{ chunks: number; versions: number; takes: number; timeline: number }>(`SELECT(SELECT count(*)::int FROM content_chunks WHERE page_id=$1) AS chunks, (SELECT count(*)::int FROM page_versions WHERE page_id=$1) AS versions,(SELECT count(*)::int FROM takes WHERE page_id=$1) AS takes, (SELECT count(*)::int FROM timeline_entries WHERE page_id=$1) AS timeline`, [page.id]);diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 0f1cfbc62c..9ca39bbb35 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 136, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });+ expect(counts).toEqual({ carry: 139, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });diff --git a/test/write-attribution-cycle.test.ts b/test/write-attribution-cycle.test.tsindex c028e4446b..b92d475fe3 100644--- a/test/write-attribution-cycle.test.ts+++ b/test/write-attribution-cycle.test.ts@@ -84,7 +84,10 @@ describe('cycle and synthesis writers on an unmanaged brain', () => {const source = 'writings/essay-example';await creatorPage(brain, source, { compiled_truth: 'A long essay with extractable claims.' });const stale = 'atoms/2026-01-01/retired-example';- await creatorPage(brain, stale, { type: 'atom', compiled_truth: 'An older claim.', frontmatter: { type: 'atom', source_slug: source, source_hash: 'aaaaaaaaaaaaaaaa' } });+ await creatorPage(brain, stale, { type: 'atom', compiled_truth: 'An older claim.', frontmatter: { type: 'atom', source_slug: source, source_hash: 'aaaaaaaaaaaaaaaa', extracted_by: 'extract_atoms-v0.41.2.1' } });+ // GBRA-161: an atom from before the generation ledger is retired only on retained extractor evidence (a page version+ // the extractor wrote, unedited since), which a real earlier extraction leaves behind.+ await asCreator(engine, tx => tx.createVersion(stale, { sourceId: brain.sourceId }));const chat = async (): Promise<ChatResult> => ({text: '[{"title":"Prototypes beat renders","atom_type":"insight","body":"Buyers want tangible prototypes."}]',blocks: [{ type: 'text', text: '' }], stopReason: 'end', model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',