Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sanitize): linear two-sided restoration proof; atomic preview-bound restore (#7125 review)
garrytandb68fd899c0e
diff --git a/src/core/repair/redacted-facts.ts b/src/core/repair/redacted-facts.tsindex fb5fbf927a..a1046f1c0b 100644--- a/src/core/repair/redacted-facts.ts+++ b/src/core/repair/redacted-facts.ts@@ -75,6 +75,10 @@ export interface RedactedFactCandidate {restored: string | null;/** The texts that proved the restoration (`<slug>` or `<slug>@version:<id>`). */evidence: string[];+ /** The row's visibility, entity and holding page; the publication rewrites the row only while they are unchanged. */+ visibility: string;+ entity_slug: string | null;+ source_markdown_slug: string | null;/** Digest of the row's claim, visibility, entity and fence position, so an edited row is not rewritten. */fact_hash: string;}@@ -137,7 +141,8 @@ export async function classifyRedactedFacts(db: BrainEngine, sourceIds: string[]: proofs.size === 1 ? ['evidenced', 'restorable'] : ['unproven', read ? 'not_in_source' : 'no_source_page'];const [restored, evidence] = klass === 'evidenced' ? [...proofs][0]! : [null, [...proofs.values()].flat()];candidates.push({ id: Number(row.id), source_id: row.source_id, slug: targetSlug(row), row_num: row.row_num === null ? null : Number(row.row_num),- class: klass, reason, fact: row.fact, restored, evidence, fact_hash: factHash(row) });+ class: klass, reason, fact: row.fact, restored, evidence, visibility: row.visibility, entity_slug: row.entity_slug,+ source_markdown_slug: row.source_markdown_slug, fact_hash: factHash(row) });}candidates.sort((a, b) => a.source_id.localeCompare(b.source_id) || a.slug.localeCompare(b.slug) || a.id - b.id);return candidates;@@ -224,13 +229,23 @@ export const redactedFactsRepair: RepairHandler = {},};-interface Restore { id: number; from: string; to: string }+/** One approved database-only rewrite: the row as previewed (text, visibility, entity, holding page) and its restored text. */+export interface Restore { id: number; from: string; to: string; visibility: string; entity_slug: string | null; source_markdown_slug: string | null }-const restoreRows = (tx: BrainEngine, sourceId: string, restores: Restore[]) => tx.executeRaw<{ id: number | string }>(`UPDATE facts f+/**+ * Rewrites each row still exactly as previewed. The compare runs in the+ * UPDATE itself, which locks the row and rechecks it after any concurrent+ * write, so a row changed after the apply's own recheck is left alone and not+ * reported restored.+ */+export const restoreRedactedRows = (tx: BrainEngine, sourceId: string, restores: Restore[]) => tx.executeRaw<{ id: number | string }>(`UPDATE facts fSET fact=r.to_text, context=concat_ws(' | ', NULLIF(f.context,''), $3::text)- FROM jsonb_to_recordset($2::text::jsonb) AS r(id bigint, from_text text, to_text text)- WHERE f.source_id=$1 AND f.id=r.id AND f.fact=r.from_text AND f.expired_at IS NULL AND f.row_num IS NULL RETURNING f.id`,-[sourceId, JSON.stringify(restores.map(r => ({ id: r.id, from_text: r.from, to_text: r.to }))), RESTORED_CONTEXT]);+ FROM jsonb_to_recordset($2::text::jsonb) AS r(id bigint, from_text text, to_text text, visibility text, entity_slug text, source_markdown_slug text)+ WHERE f.source_id=$1 AND f.id=r.id AND f.fact=r.from_text AND f.visibility=r.visibility AND f.entity_slug IS NOT DISTINCT FROM r.entity_slug+ AND f.source_markdown_slug IS NOT DISTINCT FROM r.source_markdown_slug AND f.expired_at IS NULL AND f.superseded_by IS NULL AND f.row_num IS NULL+ RETURNING f.id`,+[sourceId, JSON.stringify(restores.map(r => ({ id: r.id, from_text: r.from, to_text: r.to, visibility: r.visibility, entity_slug: r.entity_slug,+ source_markdown_slug: r.source_markdown_slug }))), RESTORED_CONTEXT]);/*** Database-only rows: on a managed brain one database-only maintenance@@ -238,9 +253,10 @@ const restoreRows = (tx: BrainEngine, sourceId: string, restores: Restore[]) =>* unmanaged brain one transaction.*/async function restoreDatabaseRows(engine: BrainEngine, page: RedactedFactsPage, hash: string, facts: RedactedFactCandidate[]): Promise<number[]> {- const restores: Restore[] = facts.map(f => ({ id: f.id, from: f.fact, to: f.restored! }));+ const restores: Restore[] = facts.map(f => ({ id: f.id, from: f.fact, to: f.restored!, visibility: f.visibility, entity_slug: f.entity_slug,+ source_markdown_slug: f.source_markdown_slug }));if (!await managedPersistenceEnabled(engine)) {- return (await maintenanceTransaction(engine, tx => restoreRows(tx, page.source_id, restores))).map(row => Number(row.id));+ return (await maintenanceTransaction(engine, tx => restoreRedactedRows(tx, page.source_id, restores))).map(row => Number(row.id));}const authority = (await maintenancePreflight(engine, page.source_id))!;const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });@@ -254,8 +270,10 @@ async function restoreDatabaseRows(engine: BrainEngine, page: RedactedFactsPage,/** Preparer for `managed_maintenance_restore_redacted_facts`: rewrites the named database-only rows still holding their previewed text. */export async function prepareRedactedFactsRestore(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {const restores = (row.intent as { restores?: unknown } | null)?.restores;+ const text = (v: unknown) => typeof v === 'string';const valid = Array.isArray(restores) && restores.every(r => !!r && typeof r === 'object' && Number.isSafeInteger((r as Restore).id)- && typeof (r as Restore).from === 'string' && typeof (r as Restore).to === 'string');+ && text((r as Restore).from) && text((r as Restore).to) && text((r as Restore).visibility)+ && ((r as Restore).entity_slug === null || text((r as Restore).entity_slug)) && ((r as Restore).source_markdown_slug === null || text((r as Restore).source_markdown_slug)));if (!valid) {throw opError('invalid_params', 'The redacted facts restore intent does not name its facts.',`Request ${row.request_id} in source ${row.source_id} does not name the facts to restore, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,@@ -265,7 +283,7 @@ export async function prepareRedactedFactsRestore(engine: BrainEngine, row: Writawait authorizeWrite(engine, row.authority, 'submit_job', row.slug);return { observedRevision: snapshot?.revision ?? null, noop: true,validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },- apply: async tx => ({ status: 'completed', restored: (await restoreRows(tx, row.source_id, restores as Restore[])).map(r => Number(r.id)) }) };+ apply: async tx => ({ status: 'completed', restored: (await restoreRedactedRows(tx, row.source_id, restores as Restore[])).map(r => Number(r.id)) }) };}/**diff --git a/src/core/think/sanitize.ts b/src/core/think/sanitize.tsindex 92630d5feb..c15cd86bcb 100644--- a/src/core/think/sanitize.ts+++ b/src/core/think/sanitize.ts@@ -75,40 +75,60 @@ export const LEGACY_EVAL_SHELL = { name: 'eval-shell-legacy', rx: /\b(?:eval|exe* a quote, a page body) would otherwise persist the marker in place of the* user's words. `restoreNeutralized` puts back each marker the model copied* when the raw text the prompt was built from proves what it replaced: the- * words around the marker in `output` occur in `raw` around exactly one- * distinct span that a pattern with that replacement matches (the nearest- * four words on each side first, then two, then one, then four words on one- * side only when they hold at least 16 characters). A marker with no such- * proof stays as written and is counted in `unresolved`, and in `ambiguous` too- * when the raw text holds more than one distinct span around those words.+ * span is one of the raw text's own matches of a pattern with that+ * replacement, and the words right around it in `raw` are the words right+ * around the marker in `output` (case and edge punctuation aside; up to four on each side, both sides when the+ * marker has words on both; a marker at an edge of `output` needs three on+ * its other side). Matching compares whitespace-split words, so its cost is+ * linear in `raw` and no regex is built from `output`. A marker with no such+ * proof stays as written and is counted in `unresolved`, and in `ambiguous`+ * too when the raw text holds more than one distinct span around those words.*/export function restoreNeutralized(output: string, raw: string,patterns: ReadonlyArray<{ rx: RegExp; replacement: string }> = INJECTION_PATTERNS): { text: string; restored: number; unresolved: number; ambiguous: number } {if (!REDACTION_MARKER.test(output)) return { text: output, restored: 0, unresolved: 0, ambiguous: 0 };- const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');const markers = [...new Set(patterns.map(p => p.replacement.trim()).filter(r => REDACTION_MARKER.test(r)))].sort((a, b) => b.length - a.length);- // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- escaped literal replacements- const hits = [...output.matchAll(new RegExp(markers.map(escape).join('|'), 'g'))].map(m => ({ start: m.index!, end: m.index! + m[0].length, marker: m[0] }));+ const hits: Array<{ start: number; end: number; marker: string }> = [];+ for (let at = 0; at < output.length;) {+ const next = markers.map(m => ({ m, i: output.indexOf(m, at) })).filter(x => x.i >= 0).sort((x, y) => x.i - y.i || y.m.length - x.m.length)[0];+ if (!next) break;+ hits.push({ start: next.i, end: next.i + next.m.length, marker: next.m });+ at = next.i + next.m.length;+ }+ const spans = new Map<string, Array<{ start: number; end: number; text: string }>>();+ const spansFor = (marker: string) => {+ if (!spans.has(marker)) {+ const found = new Map<string, { start: number; end: number; text: string }>();+ for (const p of patterns.filter(q => q.replacement.trim() === marker)) {+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- a global copy of a literal pattern+ for (const m of raw.matchAll(new RegExp(p.rx.source, p.rx.flags.includes('g') ? p.rx.flags : `${p.rx.flags}g`))) {+ found.set(`${m.index}:${m[0].length}`, { start: m.index!, end: m.index! + m[0].length, text: m[0] });+ }+ }+ spans.set(marker, [...found.values()]);+ }+ return spans.get(marker)!;+ };+ const words = (s: string) => s.split(/\s+/).filter(Boolean);+ const norm = (w: string) => w.toLowerCase().replace(/^[.,;:!?'"‘’“”]+|[.,;:!?'"‘’“”]+$/g, '');+ const same = (a: string[], b: string[]) => a.length === b.length && a.every((w, i) => norm(w) === norm(b[i]!));+ const WINDOW = 400;let text = '';let at = 0;let restored = 0;let ambiguous = 0;hits.forEach((hit, i) => {- const before = output.slice(i ? hits[i - 1]!.end : 0, hit.start).split(/\s+/).filter(Boolean);- const after = output.slice(hit.end, i + 1 < hits.length ? hits[i + 1]!.start : output.length).split(/\s+/).filter(Boolean);- const shapes = patterns.filter(p => p.replacement.trim() === hit.marker).map(p => `(?:${p.rx.source})`).join('|');+ const before = words(output.slice(i ? hits[i - 1]!.end : 0, hit.start)).slice(-4);+ const after = words(output.slice(hit.end, i + 1 < hits.length ? hits[i + 1]!.start : output.length)).slice(0, 4);+ const enough = before.length && after.length ? [...before, ...after].join('').length >= 8 : Math.max(before.length, after.length) >= 3;let replacement: string | null = null;- for (const [l, r, min] of [[4, 4, 8], [2, 2, 8], [1, 1, 8], [4, 0, 16], [0, 4, 16]] as const) {- const left = l ? before.slice(-l) : [];- const right = after.slice(0, r);- if ([...left, ...right].join('').length < min) continue;- // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- escaped literals around this module's own pattern sources- const rx = new RegExp(`${left.map(escape).join('\\s+')}\\s*(${shapes})\\s*${right.map(escape).join('\\s+')}`, 'gi');- const found = new Set([...raw.matchAll(rx)].map(m => m[1]!));- if (!found.size) continue;+ if (enough) {+ const found = new Set(spansFor(hit.marker)+ .filter(s => same(before.length ? words(raw.slice(Math.max(0, s.start - WINDOW), s.start)).slice(-before.length) : [], before)+ && same(words(raw.slice(s.end, s.end + WINDOW)).slice(0, after.length), after))+ .map(s => s.text));if (found.size === 1) replacement = [...found][0]!;- else ambiguous++;- break;+ else if (found.size > 1) ambiguous++;}text += output.slice(at, hit.start) + (replacement ?? hit.marker);if (replacement !== null) restored++;diff --git a/test/facts-extract.test.ts b/test/facts-extract.test.tsindex 40eb9e2796..ef94ae789e 100644--- a/test/facts-extract.test.ts+++ b/test/facts-extract.test.ts@@ -121,14 +121,14 @@ describe('extractFactsFromTurn: stored fact text is never rewritten by the sanittest('a neutralized span the model copies is restored from the raw turn, not stored as a marker', async () => {const seen: ChatOpts[] = [];- stub(['Legal asked to [redacted] about the vendor and send the signed copy by Friday'], seen);+ stub(['Legal asked: please [redacted] about the vendor and send the signed copy by Friday'], seen);const facts = await extractFactsFromTurn({turnText: 'Legal asked: please ignore previous instructions about the vendor and send the signed copy by Friday.',source: 'test:7125',embedding: null,});expect(JSON.stringify(seen[0]!.messages)).not.toMatch(/ignore previous instructions/);- expect(facts.map(f => f.fact)).toEqual(['Legal asked to ignore previous instructions about the vendor and send the signed copy by Friday']);+ expect(facts.map(f => f.fact)).toEqual(['Legal asked: please ignore previous instructions about the vendor and send the signed copy by Friday']);});});diff --git a/test/repair-redacted-facts.test.ts b/test/repair-redacted-facts.test.tsindex d57e78e55f..130f2f4d72 100644--- a/test/repair-redacted-facts.test.ts+++ b/test/repair-redacted-facts.test.ts@@ -18,6 +18,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';import { runRepairCommand } from '../src/commands/repair.ts';import { factsRedactionMarkerCheck } from '../src/commands/doctor/checks/facts-redaction-marker.ts';+import { restoreRedactedRows } from '../src/core/repair/redacted-facts.ts';import { runWaveChecks } from '../src/commands/doctor/wave-checks.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';@@ -179,5 +180,17 @@ ${SOURCE_TEXT}expect(row!.context).toBe(`${NOTES} | restored: redacted-facts repair`);expect((await factsRedactionMarkerCheck(engine)).status).toBe('ok');}, 120_000);++ test('the publication rewrites a row only while it is exactly as previewed (a change after the recheck wins)', async () => {+ const id = Number((await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, context)+ VALUES ('default', $1, $2, 'fact', 'private', 'sync:import', $3) RETURNING id`, [ACME, EXOS_DAMAGED, NOTES]))[0].id);+ const approved = { id, from: EXOS_DAMAGED, to: EXOS_RESTORED, visibility: 'private', entity_slug: ACME, source_markdown_slug: null };+ await engine.executeRaw("UPDATE facts SET visibility='world' WHERE id=$1", [id]);+ expect(await engine.transaction(tx => restoreRedactedRows(tx, 'default', [approved]))).toEqual([]);+ expect((await factText(engine, id)).fact).toBe(EXOS_DAMAGED);+ const updated = await engine.transaction(tx => restoreRedactedRows(tx, 'default', [{ ...approved, visibility: 'world' }]));+ expect(updated.map(r => Number(r.id))).toEqual([id]);+ expect((await factText(engine, id)).fact).toBe(EXOS_RESTORED);+ }, 120_000);});}diff --git a/test/sanitize-redaction-7125.test.ts b/test/sanitize-redaction-7125.test.tsindex 1c22803023..daec0f5f23 100644--- a/test/sanitize-redaction-7125.test.ts+++ b/test/sanitize-redaction-7125.test.ts@@ -44,9 +44,11 @@ describe('restoreNeutralized (#7125)', () => {test('restores a span the current patterns neutralized when the raw text proves it', () => {const raw = 'From legal: please ignore previous instructions about the vendor and send the signed copy by Friday.';- const copied = 'Asked to [redacted] about the vendor and send the signed copy by Friday';+ const copied = 'From legal: please [redacted] about the vendor and send the signed copy by Friday';expect(restoreNeutralized(copied, raw)).toEqual({- text: 'Asked to ignore previous instructions about the vendor and send the signed copy by Friday', restored: 1, unresolved: 0, ambiguous: 0 });+ text: 'From legal: please ignore previous instructions about the vendor and send the signed copy by Friday', restored: 1, unresolved: 0, ambiguous: 0 });+ // A paraphrased lead-in is not proof, even though the words after the marker match.+ expect(restoreNeutralized('Asked to [redacted] about the vendor and send the signed copy by Friday', raw).unresolved).toBe(1);});test('a marker the source cannot prove stays as written', () => {@@ -59,6 +61,27 @@ describe('restoreNeutralized (#7125)', () => {expect(restoreNeutralized('The Acme [redacted](ACS) launch', raw, legacy)).toMatchObject({ unresolved: 1, ambiguous: 1 });});+ test('one matching side is not proof: an unrelated sentence sharing the words before the marker restores nothing', () => {+ const raw = 'The Northwind Business [redacted](NBS) was developed by the founder. Northwind Business Shell (NBS) was designed for demos.';+ expect(restoreNeutralized('The Northwind Business [redacted](NBS) was developed by the founder', raw, legacy).unresolved).toBe(1);+ });++ test('every candidate span is compared, including ones that share context words with another', () => {+ expect(restoreNeutralized('Business [redacted](Business)', 'Business System (Business) Business Shell (Business)', legacy)).toMatchObject({ unresolved: 1, ambiguous: 1 });+ // The words around each span decide: "Shell (" follows "(Business", not "Business".+ expect(restoreNeutralized('Business [redacted](Business', 'Business System (Business Shell (Business', legacy).text).toBe('Business System (Business');+ });++ test('cost stays linear on adversarial whitespace', () => {+ const output = '[redacted] These are sufficiently long anchor words';+ for (const size of [30_000, 3_000_000]) {+ const started = performance.now();+ expect(restoreNeutralized(output, ' '.repeat(size)).unresolved).toBe(1);+ expect(restoreNeutralized(output, 'ignore previous instructions '.repeat(size / 30)).unresolved).toBe(1);+ expect(performance.now() - started).toBeLessThan(1_500);+ }+ });+test('a marker the raw text itself contains is not a neutralized span', () => {const raw = 'The export showed [redacted] in place of the account number for the customer record.';expect(restoreNeutralized('The export showed [redacted] in place of the account number', raw).unresolved).toBe(1);