Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(trust): put_page back inside the #6007 statement budget without raising it

garrytan14e09d84378d
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index e97b16e567..bab3a8b265 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -11,7 +11,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included) / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
-- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
+- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug, then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts`.
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index bdd0fd7656..1ce5485854 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -830,7 +830,7 @@ export async function importFromContent(
await writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy);
if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
- await disposition.persistReceipt(tx);
+ await disposition.persistReceipt(tx, { existed: !!existing });
if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
// Capture the complete installed projection before releasing the page
// guard. Deferred provider results cannot replace newer text or chunks.
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index a0cb67bfd1..e536c0ebd1 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -10,6 +10,7 @@
*/
import type { BrainEngine } from './engine.ts';
import { loadConfig, loadConfigWithEngine } from './config.ts';
+import { loadConfigSnapshot } from './config-snapshot.ts';
import { assessContentSanity, ContentSanityBlockError, type ContentSanityResult } from './content-sanity.ts';
import { carryStoredQuarantineOverride, dropClassifierMarkers, hasCurrentQuarantineOverride, QUARANTINE_OVERRIDE_KEY, withQuarantineOverride } from './quarantine-override.ts';
import { logContentSanityAssessment } from './audit/content-sanity-audit.ts';
@@ -57,10 +58,17 @@ export interface ImportSanityConfig {
export async function loadImportSanityConfig(engine: BrainEngine): Promise<ImportSanityConfig> {
const baseCfg = loadConfig();
let effectiveCfg = baseCfg;
- const readKey = (key: string) => engine.getConfig(key).catch(() => null);
+ // One whole-table read answers the DB config lift and the write-gate keys (#6007 statement budget).
+ const snapshot = await loadConfigSnapshot(engine);
+ const reader = snapshot ? {
+ getConfig: async (key: string) => snapshot[key] ?? null,
+ getAllConfig: async () => snapshot,
+ listConfigKeys: async (prefix: string) => Object.keys(snapshot).filter(key => key.startsWith(prefix)),
+ } : engine;
+ const readKey = async (key: string) => { try { return await reader.getConfig(key); } catch { return null; } };
const gateKeys = Promise.all([readKey('write_gate.external_mode'), readKey('write_gate.agent_mode')]);
try {
- effectiveCfg = await loadConfigWithEngine(engine, baseCfg);
+ effectiveCfg = await loadConfigWithEngine(reader, baseCfg);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`[gbrain] content-sanity: DB config lift failed (${msg}); falling back to file/env\n`);
@@ -92,7 +100,7 @@ export interface ContentDisposition {
/** The write-gate assessment, when the caller passed `writeGate`. */
gate: WriteGateAssessment | null;
/** Records the gate's flag/quarantine receipt for the written page inside the publication transaction. */
- persistReceipt: (tx: BrainEngine) => Promise<void>;
+ persistReceipt: (tx: BrainEngine, page: { existed: boolean }) => Promise<void>;
}
/**
@@ -248,8 +256,9 @@ export async function settleContentDisposition(engine: BrainEngine, parsed: Pars
}
return {
quarantined: pageQuarantined, flagged: pageFlagged, ...(pageFlagReason ? { flagReason: pageFlagReason } : {}), gate,
- persistReceipt: async tx => {
- if (gate?.ran) await clearStalePageGateReceipts(tx, { slug, sourceId: sourceId ?? 'default', contentHash: gate.contentHash });
+ persistReceipt: async (tx, page) => {
+ // A page created by this write has a fresh id, so no receipt can name it yet (#6007: no delete on create).
+ if (gate?.ran && page.existed) await clearStalePageGateReceipts(tx, { slug, sourceId: sourceId ?? 'default', contentHash: gate.contentHash });
if (gate) await recordPageGateReceipt(tx, { slug, sourceId: sourceId ?? 'default', assessment: gate, requestId: ctx.writeGate?.requestId ?? null });
},
};
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index efdf95136a..6e7aa6f258 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -10,7 +10,7 @@ import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetenti
import { retryWriteAdmission } from './admission-retry.ts';
import { writeHealth, type WriteHealthFacts } from './health.ts';
import { writerStamp } from './writer-versions.ts';
-import { intentCarriesPurgedContent } from './purged-intent.ts';
+import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
@@ -581,7 +581,8 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
// #6007: one statement sizes the queued effects, checks the terminal reservation, completes the row and
// releases its outstanding counters; no row means the encoding exceeds the reservation and nothing changed.
const resultBytes = jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0);
- const [done] = await tx.executeRaw<WriteRequest>(`WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes
+ const probePurges = intentCarriesContent(current.intent);
+ const [terminal] = await tx.executeRaw<WriteRequest & { purge_has_facts?: boolean; purge_has_pages?: boolean }>(`WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes
FROM persistence_effects WHERE request_id=$1::uuid),
done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,
error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
@@ -591,13 +592,15 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
WHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *),
released AS (UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$11
WHERE key=ANY($10::text[]) AND EXISTS (SELECT 1 FROM done))
- SELECT * FROM done`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId,
+ SELECT done.*${probePurges ? `, ${PURGE_PRESENCE_COLUMNS}` : ''} FROM done`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId,
error?.detail ? JSON.stringify(error.detail) : null, resultBytes, ['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);
- if (!done) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
+ if (!terminal) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
+ const { purge_has_facts: purgeFacts, purge_has_pages: purgePages, ...doneRow } = terminal;
+ const done = doneRow as WriteRequest;
// #5575: a terminal write whose stored intent carries purged content (refused by the purge guards, refused for another
// reason first, or committed as a no-op after the overlay dropped the purged rows) keeps no copy of it; replay answers
// from the stored outcome, and the intent bytes were released above.
- if (error && PURGED_REFUSAL.test(`${error.code}: ${error.message}`) || await intentCarriesPurgedContent(tx as BrainEngine, current)) {
+ if (error && PURGED_REFUSAL.test(`${error.code}: ${error.message}`) || probePurges && await intentCarriesPurgedContent(tx as BrainEngine, current, { facts: purgeFacts === true, pages: purgePages === true })) {
const [redacted] = await tx.executeRaw<WriteRequest>('UPDATE persistence_requests SET intent=NULL,compacted=true WHERE id=$1::uuid RETURNING *', [row.id]);
return redacted ?? done;
}
diff --git a/src/core/persistence/purged-intent.ts b/src/core/persistence/purged-intent.ts
index a23cff6a48..862a57432d 100644
--- a/src/core/persistence/purged-intent.ts
+++ b/src/core/persistence/purged-intent.ts
@@ -7,8 +7,9 @@
*
* Checks the claims a memory or take write names (`fact`, `claim`) and the
* facts-fence rows of page content against fact_purges, and page content's
- * content hash against page_purges. One indexed probe decides that a source
- * with no tombstones needs no parsing.
+ * content hash against page_purges. Whether the source holds any tombstone
+ * rides completeWrite's terminal statement (PURGE_PRESENCE_COLUMNS), so a
+ * source with none needs no parsing and no extra statement.
*/
import type { BrainEngine } from '../engine.ts';
@@ -17,13 +18,21 @@ import { parseFactsFence } from '../facts-fence.ts';
import { contentHash } from '../utils.ts';
import type { WriteRequest } from './model.ts';
-export async function intentCarriesPurgedContent(tx: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'slug' | 'intent'>): Promise<boolean> {
+/** Only content-bearing writes (content, fact or claim) can carry purged text; every other completion skips the probe. */
+export function intentCarriesContent(intent: unknown): boolean {
+ const named = intent as Record<string, unknown> | null;
+ return !!named && [named.content, named.fact, named.claim].some(v => typeof v === 'string' && v);
+}
+
+/** Selected by completeWrite's terminal statement (#6007: no extra round trip): does the source hold any fact or page tombstone? */
+export const PURGE_PRESENCE_COLUMNS = `EXISTS (SELECT 1 FROM fact_purges WHERE source_id=done.source_id) AS purge_has_facts,
+ EXISTS (SELECT 1 FROM page_purges WHERE source_id=done.source_id) AS purge_has_pages`;
+
+export async function intentCarriesPurgedContent(tx: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'slug' | 'intent'>,
+ has: { facts: boolean; pages: boolean }): Promise<boolean> {
const intent = row.intent as Record<string, unknown> | null;
- // Only content-bearing writes can carry purged text; every other completion skips the probe.
- if (!intent || ![intent.content, intent.fact, intent.claim].some(v => typeof v === 'string' && v)) return false;
- const [has] = await tx.executeRaw<{ facts: boolean; pages: boolean }>(`SELECT EXISTS (SELECT 1 FROM fact_purges WHERE source_id=$1) AS facts,
- EXISTS (SELECT 1 FROM page_purges WHERE source_id=$1) AS pages`, [row.source_id]);
- if (!has?.facts && !has?.pages) return false;
+ if (!intent || !intentCarriesContent(intent)) return false;
+ if (!has.facts && !has.pages) return false;
const content = typeof intent.content === 'string' ? intent.content : null;
// Tombstones are subject-scoped like the guards: a memory write's claim is about its entity, a fence row about its page.
const subject = typeof intent.entity_slug === 'string' ? intent.entity_slug : typeof intent.entity === 'string' ? intent.entity : row.slug;
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index b146c73243..0a5949d041 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -22,7 +22,7 @@ import { decideFactWrite, recordFlaggedRow, recordWriteGateHold, type GatedRowDe
import { gateInput } from './gate-outcomes.ts';
import { insertTrustProposal } from './proposals.ts';
import { recordContestedFact } from './supersede-handlers.ts';
-import { compareTrust, storedTrustTier, trustRankSql } from './tier.ts';
+import { compareTrust, storedTrustTier, trustRankSql, type WriteTrust } from './tier.ts';
type FenceFact = NewFact & { row_num: number };
const WRITER_RANK = trustRankSql(`COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown')`);
@@ -53,6 +53,8 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming]);
if (guarded.length) await tx.executeRaw('UPDATE facts SET row_num = NULL WHERE id = ANY($1::bigint[])', [guarded.map(g => Number(g.id))]);
await expire();
+ // A fence with no rows and nothing guarded has nothing to place or gate (#6007: no reads on a fence-free publish).
+ if (!input.rows.length && !guarded.length) return { rows: [], async finish() { return []; } };
const occupied = new Set((await tx.executeRaw<{ row_num: number }>(
'SELECT row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL AND expired_at IS NULL', [sourceId, slug]))
.map(r => Number(r.row_num)));
@@ -65,18 +67,19 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
occupied.add(target.row_num);
rows = rows.filter(r => r !== target);
}
- const trust = await currentWriteTrust(tx) ?? { tier: 'unknown' as const, origin: null };
const gated: Array<{ row: T; decision: GatedRowDecision }> = [];
const inserted: T[] = [];
- // Owner-tier writers (tool_observed and above) are never gated, so they read no gate config.
- const cfg = compareTrust(trust.tier, 'tool_observed') < 0 && rows.some(r => !occupied.has(r.row_num)) ? await input.cfg(tx) : null;
+ // Only new rows are gated; owner-tier writers (tool_observed and above) never are, so they read no gate config.
+ let trust: WriteTrust | null = null;
+ const writerTrust = async (db: BrainEngine) => trust ??= await currentWriteTrust(db) ?? { tier: 'unknown', origin: null };
+ const cfg = rows.some(r => !occupied.has(r.row_num)) && compareTrust((await writerTrust(tx)).tier, 'tool_observed') < 0 ? await input.cfg(tx) : null;
// Only a row this write inserts at a guarded row's old position replaces it; a moved row never does.
const fresh = new Set(rows.filter(r => !occupied.has(r.row_num)).map(r => r.row_num));
for (const row of rows) {
if (!cfg || occupied.has(row.row_num)) { inserted.push(row); continue; }
const decision = decideFactWrite({ fact: row.fact, context: row.context ?? null, source: row.source ?? null }, { sourceId, slug,
payload: { fact: row.fact, kind: row.kind, visibility: row.visibility, entity_slug: row.entity_slug, source: row.source, context: row.context ?? null, row_num: row.row_num },
- input: gateInput(trust, null), cfg });
+ input: gateInput(await writerTrust(tx), null), cfg });
if (decision.action === 'hold') { await recordWriteGateHold(tx, decision.hold!); continue; }
if (decision.action === 'reject') continue;
inserted.push(row);
@@ -95,7 +98,7 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
newTier: storedTrustTier(replacement.trust_tier), guard: 'fence_projection' })).proposal_ref);
} else {
const { id } = await insertTrustProposal(db, { action: 'forget', sourceId, target: { table: 'facts', id: Number(g.id) }, proposer: 'fence_projection',
- before: { guard: 'fence_projection', fact: { id: Number(g.id), tier: storedTrustTier(g.trust_tier) }, writer_tier: trust.tier, slug } });
+ before: { guard: 'fence_projection', fact: { id: Number(g.id), tier: storedTrustTier(g.trust_tier) }, writer_tier: (await writerTrust(db)).tier, slug } });
refs.push(`tp${id}`);
}
}