Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(conversation-facts): adopt the recorded grammar that parses the most messages, and never collect while another competes

garrytanf7b601d49294
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 94b6893972..7d4a2b4286 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1065,7 +1065,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },
{ since: 'TBD', text: 'Atom extraction now covers very large pages, and after an append reads only the new text.' },
{ since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls, the synopsis step\'s embedding included, turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped. A model with no price still reserves its ceiling estimate (about one window per page at the default cap; no default changed and no price is assumed), and its receipt now says `unpriced_model` with the model; doctor `derivation_unpriced_model` warns and names the fix, `gbrain pricing set <model> --input <usd> --output <usd>`, which writes `pricing.overrides`.' },
- { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page whose format is no longer detected over the whole page (text added around the transcript can outweigh its message lines) is extracted in the format an earlier run recorded while any message still parses in it, so only the windows that format still finds keep their facts; a page with no message in any recorded format, or with no recorded format and none detected (facts an older extractor left included), is no longer a transcript: it is marked non-extractable and its conversation facts are cleared, even under `--force`. A page that reads as a transcript yet parses no message keeps every fact and leaves a `no_messages` receipt doctor lists. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },
+ { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page whose format is no longer detected over the whole page (text added around the transcript can outweigh its message lines) is extracted in the format earlier runs recorded that parses the most messages in it, so only the windows that format still finds keep their facts; when two recorded formats both parse messages and neither parses more than twice the other, the run fails for that page and changes nothing until an edit makes one format clearly dominant; a page with no message in any recorded format, or with no recorded format and none detected (facts an older extractor left included), is no longer a transcript: it is marked non-extractable and its conversation facts are cleared, even under `--force`. A page that reads as a transcript yet parses no message keeps every fact and leaves a `no_messages` receipt doctor lists. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },
// PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.
{ since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },
// PR 4 (Wave B incremental derivation, transcripts)
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 56e655c7f5..f19b2ec1ee 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -27,7 +27,9 @@
* and in runs, newest run first, so a stop reads only the runs it reached; a page nothing changed on reads nothing;
* - parses under the page's grammar: the one detectPagePattern picks over the whole page (the whole-page pass's
* choice; one unpaid read, counted in conversationDetectionWork), pinned on the rows while the occurrences that
- * recorded it under the same context are mostly unchanged by bytes; a page with no grammar is not a conversation: it settles as
+ * recorded it under the same context are mostly unchanged by bytes; with none detected, the recorded grammar that
+ * parses the most messages, while it parses more than twice any other recorded grammar (else the page fails and
+ * nothing is published); a page with no grammar is not a conversation: it settles as
* non-extractable and its conversation facts are collected; a pinned grammar under which nothing parses is detected
* again; a detected grammar under which nothing parses leaves a no_messages receipt and changes nothing;
* - reuses every window an earlier run extracted with the same rendered text under the same context (re-anchored
@@ -182,15 +184,34 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
if (!pattern && from < liveIds.length) pattern = await detectPagePattern(occurrences, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));
if (!pattern && from < liveIds.length) {
if (opts.sinceIso) { result.pages_skipped++; return { newestEnd: null }; }
- // No grammar over the whole page (text around a transcript can tip the density test). A grammar an earlier run
- // recorded that still parses a message here is the page's grammar: the run goes on under it, so its windows replace
- // their exact keys and a settled run collects the rest. Otherwise the page stopped being a transcript: it settles
- // as non-extractable below and its conversation facts are collected.
- for (const recordedGrammar of new Set(prior.map(row => rowOutput(row).pattern).filter((p): p is string => !!p))) {
- const parsed = await streamConversationWindows(occurrences, 0, liveIds.length, { page, gapMinutes: opts.gapMinutes, pattern: recordedGrammar },
+ // No grammar over the whole page (text around a transcript can tip the density test). Of the grammars earlier runs
+ // recorded, the one that parses the most messages here (on a tie, the one recorded last) is the page's grammar: the
+ // run goes on under it, so its windows replace their exact keys and a settled run collects the rest. It must parse
+ // more than twice the messages of any other recorded grammar, else the other may be the real one and collecting
+ // would delete its facts: the page fails with nothing published until an edit settles which format it is. When no
+ // recorded grammar parses a message, the page stopped being a transcript: it settles as non-extractable below and
+ // its conversation facts are collected.
+ const lastRecorded = new Map<string, string>();
+ for (const row of prior) {
+ const recordedGrammar = rowOutput(row).pattern;
+ if (recordedGrammar && row.updatedAt > (lastRecorded.get(recordedGrammar) ?? '')) lastRecorded.set(recordedGrammar, row.updatedAt);
+ }
+ const candidates: Array<{ grammar: string; messages: number; at: string }> = [];
+ for (const [grammar, at] of lastRecorded) {
+ const parsed = await streamConversationWindows(occurrences, 0, liveIds.length, { page, gapMinutes: opts.gapMinutes, pattern: grammar },
i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }), { window() {}, occurrence() {} });
- if (parsed.messages > 0) { pattern = recordedGrammar; recovered = true; break; }
+ candidates.push({ grammar, messages: parsed.messages, at });
+ }
+ candidates.sort((a, b) => b.messages - a.messages || (a.at < b.at ? 1 : a.at > b.at ? -1 : 0));
+ const [best, rival] = candidates;
+ if (best && rival && best.messages > 0 && best.messages <= 2 * rival.messages) {
+ const why = `no format is detected and its recorded formats compete (${best.grammar}: ${best.messages} messages, ${rival.grammar}: ${rival.messages}); facts kept, nothing settled`;
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${why}\n`);
+ result.pages_failed++;
+ recordFailedPage(result, page.slug, why);
+ return { newestEnd: null };
}
+ if (best && best.messages > 0) { pattern = best.grammar; recovered = true; }
if (!pattern) from = 0;
}
// Earlier windows of the occurrences the stream covers (and of retired ones), reusable by rendered text under the same context.
diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.ts
index 82ce020d29..7b92eb3f93 100644
--- a/test/helpers/conversation-facts-invariant-cases.ts
+++ b/test/helpers/conversation-facts-invariant-cases.ts
@@ -11,12 +11,13 @@
* read as window positions (F9); the grammar is detected over the whole page, not its head (F3), and that read is
* counted; a page that reads as a transcript yet parses no message changes nothing and leaves a no_messages receipt;
* a transcript whose format the whole page no longer shows runs on the format it recorded while a message still
- * parses under it (N1, R4), and a page with no format that parses anything is non-extractable and collected, with
+ * parses under it (N1, R4), in the recorded format that parses the most messages and only while it parses more
+ * than twice any other (G1), and a page with no format that parses anything is non-extractable and collected, with
* or without rows (R3); an append that commits after the old version check and before the publication locks
* the page leaves the run unsettled (N2).
* 2. Fails when: anything but an exact-key replacement or a fully settled collection deletes a fact, a moved window's
* old row keeps claiming it, a settling run keeps the old batch beside the new one, the head of a page picks its
- * grammar, a lost grammar collects a transcript's facts or holds a prose page's facts forever, or a run settles a page version it did not read.
+ * grammar, a lost grammar collects a transcript's facts (under a stale recorded format included) or holds a prose page's facts forever, or a run settles a page version it did not read.
*/
import { expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -257,6 +258,63 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
expect({ added: { grew: true, runs: added }, heading: { grew: true, runs: heading } }).toEqual({ added: settled(added), heading: settled(heading) });
}, 600_000);
+ /**
+ * A page whose rows record two grammars, and whose grammar the whole page no longer shows: a bold-name transcript
+ * extracted in full, rewritten to a plain-role one (keeping `quotes` bold-name lines) and extracted one window, so the
+ * rows it reached record plain-role and the rest bold-name; then reference text and a new title around both.
+ */
+ const twoGrammars = async (brain: AppendBrain, slug: string, quotes: number) => {
+ await caps(brain.engine, 'off');
+ const old = Array.from({ length: 100 }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** legacy turn ${i} ${'detail '.repeat(1600)}`).join('\n');
+ await brain.seed(slug, chatPage('Format change', old));
+ await extract(brain.engine, slug);
+ const current = Array.from({ length: 200 }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: current turn ${i} ${'present '.repeat(700)}`).join('\n');
+ const kept = Array.from({ length: quotes }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** a line quoted from the old format, part ${i}.`).join('\n');
+ await brain.seed(slug, chatPage('Format change', `${current}\n${kept}\n`));
+ await extract(brain.engine, slug, { segmentLimit: 1 });
+ expect(await recordedGrammars(brain, slug)).toEqual(['bold-name-no-time', 'plain-role-no-time']);
+ const prose = Array.from({ length: 12_000 }, (_, i) => `Paragraph ${i} with unrelated reference material.`).join('\n');
+ await brain.seed(slug, chatPage('Format change, retitled', `${prose}\n${current}\n${kept}\n`));
+ expect(await undetected(brain, slug)).toBeNull();
+ return { prose, current };
+ };
+ const recordedGrammars = async (brain: AppendBrain, slug: string) =>
+ [...new Set((await derivations(brain.engine, slug)).rows.map(row => (row.output as { pattern?: string | null }).pattern ?? null))].sort();
+ /** The plain-role turns the run's windows carry. */
+ const turnsIn = (calls: string[]) => new Set(calls.flatMap(text => [...text.matchAll(/current turn (\d+) /g)].map(m => m[1]))).size;
+
+ test('G1: with no grammar detected, the recorded grammar that parses the most messages is the page\'s, not the first one that parses any: the current transcript is extracted again and the page settles', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/format-change-${randomUUID().slice(0, 8)}`;
+ await twoGrammars(brain, slug, 2);
+ const { calls, result } = await extract(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ expect({ calls: calls.length, turns: turnsIn(calls), failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, processed: result.pages_processed,
+ facts: (await factsOf(brain.engine, slug)).length, grammars: await recordedGrammars(brain, slug), mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(rows.states)] })
+ .toEqual({ calls: rows.keys.length, turns: 200, failed: 0, nonExtractable: 0, processed: 1, facts: rows.keys.length, grammars: ['plain-role-no-time'], mismatches: [], states: ['done'] });
+ }, 600_000);
+
+ test('G1: while another recorded grammar parses half as many messages or more, the page fails with every fact and row kept, --force too; once an edit leaves one grammar dominant it settles under it', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/format-mix-${randomUUID().slice(0, 8)}`;
+ const { prose, current } = await twoGrammars(brain, slug, 150);
+ const facts = (await factsOf(brain.engine, slug)).map(f => f.id);
+ const rows = JSON.stringify((await derivations(brain.engine, slug)).rows.map(row => [row.occurrenceId, row.output, row.state]));
+ for (const force of [false, true]) {
+ const { calls, result } = await extract(brain.engine, slug, { force });
+ expect({ force, calls: calls.length, failed: result.pages_failed, why: result.failed_pages[0]?.error.includes('recorded formats compete'), facts: (await factsOf(brain.engine, slug)).map(f => f.id),
+ rows: JSON.stringify((await derivations(brain.engine, slug)).rows.map(row => [row.occurrenceId, row.output, row.state])) })
+ .toEqual({ force, calls: 0, failed: 1, why: true, facts, rows });
+ }
+ await brain.seed(slug, chatPage('Format change, retitled', `${prose}\n${current}\n**Alice Example:** the one line still quoted from the old format.\n`));
+ expect(await undetected(brain, slug)).toBeNull();
+ const { calls, result } = await extract(brain.engine, slug);
+ const after = await derivations(brain.engine, slug);
+ expect({ turns: turnsIn(calls), failed: result.pages_failed, processed: result.pages_processed, facts: (await factsOf(brain.engine, slug)).length,
+ grammars: await recordedGrammars(brain, slug), mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(after.states)] })
+ .toEqual({ turns: 200, failed: 0, processed: 1, facts: after.keys.length, grammars: ['plain-role-no-time'], mismatches: [], states: ['done'] });
+ }, 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> = {};
diff --git a/test/helpers/conversation-facts-property-cases.ts b/test/helpers/conversation-facts-property-cases.ts
index b48a1af7f9..fd5e5354d9 100644
--- a/test/helpers/conversation-facts-property-cases.ts
+++ b/test/helpers/conversation-facts-property-cases.ts
@@ -16,9 +16,13 @@
* that count (an earlier context's batch) or none;
* (iii) every window a row claims holds exactly the facts the row says, and a settled page holds only current windows.
* Before a step, the page may also be rewritten to prose that keeps zero to three of its message lines, so no grammar
- * is detected while it still holds facts, then restored; each of the two runs is checked like a step.
+ * is detected while it still holds facts, then restored; each of the two runs is checked like a step. Or it may be
+ * rewritten to another transcript format and run one window, so its rows record two grammars, then lose detection with
+ * a few or about as many of its own message lines kept, then be restored: each run is checked like a step, and the lost
+ * run also holds that competing grammars publish nothing and a settled page records the grammar parsing the most messages.
* Each step records which paths it exercised (a moved window, a window-specific failure, a window marked failed, a
- * settled collection, a --since run, a cap refusal, a lost grammar on a page holding facts); across the seeds every path must fire at least its floor. Each seed
+ * settled collection, a --since run, a cap refusal, a lost grammar on a page holding facts, a lost grammar on a page
+ * recording two grammars that one dominates or that compete); across the seeds every path must fire at least its floor. Each seed
* also dooms the windows whose text hash starts with one chosen digit for a span of steps, so windows reach the failure
* limit and block collection until the final --force run.
* At the end a healthy unconstrained --force run leaves the same windows and facts as one extraction of the same page on
@@ -34,7 +38,8 @@ import type { BrainEngine } from '../../src/core/engine.ts';
import type { AppendBrain } from './append-brain.ts';
import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';
import { CONVERSATION_FACTS_DERIVATION_VERSION } from '../../src/core/facts/conversation-incremental.ts';
-import { createPatternDetector } from '../../src/core/conversation-parser/parse.ts';
+import { applyPattern, createPatternDetector, deriveDateContext } from '../../src/core/conversation-parser/parse.ts';
+import { BUILTIN_PATTERNS } from '../../src/core/conversation-parser/builtins.ts';
import { parseSourceWindow, sourceWindowKey, type SourceWindow } from '../../src/core/page-body/derivations.ts';
import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';
import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';
@@ -143,16 +148,17 @@ async function violations(engine: BrainEngine, slug: string, before: Fact[], o:
return { problems, after, fired };
}
-type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap' | 'grammar_lost';
+type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap' | 'grammar_lost' | 'grammar_adopted' | 'grammar_refused';
/**
* Steps, across every seed, that must exercise each path: the round-5 floors (about half of 193, 165, 46, 133, 28, 21),
- * and half of the 24 steps that lose the grammar on a page holding facts (the 30 seeds now exercise 189, 155, 37, 167,
- * 30, 22, 24).
+ * half of the 24 steps that lose the grammar on a page holding facts, and half of the 12 lost runs on a page recording two
+ * grammars where one dominates and of the 12 where they compete (the 30 seeds now exercise 201, 153, 37, 184, 30, 22,
+ * 24, 12, 12).
*/
-export const PROPERTY_PATH_FLOORS: Record<PropertyPath, number> = { moved: 96, failed_window: 82, marked_failed: 23, collected: 66, since: 14, cap: 10, grammar_lost: 12 };
+export const PROPERTY_PATH_FLOORS: Record<PropertyPath, number> = { moved: 96, failed_window: 82, marked_failed: 23, collected: 66, since: 14, cap: 10, grammar_lost: 12, grammar_adopted: 6, grammar_refused: 6 };
export function defineConversationFactsPropertyCases(opts: { getBrain: () => AppendBrain; getFresh: () => AppendBrain }): void {
- const firedSteps: Record<PropertyPath, number> = { moved: 0, failed_window: 0, marked_failed: 0, collected: 0, since: 0, cap: 0, grammar_lost: 0 };
+ const firedSteps: Record<PropertyPath, number> = { moved: 0, failed_window: 0, marked_failed: 0, collected: 0, since: 0, cap: 0, grammar_lost: 0, grammar_adopted: 0, grammar_refused: 0 };
let seedsRun = 0;
for (let seed = 1; seed <= PROPERTY_SEEDS; seed++) {
test(`seed ${seed}: ${PROPERTY_STEPS} seeded changes and constrained runs keep the deletion invariant, and the page converges to a fresh extraction`, async () => {
@@ -194,6 +200,58 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
facts = checked.after;
}
};
+ // Its own stream as well, so the steps the other streams draw stay those of a run with no rival grammar.
+ const rival = rng(seed + 104_729);
+ /**
+ * Rewrite the page to a plain-role transcript and run one window of it, so the rows record two grammars; then put
+ * prose before it and keep a few of the page's own message lines (the plain-role grammar dominates) or about as many
+ * as it has turns (the two compete), so no grammar is detected, and run; then restore the page and run. Each run is
+ * checked like a step, and the lost run also against G1: competing grammars publish nothing, a dominant one is the
+ * grammar every row of a settled page records.
+ */
+ const rivalGrammar = async (step: number) => {
+ const truth = (await brain.body(slug)).truth;
+ const own = truth.split('\n').filter(line => line.startsWith('**'));
+ // Long turns, so the page stays above the segmented demotion size while each turn fits one window.
+ const count = 110 + Math.floor(rival() * 60);
+ const plain = Array.from({ length: count }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: turn ${i} of step ${step} on the ${WORDS[Math.floor(rival() * WORDS.length)]} and the ${WORDS[i % WORDS.length]}. ${'detail '.repeat(700)}`).join('\n');
+ const competing = rival() < 0.5;
+ const keep = Math.min(own.length, competing ? Math.ceil(count * (0.6 + rival())) : Math.floor(rival() * 4));
+ const kept = own.slice(own.length - keep);
+ const prose = Array.from({ length: 12_000 }, (_, i) => `Paragraph ${i} of the notes: ${WORDS[Math.floor(rival() * WORDS.length)]} and ${WORDS[i % WORDS.length]}.`).join('\n\n');
+ for (const phase of ['recorded', 'lost', 'restored'] as const) {
+ await brain.seed(slug, chatPage(title, phase === 'recorded' ? plain : phase === 'lost' ? [prose, plain, ...kept].join('\n\n') : truth));
+ const body = (await brain.body(slug)).truth;
+ const detector = createPatternDetector();
+ detector.push(body);
+ const grammars = [...new Set((await derivations(engine, slug)).rows.map(row => (row.output as { pattern?: string | null }).pattern).filter((p): p is string => !!p))];
+ const lostTwo = phase === 'lost' && detector.finish() === null && facts.length > 0 && grammars.length > 1;
+ const page = (await engine.getPage(slug, { sourceId: 'default' }))!;
+ const parsed = grammars.map(id => ({ id, messages: applyPattern(body, BUILTIN_PATTERNS.find(p => p.id === id)!, deriveDateContext({ page })).length })).sort((a, b) => b.messages - a.messages);
+ const counts = parsed.map(p => p.messages).join(' vs ');
+ const refused = lostTwo && parsed[0]!.messages > 0 && parsed[0]!.messages <= 2 * parsed[1]!.messages;
+ const constraint = phase === 'recorded' ? 'limit' : (['none', 'none', 'abort', 'limit'] as const)[Math.floor(rival() * 4)]!;
+ const o: RunOpts = phase === 'recorded' ? { segmentLimit: 1 } : constraint === 'abort' ? { abortAfter: 1 + Math.floor(rival() * 30) }
+ : constraint === 'limit' ? { segmentLimit: 1 + Math.floor(rival() * 20) } : {};
+ const outcome = await run(engine, slug, o);
+ const checked = await violations(engine, slug, facts, o, outcome);
+ if (refused) {
+ checked.fired.add('grammar_refused');
+ if (outcome.calls !== 0 || outcome.failed !== 1 || checked.after.map(f => f.id).join() !== facts.map(f => f.id).join()) checked.problems.push(`(G1) competing recorded grammars (${counts} messages) published or extracted`);
+ } else if (lostTwo && parsed[0]!.messages > 0) {
+ checked.fired.add('grammar_adopted');
+ const best = parsed[0]!.id;
+ const state = await pageState(engine, slug);
+ const d = await derivations(engine, slug);
+ const live = d.rows.filter(row => d.live.includes(row.occurrenceId)).map(row => (row.output as { pattern?: string | null }).pattern);
+ if (state.settled && live.some(p => p !== best)) checked.problems.push(`(G1) the page settled under ${[...new Set(live)].join()} although ${best} parses the most messages (${counts})`);
+ }
+ log.push(`step ${step} (rival grammar ${phase}, ${count} plain-role turns, ${keep} own line(s) kept, recorded ${grammars.join('+') || 'none'} parsing ${counts || 'nothing'}): ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts; ${[...checked.fired].join(' ') || 'no path'}`);
+ for (const path of checked.fired) firedSteps[path]++;
+ expect({ step, log: log.at(-1), problems: checked.problems.slice(0, 5) }).toEqual({ step, log: log.at(-1), problems: [] });
+ facts = checked.after;
+ }
+ };
// The windows whose text hash starts with this digit fail in every run of these steps.
const doomDigit = pick([...'0123456789abcdef']);
const doomFrom = 1 + Math.floor(next() * (PROPERTY_STEPS - 6));
@@ -209,6 +267,7 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
const final = step > PROPERTY_STEPS;
// Never inside the doomed span, whose windows must fail run after run to reach the failure limit.
if (lost() < 0.08 && !final && !(step >= doomFrom && step < doomFrom + doomSteps)) await loseGrammar(step);
+ if (rival() < 0.06 && !final && !(step >= doomFrom && step < doomFrom + doomSteps)) await rivalGrammar(step);
const change = final ? 'none' : pick(['none', 'none', 'append', 'append', 'append', 'new-day', 'edit', 'edit', 'insert', 'insert', 'delete', 'oversized',
'title', 'title', 'visibility', 'model', 'version'] as const);
if (change === 'append') {