Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(facts): parse and render the entity fence once per managed fact publication (#6898)
garrytan6a4af9f44978
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex 8466d9de75..0efbdb6b7c 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -594,6 +594,11 @@ export function factsGapWarning(`dropped by a caller who never saw them, they are now lost.`;}+export type NewFactRow = Omit<ParsedFact, 'rowNum' | 'active' | 'supersededBy' | 'forgotten'> & {+ rowNum?: number;+ active?: boolean;+};+/*** Append a new fact row to the body. If a fenced facts table exists, the* row is added to the end of it. If not, a new `## Facts` section + fence@@ -604,45 +609,78 @@ export function factsGapWarning(* the same row. Throws `FenceRewriteRefusal` when the existing fence does* not parse cleanly: re-rendering it would drop the rows the parser skipped.*/-export function upsertFactRow(- body: string,- newRow: Omit<ParsedFact, 'rowNum' | 'active' | 'supersededBy' | 'forgotten'> & {- rowNum?: number;- active?: boolean;- },-): { body: string; rowNum: number } {+export function upsertFactRow(body: string, newRow: NewFactRow): { body: string; rowNum: number } {const parsed = parseFactsFence(body);assertFenceRewritable('facts', parsed);const { facts } = parsed;const nextRowNum = newRow.rowNum?? (facts.length > 0 ? Math.max(...facts.map(f => f.rowNum)) + 1 : 1);+ return { body: replaceOrInsertFactsFence(body, renderFactsTable([...facts, factRow(newRow, nextRowNum)])), rowNum: nextRowNum };+}- const allRows: ParsedFact[] = [- ...facts,- {- rowNum: nextRowNum,- claim: newRow.claim,- kind: newRow.kind,- confidence: newRow.confidence,- visibility: newRow.visibility,- notability: newRow.notability,- validFrom: newRow.validFrom,- validUntil: newRow.validUntil,- source: newRow.source,- context: newRow.context,- active: newRow.active ?? true,- // v0.35.4 — typed-claim pass-through. When undefined the renderer- // stays at the 10-cell shape so unrelated edits don't widen the- // fence.- claimMetric: newRow.claimMetric,- claimValue: newRow.claimValue,- claimUnit: newRow.claimUnit,- claimPeriod: newRow.claimPeriod,- ...(newRow.attributedTo ? { attributedTo: newRow.attributedTo } : {}),- },- ];+function factRow(newRow: NewFactRow, rowNum: number): ParsedFact {+ return {+ rowNum,+ claim: newRow.claim,+ kind: newRow.kind,+ confidence: newRow.confidence,+ visibility: newRow.visibility,+ notability: newRow.notability,+ validFrom: newRow.validFrom,+ validUntil: newRow.validUntil,+ source: newRow.source,+ context: newRow.context,+ active: newRow.active ?? true,+ // v0.35.4 — typed-claim pass-through. When undefined the renderer+ // stays at the 10-cell shape so unrelated edits don't widen the+ // fence.+ claimMetric: newRow.claimMetric,+ claimValue: newRow.claimValue,+ claimUnit: newRow.claimUnit,+ claimPeriod: newRow.claimPeriod,+ ...(newRow.attributedTo ? { attributedTo: newRow.attributedTo } : {}),+ };+}- return { body: replaceOrInsertFactsFence(body, renderFactsTable(allRows)), rowNum: nextRowNum };+/**+ * #6898 follow-up: upsertFactRow and strikeFactRowInPage for a whole batch of+ * rows, with the section's fence parsed once (at the first append, which+ * throws FenceRewriteRefusal exactly where upsertFactRow would) and rendered+ * once by `page()`. A publication of N facts on a fence of M rows costs+ * O(N + M) instead of re-parsing and re-rendering the whole fence per row+ * (O(N × M): minutes on a fence of thousands of rows). The page it returns is+ * the page the one-row-at-a-time calls leave.+ */+export function factsFenceEditor<T extends { compiled_truth: string; timeline: string }>(page: T, section: 'compiled_truth' | 'timeline') {+ let current = page;+ let rows: ParsedFact[] | null = null;+ return {+ append(newRow: NewFactRow & { rowNum: number }): void {+ if (!rows) {+ const parsed = parseFactsFence(current[section]);+ assertFenceRewritable('facts', parsed);+ rows = parsed.facts;+ }+ rows.push(factRow(newRow, newRow.rowNum));+ },+ strike(rowNum: number, by: number): void {+ const struck = (f: ParsedFact): ParsedFact => f.rowNum === rowNum ? { ...f, active: false, supersededBy: by, context: `superseded by #${by}` } : f;+ for (const key of ['compiled_truth', 'timeline'] as const) {+ if (key === section && rows) {+ if (!rows.some(f => f.rowNum === rowNum)) continue;+ rows = rows.map(struck);+ return;+ }+ const found = parseFactsFence(current[key]).facts;+ if (!found.some(f => f.rowNum === rowNum)) continue;+ current = { ...current, [key]: replaceOrInsertFactsFence(current[key], renderFactsTable(found.map(struck))) };+ return;+ }+ },+ page(): T {+ return rows ? { ...current, [section]: replaceOrInsertFactsFence(current[section], renderFactsTable(rows)) } : current;+ },+ };}/**diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex dd42eca61d..75541ac135 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -5,7 +5,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';-import { factsFenceSection, parseFactsFence, strikeFactRowInPage, upsertFactRow, formatFenceDate } from '../facts-fence.ts';+import { factsFenceEditor, factsFenceSection, parseFactsFence, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { assertInlineBody } from '../page-body/page-shape.ts';import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';@@ -153,7 +153,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ// #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.const fenced = { compiled_truth: target?.page.compiled_truth ?? '', timeline: target?.page.timeline ?? '' };const section = factsFenceSection(fenced);- let next = { ...fenced };+ // #6898 follow-up: the fence is parsed once and rendered once for the whole group, not once per fact.+ const fence = factsFenceEditor(fenced, section);const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);let nextRow = Math.max(maximum?.n ?? 0, ...[fenced.compiled_truth, fenced.timeline].flatMap(text => parseFactsFence(text).facts.map(fact => fact.rowNum))) + 1;const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate; gate?: GatedRowDecision }> = [];@@ -188,19 +189,20 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (gate && gate.action !== 'insert') { blocked.push(gate); continue; }const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;// #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.- if (rowNum !== undefined) next = { ...next, [section]: refuseUnparsedRewrite(next, row.slug, row.source_id, () => upsertFactRow(next[section], {+ if (rowNum !== undefined) refuseUnparsedRewrite(fenced, row.slug, row.source_id, () => fence.append({rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,claimMetric: fact.claim_metric ?? undefined, claimValue: fact.claim_value ?? undefined,claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined,- ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }).body) };+ ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }));// Strike the superseded row in this page's fence, as the remember mutation does (#6686: in the section that holds it).if (supersedes && rowNum !== undefined && supersedes.source_markdown_slug === row.slug && supersedes.row_num != null) {- next = strikeFactRowInPage(next, Number(supersedes.row_num), rowNum);+ fence.strike(Number(supersedes.row_num), rowNum);}entries.push({ fact, duplicateId: null, rowNum, supersedes, gate });}+ const next = fence.page();const canonicalFacts = extractFactsFromFenceText(parseFactsFence(next[section]).facts, row.slug, row.source_id);for (const entry of entries) {if (entry.rowNum === undefined) continue;diff --git a/test/facts-fence-editor-6898.test.ts b/test/facts-fence-editor-6898.test.tsnew file mode 100644index 0000000000..5d73699349--- /dev/null+++ b/test/facts-fence-editor-6898.test.ts@@ -0,0 +1,86 @@+/**+ * #6898 follow-up: factsFenceEditor is upsertFactRow + strikeFactRowInPage for+ * a whole batch, parsed and rendered once.+ *+ * Protects: for every page shape the managed fact preparer meets (an existing+ * fence, typed claims, attribution, pipes and odd spacing in cells, no fence+ * yet, a fence below the timeline sentinel, strikes in the edited section and+ * in the other one, an unparsable fence) the editor leaves exactly the page+ * the one-row-at-a-time calls leave, and refuses where they refuse.+ */+import { describe, expect, test } from 'bun:test';+import { factsFenceEditor, factsFenceSection, strikeFactRowInPage, upsertFactRow, type NewFactRow } from '../src/core/facts-fence.ts';++type Page = { compiled_truth: string; timeline: string };+type Edit = { row: NewFactRow & { rowNum: number }; strike?: number };++const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';+const fence = (rows: string[]) => `## Facts\n\n<!--- gbrain:facts:begin -->\n${HEADER}\n${rows.join('\n')}\n<!--- gbrain:facts:end -->\n`;+const row = (rowNum: number, claim: string, extra: Partial<NewFactRow> = {}): NewFactRow & { rowNum: number } => ({+ rowNum, claim, kind: 'fact', confidence: 0.9, visibility: 'private', notability: 'medium', validFrom: '2026-01-02', source: 'fixture', ...extra });++function sequential(page: Page, edits: Edit[]): Page {+ const section = factsFenceSection(page);+ let next = { ...page };+ for (const edit of edits) {+ next = { ...next, [section]: upsertFactRow(next[section], edit.row).body };+ if (edit.strike !== undefined) next = strikeFactRowInPage(next, edit.strike, edit.row.rowNum);+ }+ return next;+}+function batched(page: Page, edits: Edit[]): Page {+ const editor = factsFenceEditor(page, factsFenceSection(page));+ for (const edit of edits) {+ editor.append(edit.row);+ if (edit.strike !== undefined) editor.strike(edit.strike, edit.row.rowNum);+ }+ return editor.page();+}++const EXISTING = [+ '| 1 | Founded acme-example | fact | 1.0 | world | high | 2017-01-01 | | chat | |',+ '|2| Lives in Paris |fact|0.8|private|medium|2018-01-01|2020-01-01|chat|moved later|',+ '| 3 | ~~Old title~~ | fact | 1.0 | private | low | 2016-01-01 | | chat | superseded by #1 |',+];+const EDITS: Edit[] = [+ { row: row(4, 'Prefers weekly reports') },+ { row: row(5, 'Moved to Berlin', { context: 'relocation' }), strike: 2 },+ { row: row(6, 'Revenue a | b split', { claimMetric: 'mrr', claimValue: 50000, claimUnit: 'USD', claimPeriod: 'monthly' }) },+ { row: row(7, 'Said the plan works', { attributedTo: 'assistant' }) },+ { row: row(8, 'Replaces the replacement'), strike: 5 },+ { row: row(9, 'Strike of a missing row'), strike: 42 },+];++describe('factsFenceEditor matches one-row-at-a-time upserts', () => {+ const cases: Array<[string, Page]> = [+ ['an existing fence in the body', { compiled_truth: `# Alice\n\nIntro.\n\n${fence(EXISTING)}\nAfter.\n`, timeline: '' }],+ ['no fence yet', { compiled_truth: '# Alice\n\nIntro only.\n', timeline: '' }],+ ['no fence yet, with a timeline', { compiled_truth: '# Alice\n\nIntro.\n', timeline: '- 2026-01-01 met' }],+ ['a lone fence in the timeline', { compiled_truth: '# Alice\n', timeline: `- 2026-01-01 met\n\n${fence(EXISTING)}` }],+ ];+ for (const [name, page] of cases) {+ test(name, () => {+ for (let n = 1; n <= EDITS.length; n++) expect(batched(page, EDITS.slice(0, n))).toEqual(sequential(page, EDITS.slice(0, n)));+ });+ }++ test('a strike in the other section is applied where strikeFactRowInPage applies it', () => {+ const page = { compiled_truth: `# Alice\n\n${fence(['| 1 | Body row | fact | 1.0 | private | medium | 2020-01-01 | | chat | |'])}`,+ timeline: `${fence(['| 2 | Timeline row | fact | 1.0 | private | medium | 2020-01-01 | | chat | |'])}` };+ const edits: Edit[] = [{ row: row(3, 'New'), strike: 2 }, { row: row(4, 'Newer'), strike: 1 }];+ expect(batched(page, edits)).toEqual(sequential(page, edits));+ });++ test('no appended row leaves the page untouched', () => {+ const page = { compiled_truth: `# Alice\n\n${fence(EXISTING)}`, timeline: '' };+ expect(factsFenceEditor(page, 'compiled_truth').page()).toBe(page);+ });++ test('an unparsable fence refuses at the first append, as upsertFactRow does', () => {+ const page = { compiled_truth: `# Alice\n\n${fence([...EXISTING, '| 4 | short row |'])}`, timeline: '' };+ expect(() => upsertFactRow(page.compiled_truth, row(5, 'x'))).toThrow();+ const editor = factsFenceEditor(page, 'compiled_truth');+ expect(() => editor.append(row(5, 'x'))).toThrow(+ (() => { try { upsertFactRow(page.compiled_truth, row(5, 'x')); } catch (e) { return (e as Error).message; } return 'no refusal'; })());+ });+});