Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger lane A: every redaction release appends redaction.released in the publication released_by names (#43/#5)
garrytan52b990576618
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex e85f2932a0..5c239a9608 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -6,7 +6,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `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`.- `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.-- `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`). 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.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, 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`.- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.mdindex d05d45f2ca..50776e6aee 100644--- a/docs/designs/BELIEF_LEDGER.md+++ b/docs/designs/BELIEF_LEDGER.md@@ -217,8 +217,11 @@ Link: `link.asserted`, `link.retracted`, `link.transition_added`,Trust and gating (section 6): `trust.contested`, `trust.held`,`trust.retiered`.-Purge (section 6.5): `fact.purged` and `page.purged` (above), and-`derived.hidden` for a key whose row a purge hid through the derivation walk.+Purge (section 6.5): `fact.purged` and `page.purged` (above),+`derived.hidden` for a key whose row a purge hid through the derivation walk,+and `redaction.released` when an owner release binds a redacted field to a new+value (value `{releases: [{field, purge_request, released_hash}]}`, never the+released text; cause `released_by`, the publication the event belongs to).Retention removal of an old soft-deleted page is `page.expired`, never`page.purged`.@@ -1390,8 +1393,12 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.2. **Link `context` is carried text:** it is in the event value (purge redactsit) but excluded from the diff hash, so prose edits near a link appendnothing (probe 2).-3. **Added event types:** `link.revised`, `link.transition_revised` and- `coverage.complete`; a held write's key is+3. **Added event types:** `link.revised`, `link.transition_revised`,+ `coverage.complete` and `redaction.released` (review #43/#5: every write of+ `belief_redactions.released_by` appends one on the redacted key and its+ stream in the same transaction and publication, from the owner-edit append+ path and from `trust confirm`; a confirm that leaves the tier unchanged+ publishes only this event); a held write's key is`["h", <stream lifetime or slug ref>, kind, hold fingerprint]`, so twoholds with one fingerprint in one publication stay two keys.4. **Commit marks** are a follow-up statement after commit by every appender@@ -1423,7 +1430,9 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.claim) and may mint their open lifetime without that page's key. Takingthose keys inside the purge transaction would break the global lockorder, so a concurrent rename of such a page can mint a second lifetime.-12. **Owner release reach (6.5).** A publication is an owner edit only when a+12. **Owner release reach (6.5). W1-later: local CLI writes as owner tier+ needs Garry's trust-posture decision; in W1 only `trust confirm`+ releases.** A publication is an owner edit only when alocal caller journals a direct edit (`put_page`, `edit_page`,`takes_update`, `takes_resolve`) with no internal intent kind; appendstill requires the writer tier at or above `OWNER_TIER_FLOOR`. The trustdiff --git a/src/core/belief/append.ts b/src/core/belief/append.tsindex 0a7dfd6741..0c2155c33a 100644--- a/src/core/belief/append.ts+++ b/src/core/belief/append.ts@@ -41,6 +41,27 @@ export interface AppendContext {preparedEpoch?: number;}+/** One suppression an owner release bound to a new value: never the value itself, only its hash. */+export interface RedactionRelease { field: string; purge_request: string; released_hash: string }+export const REDACTION_RELEASED = 'redaction.released';++/**+ * The `redaction.released` event of one subject (section 6.5): on the redacted key and its stream, in the publication+ * that `belief_redactions.released_by` names, carrying the released fields, their purge requests and the hashes the+ * release bound (never the released text).+ */+export function redactionReleasedDraft(base: Pick<BeliefEventDraft, 'sourceId' | 'incarnation' | 'lifetime' | 'slug' | 'stream' | 'subjectKind' | 'subjectKey'+ | 'trustTier' | 'visibility' | 'stateHash'>, releases: readonly RedactionRelease[], releasedBy: string): BeliefEventDraft {+ const sorted = [...releases].sort((a, b) => a.field.localeCompare(b.field) || a.purge_request.localeCompare(b.purge_request));+ return { sourceId: base.sourceId, incarnation: base.incarnation, lifetime: base.lifetime, slug: base.slug, stream: base.stream, subjectKind: base.subjectKind,+ subjectKey: base.subjectKey, eventType: REDACTION_RELEASED, trustTier: base.trustTier, tierBasis: 'row', visibility: base.visibility,+ value: { releases: sorted }, stateHash: base.stateHash, cause: { op: 'redaction.release', released_by: releasedBy } };+}++let dropReleaseEvents = false;+/** Tests: the forced probe that drops every `redaction.released` event before the insert. */+export function __dropRedactionReleaseEventsForTests(dropped: boolean): void { dropReleaseEvents = dropped; }+const KIND_RANK: Record<string, number> = { coverage: 0, page: 1, fact: 2, take: 3, link: 4, link_transition: 5 };const ASSERTING = /\.(asserted|revised|resolved|unresolved|adopted|transferred)$|^baseline$|^reconcile$/;@@ -69,18 +90,20 @@ interface Suppression { id: number; subject_key: string; field: string; purge_re* Applies the redaction register to the drafts' carrying fields and records* releases and successor copies. Returns each draft's redacted field list.*/-async function applyRedactions(tx: BrainEngine, sourceId: string, drafts: BeliefEventDraft[], ctx: AppendContext): Promise<Map<BeliefEventDraft, string[]>> {+async function applyRedactions(tx: BrainEngine, sourceId: string, drafts: BeliefEventDraft[], ctx: AppendContext): Promise<{ redacted: Map<BeliefEventDraft, string[]>; released: BeliefEventDraft[] }> {const redacted = new Map<BeliefEventDraft, string[]>();+ const released: BeliefEventDraft[] = [];const carrying = drafts.filter(d => d.value && CARRYING_FIELDS[d.subjectKind]?.some(f => typeof d.value![f] === 'string' && d.value![f] !== ''));- if (!carrying.length) return redacted;+ if (!carrying.length) return { redacted, released };const predecessors = carrying.map(d => (d.cause.replaces ?? d.cause.from_key) as string | undefined).filter((k): k is string => !!k);const hashes = carrying.flatMap(d => CARRYING_FIELDS[d.subjectKind]!.map(f => d.value![f]).filter((v): v is string => typeof v === 'string' && v !== '').map(fieldHash));const rows = await tx.executeRaw<Suppression>(`SELECT id, subject_key, field, purge_request::text AS purge_request, field_hash, released_hashFROM belief_redactions WHERE source_id = $1 AND (subject_key = ANY($2::text[]) OR field_hash = ANY($3::text[]))`,[sourceId, [...carrying.map(d => d.subjectKey), ...predecessors], hashes]);- if (!rows.length) return redacted;+ if (!rows.length) return { redacted, released };const owner = isOwnerWrite(ctx);for (const draft of carrying) {+ const releases: RedactionRelease[] = [];const predecessor = (draft.cause.replaces ?? draft.cause.from_key) as string | undefined;for (const field of CARRYING_FIELDS[draft.subjectKind]!) {const text = draft.value![field];@@ -100,13 +123,15 @@ async function applyRedactions(tx: BrainEngine, sourceId: string, drafts: Beliefif (owner && own.every(s => s.field_hash !== hash)) {await tx.executeRaw('UPDATE belief_redactions SET released_by = $2::uuid, released_hash = $3 WHERE id = ANY($1::bigint[])',[own.map(s => Number(s.id)), ctx.publicationId, hash]);+ releases.push(...own.map(s => ({ field, purge_request: s.purge_request, released_hash: hash })));continue;}draft.value = { ...draft.value!, [field]: REDACTION_MARKER(own[0]!.purge_request) };redacted.set(draft, [...redacted.get(draft) ?? [], field]);}+ if (releases.length) released.push(redactionReleasedDraft({ ...draft, stream: draft.stream ?? draft.slug }, releases, ctx.publicationId));}- return redacted;+ return { redacted, released };}let emitterFault: ((drafts: BeliefEventDraft[]) => BeliefEventDraft[]) | null = null;@@ -120,7 +145,7 @@ export function __setBeliefEmitterFaultForTests(fault: ((drafts: BeliefEventDraf}export async function appendBeliefEvents(tx: BrainEngine, input: BeliefEventDraft[], ctx: AppendContext): Promise<number> {- const drafts = emitterFault ? emitterFault(input) : input;+ const drafts = (emitterFault ? emitterFault(input) : input).filter(d => !(dropReleaseEvents && d.eventType === REDACTION_RELEASED));if (!drafts.length) return 0;const ordered = orderDrafts(drafts);const sourceId = ordered[0]!.sourceId;@@ -132,8 +157,9 @@ export async function appendBeliefEvents(tx: BrainEngine, input: BeliefEventDraf}}const purgedFps = ctx.purgesPossible === false ? new Set<string>() : await tombstoned(tx, sourceId, ordered);- const redactions = ctx.purgesPossible === false ? new Map<BeliefEventDraft, string[]>() : await applyRedactions(tx, sourceId, ordered, ctx);- const rows = ordered.map((d, ord) => {+ const { redacted: redactions, released } = ctx.purgesPossible === false ? { redacted: new Map<BeliefEventDraft, string[]>(), released: [] }+ : await applyRedactions(tx, sourceId, ordered, ctx);+ const rows = [...ordered, ...(dropReleaseEvents ? [] : released)].map((d, ord) => {const purged = d.purged === true || (!!d.claimFp && purgedFps.has(d.claimFp) && ASSERTING.test(d.eventType));const value = purged ? null : d.value;return {diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.tsindex 6e2d22e9c1..a3707b4f6b 100644--- a/src/core/belief/ledger.ts+++ b/src/core/belief/ledger.ts@@ -20,7 +20,7 @@ import { COVERAGE_KEY, heldKey, lifetimeRef, pageKey, sha256Hex, canonicalJson,import { readBeliefState, readFactsById, type RawPage, type RawState } from './state.ts';import { keyedSubjects, keyFact, pageNeeds, type KeyContext, type Subject } from './subjects.ts';import { endLifetime, mintLifetime, readOpenLifetimes, renameLifetime, resolveLifetimes } from './lifetimes.ts';-import { appendBeliefEvents, type BeliefEventDraft, type BeliefOrigin } from './append.ts';+import { appendBeliefEvents, redactionReleasedDraft, type BeliefEventDraft, type BeliefOrigin, type RedactionRelease } from './append.ts';export type BeliefNote =| { kind: 'contested'; table: string; rowId: number; proposalId: number; guard: string }@@ -30,7 +30,9 @@ export type BeliefNote =| { kind: 'purged'; table: 'facts' | 'takes' | 'pages'; ids: number[]; request: string; derivedWalk?: 'truncated' }| { kind: 'transferred'; fromSlug: string; table: 'facts' | 'takes' | 'links'; ids: number[] }/** A tier change another writer caused (derived propagation): the batch's own `trust.retiered` for the row carries this cause. */- | { kind: 'retier_cause'; table: 'facts' | 'takes' | 'pages'; rowId: number; cause: Record<string, unknown> };+ | { kind: 'retier_cause'; table: 'facts' | 'takes' | 'pages'; rowId: number; cause: Record<string, unknown> }+ /** The owner confirm released redactions on the row's key (`releaseSuppressedFields`): the batch appends its `redaction.released`. */+ | { kind: 'released'; table: 'facts' | 'takes'; rowId: number; releases: RedactionRelease[] };export interface BeliefBatchOptions {sourceId: string;@@ -426,6 +428,10 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): PromisubjectKind: note.holdKind === 'take' ? 'take' : 'fact', subjectKey: heldKey(lifetime ? lifetimeRef(lifetime) : slugRef(batch.incarnation, note.slug), note.holdKind, note.fingerprint), eventType: 'trust.held',trustTier: note.tier, tierBasis: 'writer', visibility: page && !page.visible ? 'private' : 'world', value: { value_hash: note.valueHash },stateHash: streamHash(note.slug), cause: d.cause({ hold: `wh${note.holdId}` }) });+ } else if (note.kind === 'released') {+ const s = postSubjects.find(x => x.kind === (note.table === 'facts' ? 'fact' : 'take') && x.rowIds.includes(note.rowId));+ if (s) drafts.push(redactionReleasedDraft({ sourceId: opts.sourceId, incarnation: batch.incarnation, lifetime: lifetimeAt(s.stream), slug: s.stream, stream: s.stream,+ subjectKind: s.kind as BeliefEventDraft['subjectKind'], subjectKey: s.key, trustTier: s.tier, visibility: s.visibility, stateHash: streamHash(s.stream) }, note.releases, batch.publicationId));}}return appendBeliefEvents(tx, drafts, { publicationId: batch.publicationId, origin: opts.origin ?? (batch.managed ? 'live' : 'unmanaged'),diff --git a/src/core/belief/purge.ts b/src/core/belief/purge.tsindex 377538dbef..93c53ad1e5 100644--- a/src/core/belief/purge.ts+++ b/src/core/belief/purge.ts@@ -34,8 +34,8 @@ import { CARRYING_FIELDS, REDACTION_MARKER, canonicalJson, fieldHash, pageKey, vimport { readBeliefState } from './state.ts';import { keyedSubjects, pageNeeds } from './subjects.ts';import { resolveLifetimes } from './lifetimes.ts';-import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';-import { coverageActive, readLedgerSource } from './ledger.ts';+import { appendBeliefEvents, type BeliefEventDraft, type RedactionRelease } from './append.ts';+import { coverageActive, noteBelief, readLedgerSource } from './ledger.ts';import { bodySubjects } from './backfill.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';@@ -375,12 +375,16 @@ export async function releaseSuppressedFields(engine: BrainEngine, table: 'factsconst subject = await rowSubject(engine, table, id);if (!subject) return [];const released: string[] = [];+ const releases: RedactionRelease[] = [];for (const field of CARRYING_FIELDS[table === 'facts' ? 'fact' : 'take'] ?? []) {const text = subject.value[field];if (typeof text !== 'string') continue;- const rows = await engine.executeRaw(`UPDATE belief_redactions SET released_by = $4::uuid, released_hash = $5 WHERE source_id = $1 AND subject_key = $2 AND field = $3- AND released_hash IS DISTINCT FROM $5 AND field_hash <> $5 RETURNING id`, [subject.sourceId, subject.key, field, releasedBy, fieldHash(text)]);+ const hash = fieldHash(text);+ const rows = await engine.executeRaw<{ purge_request: string }>(`UPDATE belief_redactions SET released_by = $4::uuid, released_hash = $5 WHERE source_id = $1 AND subject_key = $2+ AND field = $3 AND released_hash IS DISTINCT FROM $5 AND field_hash <> $5 RETURNING purge_request::text AS purge_request`, [subject.sourceId, subject.key, field, releasedBy, hash]);if (rows.length) released.push(field);+ releases.push(...rows.map(r => ({ field, purge_request: r.purge_request, released_hash: hash })));}+ if (releases.length) noteBelief({ kind: 'released', table, rowId: id, releases });return released;}diff --git a/test/belief-ledger-purge-review.test.ts b/test/belief-ledger-purge-review.test.tsindex ffe75d072e..9e88d76439 100644--- a/test/belief-ledger-purge-review.test.ts+++ b/test/belief-ledger-purge-review.test.ts@@ -8,7 +8,8 @@ import { randomUUID } from 'node:crypto';import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { purgeMirrorPath } from '../src/core/belief/purge-mirror.ts';import { CODES } from '../src/core/error-registry.ts';-import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';+import { __dropRedactionReleaseEventsForTests, __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';+import { applyOwnerAction, previewOwnerAction } from '../src/core/trust/owner-actions.ts';import { __dropOwnerEditAllowlistForTests, publicationBeliefOptions, withBeliefBatch } from '../src/core/belief/ledger.ts';import { performSync } from '../src/commands/sync/perform.ts';import { execFileSync } from 'node:child_process';@@ -18,7 +19,7 @@ import { coverageAt, coverageIntervals } from '../src/core/belief/coverage-reporimport { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';import { claimForms, quotes, redactCarryingFields, registerLiveCarriers } from '../src/core/belief/purge.ts';import { REDACTION_MARKER } from '../src/core/belief/keys.ts';-import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { withCoordinatedWrite, withTrustPromotion } from '../src/core/persistence/context.ts';import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';import { operations } from '../src/core/operations.ts';import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';@@ -26,7 +27,7 @@ import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { testBackends } from './helpers/test-backends.ts';import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain, type BeliefEvent } from './helpers/belief-ledger.ts';-afterEach(() => { __setBeliefEmitterFaultForTests(null); __dropOwnerEditAllowlistForTests(false); });+afterEach(() => { __setBeliefEmitterFaultForTests(null); __dropOwnerEditAllowlistForTests(false); __dropRedactionReleaseEventsForTests(false); });const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });@@ -131,6 +132,60 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(forced).toEqual({ marker: forced.marker, sync: ['sync rewrote it'], afterSync: 1 });}, 240_000);+ test('#43/#5: every redaction release appends one redaction.released in the publication released_by names, also when the confirm leaves the tier unchanged', async () => {+ const run = (dropped: boolean) => collect<Record<string, unknown>>(report => brain(async b => {+ const slug = 'companies/acme-example';+ const page = (context: string, confidence = '1.0') => beliefPage({ facts: [X, { claim: 'Acme sells widgets', context, confidence },+ { claim: 'Acme has a board', context: `minutes say ${X}`, confidence }] });+ await b.put(slug, page(`notes say ${X}`));+ await b.put(slug, page(`notes say ${X}`, '0.9'));+ const factId = async (claim: string) => Number((await b.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL`, [b.sourceId, claim]))[0]!.id);+ const confirm = async (claim: string) => {+ const ref = `f${await factId(claim)}`;+ const preview = await previewOwnerAction(b.engine, { action: 'confirm', ref });+ return applyOwnerAction(b.engine, { action: 'confirm', ref }, { binding: preview.binding, confirmation: { via: 'tty' } });+ };+ await confirm('Acme has a board');+ const request = await requestOf(b, String((await purgeFact(b, X)).request_id));+ __dropRedactionReleaseEventsForTests(dropped);+ const fact = (claim: string) => `source_id = $1 AND fact = '${claim}' AND expired_at IS NULL`;+ const publications = async (claim: string) => (await b.engine.executeRaw<{ released_by: string; released_hash: string }>(`SELECT DISTINCT r.released_by::text AS released_by, r.released_hash+ FROM belief_redactions r WHERE r.source_id = $1 AND r.released_by IS NOT NULL AND r.subject_key = (SELECT subject_key FROM belief_events e+ WHERE e.source_id = $1 AND e.value->>'fact' = $2 ORDER BY e.id DESC LIMIT 1)`, [b.sourceId, claim]));+ const shapeOf = async (publication: string) => (await b.events()).filter(e => e.publication_id === publication)+ .map(e => [e.event_type, e.event_type === 'redaction.released' ? [(e.cause as any).released_by === publication, e.value] : e.value?.context ?? null]);+ // The append path: an owner-tier direct edit that sets a different value.+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);+ await withBeliefBatch(tx, publicationBeliefOptions({ id: randomUUID(), source_id: b.sourceId, slug, operation: 'put_page', authority: { remote: false }, intent: {} }),+ () => tx.executeRaw(`UPDATE facts SET context = 'owner rewrote it' WHERE ${fact('Acme sells widgets')}`, [b.sourceId]));+ }, { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'operator_curated', origin: { channel: 'put_page' } } }));+ const [edit] = await publications('Acme sells widgets');+ // The confirm path on a row already confirmed: a write that keeps its tier changes the field (redacted, nothing released),+ // then the confirm leaves the tier as it is, so the release is the publication's only event.+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op: 'managed_file_import', remote: false },+ () => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(`UPDATE facts SET context = 'minutes rewritten' WHERE ${fact('Acme has a board')}`, [b.sourceId])));+ }, { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'user_confirmed', origin: { channel: 'managed_file_import' } } }));+ const tier = (await b.engine.executeRaw<{ t: string }>(`SELECT trust_tier AS t FROM facts WHERE ${fact('Acme has a board')}`, [b.sourceId]))[0]!.t;+ const unchanged = await confirm('Acme has a board');+ const [confirmed] = await publications('Acme has a board');+ const all = await b.events();+ report({ tier, edit: (await shapeOf(edit!.released_by)).filter(([type]) => type !== 'trust.retiered'), confirmed: await shapeOf(confirmed!.released_by), status: unchanged.status, request,+ hashes: [edit!.released_hash, confirmed!.released_hash], text: all.filter(e => e.event_type === 'redaction.released' && /rewr/.test(JSON.stringify(e.value))).length });+ }));+ const r = await run(false);+ const [editHash, confirmHash] = r.hashes as string[];+ expect(r).toEqual({ tier: 'user_confirmed', request: r.request, status: 'confirmed', hashes: r.hashes, text: 0,+ edit: [['fact.revised', 'owner rewrote it'], ['redaction.released', [true, { releases: [{ field: 'context', purge_request: r.request, released_hash: editHash }] }]]],+ confirmed: [['redaction.released', [true, { releases: [{ field: 'context', purge_request: r.request, released_hash: confirmHash }] }]]] });+ // Forced probe: with the event dropped, the release leaves the publication released_by names without any event.+ const forced = await run(true);+ expect(forced.edit).toEqual([['fact.revised', 'owner rewrote it']]);+ expect(forced.confirmed).toEqual([]);+ }, 240_000);+test('#2: the first page purge in a source writes no purged text into the ledger', async () => {const r = await collect<Record<string, unknown>>(report => brain(async b => {const claim = 'Vault code is 7731';diff --git a/test/belief-ledger-purge.test.ts b/test/belief-ledger-purge.test.tsindex 8ae44f923d..4fcbeb3bb8 100644--- a/test/belief-ledger-purge.test.ts+++ b/test/belief-ledger-purge.test.ts@@ -207,7 +207,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {const [register] = await b.engine.executeRaw<{ released_by: string }>(`SELECT released_by::text AS released_by FROM belief_redactionsWHERE source_id = $1 AND field = 'context' AND released_hash IS NOT NULL`, [b.sourceId]);const confirm = (await b.events(mark)).filter(e => e.publication_id === register!.released_by);- expect(confirm.map(e => [`${e.subject_kind}:${e.event_type}`, e.trust_tier])).toEqual([['fact:trust.retiered', 'user_confirmed']]);+ expect(confirm.map(e => [`${e.subject_kind}:${e.event_type}`, e.trust_tier])).toEqual([['fact:redaction.released', 'user_confirmed'], ['fact:trust.retiered', 'user_confirmed']]);const [row] = await b.engine.executeRaw<{ publication: string; marked: boolean }>(`SELECT f.write_origin->'owner_decision'->>'publication_id' AS publication,EXISTS (SELECT 1 FROM belief_commit_marks m WHERE m.publication_id::text = f.write_origin->'owner_decision'->>'publication_id') AS markedFROM facts f WHERE f.id = $1`, [fact!.id]);