Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): purged_content stays typed on receipts and the verb path; journals keep no purged text (outcomes redacted, refused or no-op writes carrying purged content drop their intent)

garrytand045ec7925a7
diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.ts
index 211e2e74e6..39e130907a 100644
--- a/src/core/persistence/intent-redaction.ts
+++ b/src/core/persistence/intent-redaction.ts
@@ -25,18 +25,29 @@ import { isTerminal, principalKey, requestPrincipal, type WriteRequest } from '.
export interface IntentRedactionTarget { id: string; principal_kind: string; principal_id: string }
-/** Requests in `sourceId` whose stored intent or error text carries `claim`, bounded. Owner-only; never returns the text. */
+/**
+ * Requests in `sourceId` whose stored intent, outcome or error text carries `claim`, bounded, compacted
+ * ones included (compaction keeps the outcome). Owner-only; never returns the text.
+ */
export async function findRequestsCarrying(engine: BrainEngine, sourceId: string, claim: string, limit = 10_000): Promise<IntentRedactionTarget[]> {
const needle = claim.toLowerCase();
// The claim as it appears inside a JSON string (quotes and backslashes escaped), lowercased.
const jsonNeedle = JSON.stringify(claim).slice(1, -1).toLowerCase();
+ const carries = (column: string) => `(${column} IS NOT NULL AND (strpos(lower(${column}::text),$2)>0 OR strpos(lower(${column}::text),$3)>0))`;
return engine.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id,principal_kind,principal_id FROM persistence_requests
- WHERE source_id=$1 AND NOT compacted AND (
- (intent IS NOT NULL AND (strpos(lower(intent::text),$2)>0 OR strpos(lower(intent::text),$3)>0))
- OR (error_message IS NOT NULL AND strpos(lower(error_message),$2)>0))
+ WHERE source_id=$1 AND (${carries('intent')} OR ${carries('outcome')} OR ${carries('error_detail')} OR ${carries('error_message')})
ORDER BY sequence LIMIT $4`, [sourceId, needle, jsonNeedle, limit]);
}
+/** Replace every JSON string that carries one of `needles` (case-insensitive) with "[purged]"; structure and other values stay. */
+export function redactJson<T>(value: T, needles: readonly string[]): T {
+ const lowered = needles.map(n => n.toLowerCase()).filter(Boolean);
+ if (!lowered.length || value === null || value === undefined) return value;
+ const walk = (v: unknown): unknown => typeof v === 'string' ? (lowered.some(n => v.toLowerCase().includes(n)) ? '[purged]' : v)
+ : Array.isArray(v) ? v.map(walk) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)])) : v;
+ return walk(value) as T;
+}
+
/** Requests in `sourceId` that target one of `slugs` and still hold an intent (page purge). */
export async function findRequestsForSlugs(engine: BrainEngine, sourceId: string, slugs: readonly string[], limit = 10_000): Promise<IntentRedactionTarget[]> {
return engine.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id,principal_kind,principal_id FROM persistence_requests
@@ -54,7 +65,7 @@ export function redactionCounterKeys(targets: readonly IntentRedactionTarget[]):
* `exclude` is the purge's own request id. Returns the number redacted.
*/
export async function redactRequestIntents(tx: BrainEngine, targets: readonly IntentRedactionTarget[], exclude?: string,
- opts: { skipPending?: boolean } = {}): Promise<number> {
+ opts: { skipPending?: boolean; needles?: readonly string[] } = {}): Promise<number> {
const ids = targets.map(t => t.id).filter(id => id !== exclude);
if (!ids.length) return 0;
await lockCounters(tx, ['brain', ...redactionCounterKeys(targets)]);
@@ -70,12 +81,19 @@ export async function redactRequestIntents(tx: BrainEngine, targets: readonly In
}
let redacted = 0;
for (const current of rows) {
- if (current.compacted || !isTerminal(current) || current.recovery) continue;
+ if (!isTerminal(current) || current.recovery) continue;
+ // The stored outcome stays the replay answer, with every string carrying the claim replaced by "[purged]".
+ const outcome = redactJson(current.outcome, opts.needles ?? []);
+ const detail = redactJson(current.error_detail, opts.needles ?? []);
+ if (current.compacted && JSON.stringify(outcome) === JSON.stringify(current.outcome) && JSON.stringify(detail) === JSON.stringify(current.error_detail)
+ && current.error_message === null) continue;
const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes
FROM persistence_effects WHERE request_id=$1::uuid`, [current.id]);
- const retained = Math.min(Number(current.terminal_reservation), jsonBytes(current.authority) + jsonBytes(current.outcome ?? {})
- + (current.error_detail ? jsonBytes(current.error_detail) : 0) + Number(effects.bytes) + 1024);
- await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid', [current.id, retained]);
+ const retained = Math.min(Number(current.terminal_reservation), jsonBytes(current.authority) + jsonBytes(outcome ?? {})
+ + (detail ? jsonBytes(detail) : 0) + Number(effects.bytes) + 1024);
+ await tx.executeRaw(`UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2,
+ outcome=$3::text::jsonb,error_detail=$4::text::jsonb WHERE id=$1::uuid`,
+ [current.id, retained, outcome == null ? null : JSON.stringify(outcome), detail == null ? null : JSON.stringify(detail)]);
for (const key of ['brain', principalKey(requestPrincipal(current))]) {
await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-$2 WHERE key=$1', [key, Number(current.terminal_reservation) - retained]);
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 9a918610f7..efdf95136a 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -10,6 +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 { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
@@ -593,9 +594,17 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
SELECT * 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');
+ // #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)) {
+ const [redacted] = await tx.executeRaw<WriteRequest>('UPDATE persistence_requests SET intent=NULL,compacted=true WHERE id=$1::uuid RETURNING *', [row.id]);
+ return redacted ?? done;
+ }
// Recovery bytes remain reserved until physical cleanup has been verified.
return done;
}
+const PURGED_REFUSAL = /^purged_content:|which the owner purged; it was not imported\.$/;
/**
* `known` is the row a publication just completed, passed while it still
diff --git a/src/core/persistence/purged-intent.ts b/src/core/persistence/purged-intent.ts
new file mode 100644
index 0000000000..a23cff6a48
--- /dev/null
+++ b/src/core/persistence/purged-intent.ts
@@ -0,0 +1,45 @@
+/**
+ * #5575: does a failed write's stored intent carry purged content? A write
+ * refused for any reason (a permission or revision refusal arrives before the
+ * purge guards run), or committed as a no-op after the purge overlay dropped
+ * the purged rows, must not keep a copy of content the owner purged, so
+ * `completeWrite` nulls the intent of a terminal request when this says yes.
+ *
+ * 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.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { parseMarkdown } from '../markdown.ts';
+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> {
+ 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;
+ 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;
+ const claims = [intent.fact, intent.claim].filter((c): c is string => typeof c === 'string' && !!c.trim()).map(claim => ({ claim, subject }));
+ let parsed: ReturnType<typeof parseMarkdown> | null = null;
+ try { parsed = content ? parseMarkdown(content, `${row.slug}.md`) : null; } catch { parsed = null; }
+ if (parsed) for (const body of [parsed.compiled_truth, parsed.timeline ?? '']) claims.push(...parseFactsFence(body).facts.map(f => ({ claim: f.claim, subject: row.slug })));
+ if (has.facts && claims.length) {
+ const hit = await tx.executeRaw(`SELECT 1 FROM fact_purges p JOIN jsonb_to_recordset($2::text::jsonb) AS c(claim text, subject text)
+ ON p.fact_hash=gbrain_fact_fingerprint(c.claim) AND (p.subject='*' OR p.subject=c.subject) WHERE p.source_id=$1 LIMIT 1`,
+ [row.source_id, JSON.stringify(claims.slice(0, 1000))]);
+ if (hit.length) return true;
+ }
+ if (has.pages && parsed) {
+ const hit = await tx.executeRaw('SELECT 1 FROM page_purges WHERE source_id=$1 AND content_hash=$2 LIMIT 1', [row.source_id, contentHash(parsed)]);
+ if (hit.length) return true;
+ }
+ return false;
+}
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index 7378d7435b..262faa4aa5 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -18,7 +18,7 @@ export const WRITE_ERROR_CODES = [
'connector_account_changed', 'connector_intent_outdated', 'checkpoint_validation_timeout',
'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline',
'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
- 'timeline_rows_would_be_removed',
+ 'timeline_rows_would_be_removed', 'purged_content',
] as const;
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 216481ba56..34edff317c 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -105,12 +105,17 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
// #6188 (UC3): a company-brain source names the fence correction it will not write; the repository commit is the fix.
if (code === 'source_writeback_required' && message?.startsWith('Canonical preparation would normalize a facts or takes fence (')) return { reason: code, message,
suggestion: 'A company-brain source never rewrites repository files: fix the named fence in the repository, commit it, and resume the sync.' };
+ // #5575: a purged claim or page content is refused for good; the owner alone can clear its tombstone.
+ if (code === 'purged_content') return { reason: code, message: 'This content was purged from this source and cannot be saved again.',
+ suggestion: PURGED_SUGGESTION };
const replaces = code === 'invalid_params' ? REPLACES_REFUSAL.exec(message ?? '') : null;
if (replaces) return { reason: code, message: message!, suggestion: REPLACES_SUGGESTION[replaces[1]!]! };
return { reason: isWriteErrorCode(code) ? code : 'storage_error', message: 'The write did not commit. Inspect its durable request on the source host.',
suggestion: 'Resolve the reported write failure before starting a corrected attempt.' };
}
+const PURGED_SUGGESTION = 'Do not retry the same content. If it is still true, write it in new words; only the owner can clear a purge tombstone on the brain host.';
+
/** `remember.replaces` refusals decided under the target row lock keep their code and next step. */
const REPLACES_REFUSAL = /^(target_superseded|target_withdrawn|target_expired|replaces_entity_mismatch|replaces_cross_page|replaces_duplicate): /;
const REPLACES_SUGGESTION: Record<string, string> = {
@@ -133,6 +138,12 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
if (error.canonicalCode === 'invalid_fence') Object.assign(frozen, { reason: error.reason, fence: error.fence, fenceIssues: error.fenceIssues });
throw frozen;
}
+ // #5575: the frozen wire code stays invalid_params; the envelope's canonical code is purged_content.
+ if ((error.canonical ?? error.code) === 'purged_content') {
+ const purged = verbError('invalid_params', error.message, error.suggestion ?? PURGED_SUGGESTION);
+ purged.canonical = 'purged_content'; purged.writeError = 'purged_content';
+ throw purged;
+ }
const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)
? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)
? 'invalid_params' : 'unavailable';
@@ -151,7 +162,7 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorC
: receipt.state === 'conflict' ? 'revision_conflict'
: receipt.state === 'cancelled' ? 'cancelled' : 'storage_error');
const code = ['source_changed','permission_denied','scope_denied','writer_registration_required'].includes(writeError) ? 'scope_denied'
- : ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed'].includes(writeError) || writeError.startsWith('core_')
+ : ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed','purged_content'].includes(writeError) || writeError.startsWith('core_')
? 'invalid_params' : 'unavailable';
const diagnostic = writeFailureDiagnostic(writeError, message);
const suggestion = pending
@@ -163,6 +174,7 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorC
pending ? 'The write is accepted and awaiting completion; it is not committed.' : diagnostic.message,
suggestion);
if (!pending) error.detail = diagnostic.reason;
+ if (writeError === 'purged_content') error.canonical = 'purged_content';
error.writeError = writeError;
error.writeRequest = receipt;
return error;