Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
LPH (h2): purge_fact deletes unreferenced segment texts holding the claim as a fence cell stores it
garrytanec1196546393
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 86829b5f91..abb5d0de6c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -911,6 +911,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A withdrawal (`forget`, `forget_fact`, `purge_fact`) of a claim in a facts fence that crosses a forced segment cut, when that one fence holds more than 16,384 rows (or more than 8 MiB of rows to check), is still refused `withdrawal_capacity` (the bound is unchanged), but the refusal now says why: it carries reason `split_fence_rows`, names the page, the fence\'s row count and the limit, and its fix asks you to split that fence into fences of at most 16,384 rows and write the page again. It used to say discovery "could not prove a bounded complete target set" and told you not to split the source.' },// Large-pages hardening (h): N14-5.{ since: 'TBD', text: '`delete_page purge: true` (`gbrain delete --purge`) of a page stored in segments now also deletes, in the purge, the segment texts the page stopped referencing within the last hour, which used to stay in `page_segment_texts` until the hourly segment sweep removed them. A withdrawal (`forget`, `forget_fact`) followed by another write to the page (a delete and `restore_page` included) left the text that held the withdrawn row, with the page text around it, in that state, and the purge reported success. `removed.page_segment_texts` in the purge receipt counts these texts too. A text that an unpublished write of another page staged is still kept, as before for the texts the page referenced.' },+ { since: 'TBD', text: '`purge_fact` (`gbrain forget <id> --purge`) of a claim containing `|` now also deletes the unreferenced segment texts that hold the claim as its facts-fence cell stores it (`|` escaped as `\\|`, a line break as `<br>`), in the purge. It matched only the claim\'s exact bytes, so after a withdrawal and another write to a page stored in segments (a delete and `restore_page` included) the text holding the old fence row stayed until the hourly segment sweep, and the receipt\'s `page_segment_texts` store did not report it. The receipt now probes both forms.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 5c96ef2bc1..2b8b217968 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -445,7 +445,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgif (Number(legacy?.n ?? 0)) stores.push({ store: 'derived_legacy', status: 'unverified', reason: 'legacy_no_derivation_edges', remaining: Number(legacy.n),detail: `${legacy.n} model-derived page(s) in this source predate derivation edges, so purge cannot tell whether they restate the claim in other words.` });if (!dryRun) {- stores.push(await segmentTextReport(engine, src, [claim], removed.page_segment_texts ?? 0, deadline));+ stores.push(await segmentTextReport(engine, src, [...new Set([claim, escapeFenceCell(claim)])], removed.page_segment_texts ?? 0, deadline));stores.push(...await ledgerReports(engine, src, [claim], input.ledger, deadline));stores.push(await effectPayloadReport(engine, src, [claim], deadline, removed.persistence_effects ?? 0));}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 287821f841..02648007d0 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -346,8 +346,9 @@ export async function redactPageVersions(tx: BrainEngine, sourceId: string, clai/*** Wave B (spec 11), after the body and version rewrites: stagings holding the claim are aborted (their upload parts* deleted, requests that reference them cancelled with purged_content), closed manifest rows outside every GC root- * go, and every segment text the rewrites replaced, or that still holds the claim, is deleted once nothing- * references it, in this transaction (purge never waits for GC). A live staging that recorded such a text was aborted+ * go, and every segment text the rewrites replaced, or that still holds the claim (plain, or as a fence cell stores it:+ * escapeFenceCell, the forms stagingsHoldingClaim matches), is deleted once nothing references it, in this transaction+ * (purge never waits for GC). A live staging that recorded such a text was aborted* by the plan (`stagingsHoldingClaim`), so no write in flight still needs it. The restore-time purge replay runs it too.*/export async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claim: string, plan: Pick<PurgePlan, 'stagings' | 'held'>, pageIds: number[],@@ -366,8 +367,9 @@ export async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claif (pageIds.length) await tx.executeRaw('DELETE FROM page_view_digests WHERE page_id=ANY($1::int[])', [pageIds]);const texts = (await tx.executeRaw(`DELETE FROM page_segment_texts d WHERE (d.source_id,d.sha256) IN (SELECT t.source_id,t.sha256 FROM page_segment_texts tWHERE t.source_id=$1 AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) OFFSET 0)- AND (d.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h) OR strpos(lower(convert_from(d.body,'UTF8')),$3)>0) RETURNING 1`,- [sourceId, replaced.map(sha => Buffer.from(sha).toString('hex')), claim.toLowerCase()])).length;+ AND (d.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h) OR strpos(lower(convert_from(d.body,'UTF8')),$3)>0+ OR strpos(lower(convert_from(d.body,'UTF8')),$4)>0) RETURNING 1`,+ [sourceId, replaced.map(sha => Buffer.from(sha).toString('hex')), claim.toLowerCase(), escapeFenceCell(claim).toLowerCase()])).length;return { texts, stagings: plan.stagings.length, parts, cancelled };}diff --git a/test/pathological/lp-h-purge-orphan-segment-text.test.ts b/test/pathological/lp-h-purge-orphan-segment-text.test.tsindex 5a09356d9d..e6c34e6663 100644--- a/test/pathological/lp-h-purge-orphan-segment-text.test.ts+++ b/test/pathological/lp-h-purge-orphan-segment-text.test.ts@@ -9,7 +9,10 @@* takes every text the page's own stagings recorded (page_body_staging_texts) and deletes those no manifest row* references, in the same transaction. A text a live staging of another write recorded stays (that unpublished* write's copy, the rule for referenced texts); purge_fact aborts a live staging holding the claim, so its texts go.- * 2. Fails when: right after the purge, before any GC, a row of page_segment_texts still holds the planted claim.+ * purge_fact's text delete also matches the claim as a fence cell stores it (escapeFenceCell: `|` as `\|`), the+ * forms stagingsHoldingClaim matches, so an orphan holding a claim with `|` goes too.+ * 2. Fails when: right after the purge, before any GC, a row of page_segment_texts still holds the planted claim, plain+ * or escaped.* 3. A 2 MB conversation page with a facts fence: put_page, forget_fact, delete_page, restore_page, then delete_page* purge:true (the N14 lifecycle) or purge_fact of the claim. Runs on PGLite, and on Postgres when DATABASE_URL is* set. N14 reproduced it at 2 MB, 20 MB and 24 MiB; the orphan is one fence segment at any size, so the 2 MB page@@ -27,6 +30,7 @@ import { operations } from '../../src/core/operations.ts';import { registerLocalWriter } from '../../src/core/persistence/identity.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { escapeFenceCell } from '../../src/core/fence-shared.ts';import { conversationBody } from '../helpers/conversation-page.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';@@ -37,13 +41,16 @@ import { pathologicalArms } from './harness.ts';const TOKEN = 'quillfeather7731';const CLAIM = `The lifecycle marker is ${TOKEN}`;const NEEDLES = ['lphneedleone', 'lphneedletwo', 'lphneedlethree'];-const FENCE = ['', '', '## Facts', '', '<!--- gbrain:facts:begin -->',+const PIPE_TOKEN = 'pipe8842';+/** A claim holding `|`: the fence cell stores it escaped (`\|`), so the stored text never holds the claim's exact bytes. */+const PIPE_CLAIM = `The gate marker is quill|${PIPE_TOKEN}`;+const fence = (cell: string) => ['', '', '## Facts', '', '<!--- gbrain:facts:begin -->','| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |','|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',- `| 1 | ${CLAIM} | fact | 1.0 | world | low | 2026-10-01 | | chat | |`,+ `| 1 | ${cell} | fact | 1.0 | world | low | 2026-10-01 | | chat | |`,'<!--- gbrain:facts:end -->', ''].join('\n');-const page = (seed: number) => `---\ntitle: Lifecycle chat\ntype: note\n---\n\n${conversationBody(2_000_000, { seed,- needles: NEEDLES.map((word, i) => ({ at: 0.2 + i * 0.3, word })) })}${FENCE}`;+const page = (seed: number, cell = CLAIM) => `---\ntitle: Lifecycle chat\ntype: note\n---\n\n${conversationBody(2_000_000, { seed,+ needles: NEEDLES.map((word, i) => ({ at: 0.2 + i * 0.3, word })) })}${fence(cell)}`;const homes: string[] = [];afterAll(() => { for (const home of homes) rmSync(home, { recursive: true, force: true }); });@@ -78,17 +85,17 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge aftORDER BY 1`, [slug])).map(row => row.sha);/** put_page, forget_fact, delete_page, restore_page: leaves the pre-forget fence text unreferenced (N14-5). */- async function lifecycle(slug: string, seed: number): Promise<{ factId: number; orphans: string[] }> {- await op('put_page', { slug, content: page(seed), request_id: randomUUID(), wait_ms: 30000 });+ async function lifecycle(slug: string, seed: number, claim = { cell: CLAIM, token: TOKEN }): Promise<{ factId: number; orphans: string[] }> {+ await op('put_page', { slug, content: page(seed, claim.cell), request_id: randomUUID(), wait_ms: 30000 });expect((await segmentedPageRow(engine, slug)).body_storage).toBe('segmented');- const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND strpos(fact,$2)>0', ['default', TOKEN]);+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND strpos(fact,$2)>0', ['default', claim.token]);const factId = Number(fact!.id);expect((await op('forget_fact', { id: factId, reason: 'lp-h lifecycle' })).expired).toBe(true);expect((await op('delete_page', { slug, request_id: randomUUID(), expected_revision: await revision(slug) })).status).toBe('soft_deleted');expect((await op('restore_page', { slug, request_id: randomUUID(), expected_revision: await revision(slug, true) })).status).toBe('restored');const orphans = await orphansOf(slug);expect(orphans.length).toBeGreaterThan(0);- expect(await textsHolding(TOKEN)).toBeGreaterThan(0);+ expect(await textsHolding(claim.token)).toBeGreaterThan(0);return { factId, orphans };}/** An unpublished create of another page that deduped onto `sha` (its staging recorded the text). */@@ -159,4 +166,25 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge aftexpect(read.revision).toBe(row.knowledge_revision);await engine.executeRaw('DELETE FROM page_body_stagings WHERE id=$1::uuid', [staging]);}), 600_000);++ test('purge_fact of a claim holding | deletes the unreferenced text that stores it escaped in the fence cell', async () => withEnv(env(), async () => {+ const slug = 'notes/lp-h-pipe-purge', cell = escapeFenceCell(PIPE_CLAIM);+ expect(cell).not.toBe(PIPE_CLAIM);+ const { factId, orphans } = await lifecycle(slug, 19, { cell, token: PIPE_TOKEN });+ const [fact] = await engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE id=$1', [factId]);+ expect(fact!.fact).toBe(PIPE_CLAIM);+ const escaped = (await Promise.all(orphans.map(async sha => (await engine.executeRaw(`SELECT 1 FROM page_segment_texts WHERE source_id='default'+ AND sha256=decode($1,'hex') AND position(convert_to($2::text,'UTF8') in body)>0`, [sha, cell])).length))).filter(Boolean).length;+ expect(escaped).toBeGreaterThan(0);+ const dry = await op('purge_fact', { id: factId, dry_run: true });+ const done = await op('purge_fact', { id: factId, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });+ expect(done.state).toBe('committed');+ const left = { escaped: await textsHolding(cell), plain: await textsHolding(PIPE_CLAIM), orphans: (await Promise.all(orphans.map(textExists))).filter(Boolean).length };+ console.log(`[lp-h] ${backend} pipe purge_fact: ${escaped} orphan(s) holding the escaped cell before; after: ${JSON.stringify(left)}`);+ expect(left).toEqual({ escaped: 0, plain: 0, orphans: 0 });+ const { page: row, body, hash } = await reconstructedPage(engine, slug);+ expect(hash).toBe(row.content_hash);+ expect(body.compiled_truth).not.toContain(PIPE_TOKEN);+ for (const needle of NEEDLES) expect(body.compiled_truth).toContain(needle);+ }), 600_000);});