Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(conversation-facts): a grammar switch streams the page from its head, so windows of the old grammar never survive
garrytan2e479b2818b7
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.tsindex 16c1dc01ba..7892e9619b 100644--- a/src/core/facts/conversation-incremental.ts+++ b/src/core/facts/conversation-incremental.ts@@ -159,6 +159,18 @@ async function messagesByGrammar(occurrences: Parameters<typeof streamConversatireturn counts;}+/**+ * Whether the run must stream from the page's head instead of reusing the rows before its start: a row there recorded+ * another grammar than the run's (`pattern`; with it undefined, the rows disagree among themselves), or was written under+ * an operator choice that no longer applies. Windows with the same rendered text are reused either way.+ */+function grammarRestart(rows: Array<SegmentDerivationRow | undefined>, pattern: string | null | undefined, choice: string | null | undefined): boolean {+ const outputs = rows.filter((row): row is SegmentDerivationRow => !!row).map(rowOutput);+ if (choice === undefined && outputs.some(o => o.chosen)) return true;+ const grammars = new Set(outputs.map(o => o.pattern ?? null));+ return pattern === undefined ? grammars.size > 1 : [...grammars].some(g => g !== pattern);+}+/*** One segmented page's conversation facts, incrementally (module doc). `gapMinutes` is the page's own* conversation_segment_gap_minutes (null: the default). Returns the end of the newest window it extracted.@@ -206,7 +218,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio: stored?.kind === 'grammar_chosen' && stored.version_token === versionToken ? stored.grammar ?? null : undefined;const choiceReceipt: InputTruncated | null = choice === undefined ? null : { kind: 'grammar_chosen', pipeline: KIND, processed_chars: 0, grammar: choice, version_token: versionToken };if (opts.grammar !== undefined && !run.dryRun) await setExtractionReceipt(engine, page.id, KIND, choiceReceipt);- if (choice !== undefined) from = 0;+ if (choice !== undefined || grammarRestart(liveIds.slice(0, from).map(id => priorRow.get(id)), undefined, choice)) from = 0;let pattern = choice !== undefined ? choice: !opts.redetect && kept.length && 2 * bytesOf(kept) > bytesOf(recorded) && !recorded.some(row => rowOutput(row).chosen) ? rowOutput(kept[0]).pattern ?? null : null;const pinned = choice === undefined && pattern !== null;@@ -223,15 +235,15 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioif (choice === undefined && !pattern && from < liveIds.length) pattern = await detectPagePattern(occurrences, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));if (choice === undefined && !pattern && from < liveIds.length) {if (opts.sinceIso) { result.pages_skipped++; return { newestEnd: null }; }- // No format is detected over the whole page. One that still parses a message here may be the page's (text around a- // transcript can tip the density test) or a quoted part of it, and guessing has deleted current facts: the page is- // held, with no call, nothing published or collected and a detection_ambiguous receipt naming each format's count- // for this page version, until it changes or the operator chooses its format. A page no format parses a message in is not a transcript: it- // settles as non-extractable below and its conversation facts are collected.+ // No format is detected over the whole page. One that still parses a message may be the page's (text around a+ // transcript can tip the density test) or a quoted part of it: the page is held (no call, nothing published or+ // collected, a detection_ambiguous receipt with each format's count for this version) until it changes or the operator+ // chooses. A page no format parses a message in is not a transcript: it settles as non-extractable below, collected.const grammars = await messagesByGrammar(occurrences, { page, gapMinutes: opts.gapMinutes }, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));if (Object.keys(grammars).length) return hold(grammars, true);from = 0;}+ if (pattern && grammarRestart(liveIds.slice(0, from).map(id => priorRow.get(id)), pattern, choice)) from = 0;// Earlier windows of the occurrences the stream covers (and of retired ones), reusable by rendered text under the same context.const reusable = new Map<string, Array<{ occurrenceId: number; record: WindowRecord }>>();const failures = new Map<string, WindowFailure>();diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.tsindex 240e7d7ae9..be367128ba 100644--- a/test/helpers/conversation-facts-invariant-cases.ts+++ b/test/helpers/conversation-facts-invariant-cases.ts@@ -486,6 +486,38 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap.toEqual({ held: { calls: 0, held: 1, failed: 0 }, chose: true, same: { calls: 0, held: 0, failed: 0 }, after: { calls: 0, held: 1, failed: 0 }, again: { calls: 0, held: 1, failed: 0 }, facts, receipt: 'detection_ambiguous' });}, 600_000);+ test('a format detected after an operator chose another one streams the page from its head: the chosen windows before the change do not survive, and the page equals a fresh extraction', async () => {+ const brain = opts.getBrain();+ const slug = `notes/choice-switch-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ const day = (i: number) => new Date(Date.UTC(2025, 0, 1 + i)).toISOString().slice(0, 10);+ const old = Array.from({ length: 6000 }, (_, i) => `Reference line ${i} before the conversation.`).join('\n') + '\n' + Array.from({ length: 100 }, (_, i) =>+ `## ${day(i)}\n\n**Alice Example** (9:00 AM): old turn ${i} ${'detail '.repeat(800)}\n\n**Bob Example** (9:02 AM): old response ${i} ${'detail '.repeat(800)}`).join('\n\n');+ await brain.seed(slug, chatPage('Constant title', old));+ expect((await extract(brain.engine, slug)).result.pages_detection_ambiguous).toBe(1);+ await extract(brain.engine, slug, { grammar: 'bold-paren-time-12h' });+ const chosen = await factsOf(brain.engine, slug);+ const added = Array.from({ length: 12_000 }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: new format turn ${i} about a synthetic topic.`).join('\n');+ await brain.seed(slug, chatPage('Constant title', `${old}\n${added}`));+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;+ const body = (await brain.body(slug)).truth;+ expect(parser.parseConversation(body, { page }).matched_pattern_id).toBe('plain-role-no-time');+ const run = await extract(brain.engine, slug);+ const after = await factsOf(brain.engine, slug);+ const freshSlug = `notes/choice-switch-fresh-${randomUUID().slice(0, 8)}`;+ await brain.seed(freshSlug, chatPage('Constant title', body));+ await extract(brain.engine, freshSlug);+ const fresh = await factsOf(brain.engine, freshSlug);+ const shas = (facts: typeof after) => facts.map(f => f.key.split(':')[2]).sort();+ const forced = await extract(brain.engine, slug, { force: true });+ const rows = await derivations(brain.engine, slug);+ expect({ failed: run.result.pages_failed, held: run.result.pages_detection_ambiguous ?? 0, facts: after.length, same: shas(after).join() === shas(fresh).join(),+ stale: shas(after).filter(s => shas(chosen).includes(s) && !shas(fresh).includes(s)).length, forcedCalls: forced.calls.length, forcedSame: shas(await factsOf(brain.engine, slug)).join() === shas(fresh).join(),+ grammars: [...new Set(rows.rows.map(r => (r.output as { pattern?: string | null }).pattern ?? null))], chosenRows: rows.rows.filter(r => (r.output as { chosen?: boolean }).chosen).length,+ mismatches: await claimMismatches(brain.engine, slug) })+ .toEqual({ failed: 0, held: 0, facts: fresh.length, same: true, stale: 0, forcedCalls: 0, forcedSame: true, grammars: ['plain-role-no-time'], chosenRows: 0, mismatches: [] });+ }, 600_000);+test('R3 (cases C, C2): a page turned to pure prose whose facts have no recorded grammar (rows without one, or no rows at all) is non-extractable and its facts are collected, --force too', async () => {const brain = opts.getBrain();const out: Record<string, unknown> = {};