Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: forget_fact on an already-expired fact publishes its withdrawal, then answers fact_already_expired
garrytan6e09d1e68e91
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 6634334f78..88e7f71326 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -85,6 +85,11 @@ interface PreparedMutationBase {* and effects from it instead of reading the page again.*/postimage?: PageSnapshot | null;+ /**+ * #8636: the publication commits every write it made (files, rows, effects), then finishes the request failed with+ * this error instead of committed (forget_fact on an already-expired fact: its withdrawal is recorded, the answer is a refusal).+ */+ failure?: { code: string; message: string };validate?(tx: BrainEngine): Promise<void>;/*** #6712 PR 4b: runs in the publication transaction right after its effects are queued, so it sees the request's own@@ -696,19 +701,19 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared, { pushOnly: !!door, ...(pageTargets ? { pageTargets } : {}) }));if (prepared.afterEffects) await withCoordinatedWrite(tx, [row.source_id], () => prepared.afterEffects!(tx, outcome), publicationAttribution(row, prepared.trust));await hooks.boundary?.('before_commit', row);- const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);+ const committed = await completeWrite(tx, current, prepared.failure ? 'failed' : 'committed', outcome, prepared.failure, current);transactionBodyCompleted = true;return committed;}, { pipelineFirst: isPersistenceDeclaration });await hooks.boundary?.('after_commit', done);- if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(engine, [row.id]).catch(() => undefined);+ if (beliefReport.appended && (done.state === 'committed' || prepared.failure)) await markBeliefCommits(engine, [row.id]).catch(() => undefined);if (recovery) {// A large prior file's copy (staging.before) is removed once the outcome is durable, before its record is cleared.const staged = recovery;if (!isBundleRecovery(staged)) for (const file of recoveryFiles(staged)) if (file.staging?.before) await withFilesystemPublication([file.root], async () => cleanupRecoveryStaging(file));await clearResolvedRecovery(engine, row.id, done);}- if (done.state === 'committed') afterCommitDue = done;+ if (done.state === 'committed' || prepared.failure) afterCommitDue = done;return done;} catch (error) {if (recovery) {diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.tsindex 7ad72622ff..6b7b0de570 100644--- a/src/core/persistence/forget-prepare.ts+++ b/src/core/persistence/forget-prepare.ts@@ -15,7 +15,7 @@ import { existsSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { PageSnapshot, PageWithdrawal } from '../page-state/types.ts';-import { opError, verbError } from '../ops/contract.ts';+import { verbError } from '../ops/contract.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { serializePageToMarkdown } from '../markdown.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';@@ -99,9 +99,6 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteRequeif (!Number.isSafeInteger(id) || id <= 0) throw missing();const fact = await readForgetTarget(engine, id, sourceId, remote, excludePrivate, false, ownPage);if (!fact) throw missing();- if (row.operation === 'forget_fact' && fact.expired_at !== null) {- throw opError('fact_already_expired', `Fact id ${id} already expired.`, 'Recall the entity to read its current facts; nothing was changed.');- }const plan = await planFactWithdrawal(engine, id, sourceId, remote, ownPage ? undefined : excludePrivate, ownPage);if (!plan) throw missing();// The files are struck with this timestamp, and the ledger row records it, so the file and the read overlay agree.@@ -142,6 +139,8 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque}let pages: string[] = [];return { observedRevision: own?.revision ?? null, ...(file ? { file } : {}), ...(companions.length ? { companions } : {}),+ // #8636: forget_fact on an already-expired fact still publishes its withdrawal, then answers fact_already_expired.+ ...(row.operation === 'forget_fact' && fact.expired_at !== null ? { failure: { code: 'fact_already_expired', message: `Fact id ${id} already expired.` } } : {}),validate: async tx => {// Under the publication's locks: the fact is still visible, no more trusted than a remote caller, and reaches no other copy.const current = await readForgetTarget(tx, id, sourceId, remote, excludePrivate, true, ownPage);@@ -150,7 +149,7 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteRequeif (!ownPage) await refuseForgetReachingOtherCopies(tx, sourceId, current, remote, excludePrivate);},apply: async tx => {- // Even an expired legacy fact acquires a ledger row, so a stale import cannot reactivate it.+ // Even an expired legacy fact acquires a ledger row (forget_fact then finishes failed), so a stale import cannot reactivate it.const publication = { withdrawnAt, expectedSlugs: plan.slugs };pages = (await recordFactWithdrawal(tx, id, sourceId, remote, ownPage? { requestId: row.id, semanticReview: false, memberPage: ownPage, publication }diff --git a/test/forget-fact-expired-ledger.test.ts b/test/forget-fact-expired-ledger.test.tsnew file mode 100644index 0000000000..15c42a61eb--- /dev/null+++ b/test/forget-fact-expired-ledger.test.ts@@ -0,0 +1,67 @@+/**+ * #8636: forget_fact on a fact that already expired without a withdrawal (a legacy expiry) still answers+ * fact_already_expired, but first publishes the withdrawal: the ledger row, and on a file-backed source the struck fence+ * row, so neither a stale import nor a fence reconcile reactivates the claim. Repo-less (PGLite, MCP dispatch) and+ * file-backed (managed brain with a Git checkout, operation handlers).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const CLAIM = 'Keeps a rooftop beehive expiredledger';+const fence = (rows: string[]) => ['<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|', ...rows, '<!--- gbrain:facts:end -->'].join('\n');+const stale = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\nNotes.\n\n## Facts\n\n${fence([`| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | test | |`])}\n`;+const ledger = (engine: BrainEngine) => engine.executeRaw("SELECT 1 FROM fact_withdrawals WHERE source_id='default' AND fact_hash=gbrain_fact_fingerprint($1)", [CLAIM]);+const active = async (engine: BrainEngine) => (await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM facts WHERE source_id='default' AND fact=$1 AND expired_at IS NULL", [CLAIM]))[0]!.n;++describe('repo-less brain', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });+ afterAll(async () => { await engine.disconnect(); });++ test('forget_fact on a legacy-expired fact answers fact_already_expired, records the ledger row, and a stale import stays withdrawn', async () => {+ const inserted = await engine.insertFact({ fact: CLAIM, kind: 'fact', source: 'test', visibility: 'world' }, { source_id: 'default' });+ await engine.expireFact(inserted.id);+ const r = await dispatchToolCall(engine, 'forget_fact', { id: inserted.id }, { remote: false, sourceId: 'default' });+ expect(r.isError).toBe(true);+ expect(JSON.parse(r.content[0].text).error).toBe('fact_already_expired');+ expect(await ledger(engine)).toHaveLength(1);+ await dispatchToolCall(engine, 'put_page', { slug: 'notes/stale', content: stale('Stale') }, { remote: false, sourceId: 'default' });+ expect(await active(engine)).toBe(0);+ }, 60_000);+});++const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) =>+ operationsByName[name]!.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, ...params }) as Promise<Record<string, any>>;+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };++describe('file-backed brain', () => {+ test('forget_fact on a legacy-expired fact strikes its fence row in a commit, records the ledger row, answers fact_already_expired; a stale import stays withdrawn', () => managedBrain(async ({ engine, ctx, root }) => {+ expect(await call(ctx, 'put_page', { slug: 'notes/a', content: stale('A') })).toMatchObject({ state: 'committed' });+ const [fact] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE source_id='default' AND fact=$1 AND expired_at IS NULL", [CLAIM]);+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw('UPDATE facts SET expired_at=now() WHERE id=$1', [Number(fact!.id)]), TEST_WRITE_ATTRIBUTION));+ await expect(call(ctx, 'forget_fact', { id: Number(fact!.id) })).rejects.toMatchObject({ code: 'fact_already_expired' });+ expect(await ledger(engine)).toHaveLength(1);+ const text = readFileSync(join(root, 'notes/a.md'), 'utf8');+ expect(text).toContain(`~~${CLAIM}~~`);+ expect(text).toContain('forgotten:');+ await settleManagedGitEffects(engine);+ expect(git(root, 'status', '--porcelain', '--', 'notes/a.md')).toBe('');+ expect(git(root, 'show', 'HEAD:notes/a.md')).toContain('forgotten:');+ await call(ctx, 'put_page', { slug: 'notes/a', content: stale('A') }).catch(() => undefined);+ expect(await active(engine)).toBe(0);+ }, { setup }), 180_000);+});