Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(conversation-facts): round 7 - a lost grammar runs on the recorded one, otherwise the page stops being a transcript

garrytan602ccf006f49
diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
index 6e87193757..8d585fbfae 100644
--- a/src/commands/doctor/checks/extraction-input.ts
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -41,10 +41,8 @@ const FAILED_WINDOWS = 'failed_windows';
const FAILED_REMEDY = 'a conversation window failed to extract in run after run and is skipped, so the older windows still get extracted (the sample names the window, its receipt the last error); fix the cause, then gbrain extract-conversation-facts --slug <slug> --force tries it again';
const NO_MESSAGES = 'no_messages';
const NO_MESSAGES_REMEDY = 'the page reads as a transcript format over its whole text, yet no message parsed under that format (a conversation parser fault), so the last run changed nothing and kept its facts; rerunning repeats this, so report it with gbrain doctor --json and the page\'s format (a page that is not a transcript settles as non-extractable instead)';
-const GRAMMAR_LOST = 'grammar_lost';
-const GRAMMAR_LOST_REMEDY = 'no chat format is detected over the whole page any more (text added around the transcript, such as reference paragraphs, can outweigh its message lines), yet its messages still parse in the format it was extracted in, so the run kept every conversation fact and settled nothing; move the added text to another page (or below a heading the transcript does not need) and rerun gbrain extract-conversation-facts --slug <slug>; if the page is no longer meant to be a transcript, remove its message lines and rerun, which marks it non-extractable and clears its conversation facts';
const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY
- : g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : g.kind === GRAMMAR_LOST ? GRAMMAR_LOST_REMEDY : REMEDY[g.pipeline] ?? null;
+ : g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : REMEDY[g.pipeline] ?? null;
const describe = (g: ReceiptGroup): string =>
`${g.pipeline}/${g.kind}: ${g.pages} page(s) (e.g. ${g.samples.join(', ')}); ${remedy(g) ?? 'see the receipt in page_extraction_state'}`;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f595ef7ac5..a747550789 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 that is no longer a transcript (no message parses even in the format it was extracted in) is marked non-extractable and its conversation facts are cleared, even under `--force`. A page whose format is no longer detected over the whole page (text added around the transcript can outweigh its message lines) but whose messages still parse in that format keeps every fact, settles nothing and leaves a `grammar_lost` receipt doctor lists with the fix; a page that reads as a transcript yet parses no message does the same with a `no_messages` receipt. 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 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.' },
// 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/extraction-watermark.ts b/src/core/extraction-watermark.ts
index 2992a78c75..533ef1b6ea 100644
--- a/src/core/extraction-watermark.ts
+++ b/src/core/extraction-watermark.ts
@@ -37,7 +37,7 @@ export type HeadFallbackReason = 'no_watermark' | 'prefix_changed' | 'version_ch
/** The durable receipt of an extraction that did not read all of its input. */
export interface InputTruncated {
/** PR 4 (Wave B incremental derivation, transcripts): `no_messages`, a segmented conversation page reads as a transcript format over its whole text yet no message parsed under it; the run changed nothing. */
- kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages' | 'grammar_lost';
+ kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages';
pipeline: ExtractionPipeline;
/** Characters the extractor read (0 for a skipped page). */
processed_chars: number;
@@ -55,13 +55,6 @@ export interface InputTruncated {
*/
window_rule?: 'no_prior_facts' | 'prior_facts_kept';
prior_facts?: number;
- /**
- * PR 4 (Wave B incremental derivation, transcripts): `grammar_lost`, no chat format is detected over a segmented
- * conversation page that holds windows or facts, yet `messages` still parse under the format it was extracted in
- * (`pattern`), or it recorded none; the run changed nothing.
- */
- pattern?: string;
- messages?: number;
}
export interface StoredWatermark { pipelineVersion: number; bytes: number; sha256: string }
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 9cedf2a24a..9905fcca88 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -55,7 +55,7 @@ import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor,
import { conversationDetectionWork, readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';
import { emptySaveTimeResolutionCounts, mergeSaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
import { conversationEntityHints } from './conversation-entity-hints.ts';
-import { countConversationFacts, countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
+import { countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
import { recordFailedPage } from './conversation-run-status.ts';
import { detectPagePattern, startsConversationRun, streamConversationWindows } from './conversation-stream.ts';
import type { ConversationSegment } from './conversation-types.ts';
@@ -177,32 +177,21 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
const bytesOf = (rows: SegmentDerivationRow[]) => rows.reduce((n, row) => n + liveOccurrence.get(row.occurrenceId)!.byteLen, 0);
let pattern = !opts.redetect && kept.length && 2 * bytesOf(kept) > bytesOf(recorded) ? rowOutput(kept[0]).pattern ?? null : null;
const pinned = pattern !== null;
+ let recovered = false;
const detectedBytes = conversationDetectionWork.bytes;
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. Only a page that holds no window or fact, or that parses no message under the
- // grammar it was extracted in either, has stopped being a transcript (it settles as non-extractable below and its
- // facts are collected); one that still does (prose added around the transcript can tip the density test) keeps
- // everything and settles nothing.
- const recordedGrammar = prior.map(row => rowOutput(row).pattern).find(Boolean) ?? null;
- const holds = prior.some(row => rowOutput(row).windows.length > 0) || await countConversationFacts(engine, sourceId, page.slug, { active: true }) > 0;
- let still = holds && !recordedGrammar ? null : 0;
- if (holds && recordedGrammar) {
- still = (await streamConversationWindows(occurrences, 0, liveIds.length, { page, gapMinutes: opts.gapMinutes, pattern: recordedGrammar },
- i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }), { window() {}, occurrence() {} })).messages;
+ // 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 },
+ i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }), { window() {}, occurrence() {} });
+ if (parsed.messages > 0) { pattern = recordedGrammar; recovered = true; break; }
}
- if (still !== 0) {
- await setExtractionReceipt(engine, page.id, KIND, { kind: 'grammar_lost', pipeline: KIND, processed_chars: 0, ...(recordedGrammar ? { pattern: recordedGrammar } : {}),
- ...(still !== null ? { messages: still } : {}) });
- const why = recordedGrammar ? `no chat format is detected over the page any more, yet ${still} message(s) still parse as ${recordedGrammar}`
- : 'no chat format is detected over the page, which holds conversation facts from a run that recorded none';
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${why}; its facts were kept, nothing settled; gbrain doctor lists it\n`);
- result.pages_failed++;
- recordFailedPage(result, page.slug, `${why}; facts kept`);
- return { newestEnd: null };
- }
- from = 0;
+ if (!pattern) 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 }>>();
@@ -397,7 +386,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
result.resolution_errors += resolution.resolution_errors;
}
- if (pattern && from < liveIds.length && parsedMessages === 0) {
+ if (pattern && !recovered && from < liveIds.length && parsedMessages === 0) {
// A pinned grammar reads nothing here: detect the page's grammar again and start over under it.
if (pinned) return processSegmentedConversationPage(run, page, { ...opts, redetect: true });
// The grammar detected over the whole page reads no message from the page: a parser fault. Nothing is published.
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index bd2ffb4f38..e426dabc02 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -545,9 +545,9 @@ export const LABEL_RETIRED_MARKER = 'retired: conversation-labels';
* page is deleted. Returns the rows removed from the active batch.
*/
/** The page's conversation facts, audit rows aside: what a clear would lose that a window extraction may not see again. */
-export async function countConversationFacts(db: BrainEngine, sourceId: string, slug: string, opts: { active?: boolean } = {}): Promise<number> {
+export async function countConversationFacts(db: BrainEngine, sourceId: string, slug: string): Promise<number> {
const [row] = await db.executeRaw<{ count: string }>(`SELECT count(*)::text AS count FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2
- AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND NOT (f.source = ANY($3::text[]))${opts.active ? ' AND f.expired_at IS NULL' : ''}`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]);
+ AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND NOT (f.source = ANY($3::text[]))`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]);
return Number(row?.count ?? 0);
}
diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.ts
index 0350df22c0..82ce020d29 100644
--- a/test/helpers/conversation-facts-invariant-cases.ts
+++ b/test/helpers/conversation-facts-invariant-cases.ts
@@ -10,12 +10,13 @@
* unchanged key (a model change) leaves one batch per key (F6); rows from an older derivation version are never
* 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 yet still parses changes nothing and leaves a
- * grammar_lost receipt (N1); an append that commits after the old version check and before the publication locks
+ * 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
+ * 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 a run settles a page version it did not read.
+ * 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.
*/
import { expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -180,27 +181,118 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
expect({ listed: group?.samples.includes(`default:${slug}`), fault: group?.remedy?.includes('parser fault') }).toEqual({ listed: true, fault: true });
}, 600_000);
- test('N1: a transcript whose grammar the whole page no longer shows (references added, title changed) keeps every fact, settles nothing and leaves a grammar_lost receipt doctor lists', async () => {
+ test('N1: a transcript whose grammar the whole page no longer shows (references added, title changed) runs on the grammar it recorded: every window is extracted again under its new key, holds its batch, and the page settles', async () => {
const brain = opts.getBrain();
const slug = `notes/grammar-lost-${randomUUID().slice(0, 8)}`;
await caps(brain.engine, 'off');
const transcript = sparseTranscript(3000, 18);
await brain.seed(slug, chatPage('Grammar lost', transcript));
const first = await extract(brain.engine, slug);
- const before = (await factsOf(brain.engine, slug)).map(f => f.id);
+ const before = await factsOf(brain.engine, slug);
expect({ processed: first.result.pages_processed, facts: before.length > 100 }).toEqual({ processed: 1, facts: true });
await brain.seed(slug, chatPage('Grammar lost, renamed', `${transcript}\n\n## References\n\n${references(3000)}`));
const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
- const truth = (await brain.body(slug)).truth;
- expect(parser.parseConversation(truth, { page }).matched_pattern_id).toBeUndefined();
+ expect(parser.parseConversation((await brain.body(slug)).truth, { page }).matched_pattern_id).toBeUndefined();
const { calls, result } = await extract(brain.engine, slug);
- expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, cleaned: result.orphan_facts_cleaned,
- facts: (await factsOf(brain.engine, slug)).map(f => f.id), states: [...new Set((await derivations(brain.engine, slug)).states)] })
- .toEqual({ calls: 0, failed: 1, nonExtractable: 0, cleaned: 0, facts: before, states: ['done'] });
- const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;
- const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[]; remedy: string | null }> }).groups;
- const group = groups.find(g => g.pipeline === 'conversation_facts' && g.kind === 'grammar_lost');
- expect({ listed: group?.samples.includes(`default:${slug}`), remedy: group?.remedy?.includes('still parse') }).toEqual({ listed: true, remedy: true });
+ const after = await factsOf(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, processed: result.pages_processed, facts: after.length,
+ windows: rows.keys.length >= before.length, mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(rows.states)] })
+ .toEqual({ calls: rows.keys.length, failed: 0, nonExtractable: 0, processed: 1, facts: rows.keys.length, windows: true, mismatches: [], states: ['done'] });
+ }, 600_000);
+
+ /** Three runs (two plain, one --force) on a page whose grammar is no longer detected: what each reported and left. */
+ const lostGrammarRuns = async (brain: AppendBrain, slug: string) => {
+ const out: Array<Record<string, unknown>> = [];
+ for (const force of [false, false, true]) {
+ const { calls, result } = await extract(brain.engine, slug, { force });
+ const rows = await derivations(brain.engine, slug);
+ out.push({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, facts: (await factsOf(brain.engine, slug)).length,
+ windows: rows.keys.length, mismatches: (await claimMismatches(brain.engine, slug)).length });
+ }
+ return out;
+ };
+ const undetected = async (brain: AppendBrain, slug: string) => {
+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
+ return parser.parseConversation((await brain.body(slug)).truth, { page }).matched_pattern_id ?? null;
+ };
+
+ test('R4 (case A): a transcript rewritten to prose that keeps quoted message lines settles under its recorded grammar, keeping only the windows those lines still make', async () => {
+ const brain = opts.getBrain();
+ const out: Record<string, unknown> = {};
+ for (const quoted of [1, 3]) {
+ const slug = `notes/quoted-line-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Was a chat', chatDays(4600, 100, 38)));
+ await extract(brain.engine, slug);
+ expect((await factsOf(brain.engine, slug)).length).toBeGreaterThan(100);
+ const lines = Array.from({ length: quoted }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}** (1:0${5 + i} PM): the orchard review moved, part ${i}.`).join('\n\n');
+ await brain.seed(slug, chatPage('Was a chat', `${references(9000)}\n\nLines we quoted from the old chat:\n\n${lines}`));
+ expect(await undetected(brain, slug)).toBeNull();
+ out[quoted] = await lostGrammarRuns(brain, slug);
+ }
+ const run = (calls: number, nonExtractable: number, windows: number) => ({ calls, failed: 0, nonExtractable, facts: windows, windows, mismatches: 0 });
+ expect(out).toEqual({ 1: [run(0, 1, 0), run(0, 0, 0), run(0, 1, 0)], 3: [run(1, 0, 1), run(0, 0, 1), run(0, 0, 1)] });
+ }, 600_000);
+
+ test('R4 (cases B, B-heading): a transcript with reference lines added, before and after they move below a heading, settles under its recorded grammar every run', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/references-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ const transcript = `**Alice Example:** The old code is 4400.\n**Bob Example:** The launch is on Friday.\n**Alice Example:** ${'detail '.repeat(160_000)}\n`;
+ const refs = Array.from({ length: 100 }, (_, i) => `Additional reference paragraph ${i}.`).join('\n');
+ await brain.seed(slug, chatPage('References', transcript));
+ await extract(brain.engine, slug);
+ const before = (await factsOf(brain.engine, slug)).length;
+ expect(before).toBeGreaterThan(0);
+ await brain.seed(slug, chatPage('References, retitled', transcript + refs));
+ expect(await undetected(brain, slug)).toBeNull();
+ const added = await lostGrammarRuns(brain, slug);
+ await brain.seed(slug, chatPage('References, retitled again', `${transcript}\n## References\n\n${refs}`));
+ expect(await undetected(brain, slug)).toBeNull();
+ const heading = await lostGrammarRuns(brain, slug);
+ // The reference lines continue the last message, so its windows grow; every window is extracted under the new title.
+ const settled = (runs: typeof added) => { const windows = runs[0]!.windows as number; const run = (calls: number) => ({ calls, failed: 0, nonExtractable: 0, facts: windows, windows, mismatches: 0 });
+ return { grew: windows >= before, runs: [run(windows), run(0), run(0)] }; };
+ expect({ added: { grew: true, runs: added }, heading: { grew: true, runs: heading } }).toEqual({ added: settled(added), heading: settled(heading) });
+ }, 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> = {};
+ for (const shape of ['rows without a grammar', 'no rows'] as const) {
+ const slug = `notes/no-grammar-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Was a chat', chatDays(4700, 100, 39)));
+ await extract(brain.engine, slug);
+ const { pageId } = await derivations(brain.engine, slug);
+ if (shape === 'no rows') await brain.engine.executeRaw("DELETE FROM page_segment_derivations WHERE page_id = $1 AND pipeline = 'conversation_facts'", [pageId]);
+ else await brain.engine.executeRaw("UPDATE page_segment_derivations SET output = output - 'pattern' WHERE page_id = $1 AND pipeline = 'conversation_facts'", [pageId]);
+ const before = (await factsOf(brain.engine, slug)).length;
+ await brain.seed(slug, chatPage('Was a chat', references(9000)));
+ expect(await undetected(brain, slug)).toBeNull();
+ out[shape] = { before: before > 100, runs: await lostGrammarRuns(brain, slug) };
+ }
+ const collected = { calls: 0, failed: 0, nonExtractable: 1, facts: 0, windows: 0, mismatches: 0 };
+ const settled = { ...collected, nonExtractable: 0 };
+ expect(out).toEqual({ 'rows without a grammar': { before: true, runs: [collected, settled, collected] }, 'no rows': { before: true, runs: [collected, settled, collected] } });
+ }, 600_000);
+
+ test('R3 (legacy): facts the inline extractor left on a small transcript are collected once the page is segmented prose, --force too', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/former-conversation-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Former conversation', 'user: The fixture door code was 8844.\nassistant: Noted the fixture door code.\n'));
+ await extract(brain.engine, slug);
+ expect((await factsOf(brain.engine, slug)).length).toBe(1);
+ await brain.seed(slug, chatPage('Former conversation', 'Ordinary reference prose with no speaker labels or message lines.\n'.repeat(18_000)));
+ expect((await brain.body(slug)).storage).toBe('segmented');
+ const runs = [];
+ for (const force of [false, true]) {
+ const { result } = await extract(brain.engine, slug, { force });
+ runs.push({ failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, facts: (await factsOf(brain.engine, slug)).length });
+ }
+ expect(runs).toEqual([{ failed: 0, nonExtractable: 1, facts: 0 }, { failed: 0, nonExtractable: 1, facts: 0 }]);
}, 600_000);
test('N2: an append_page that commits right after the old version check (before the publication locks the page) leaves the run unsettled with its facts kept; the next run settles it', async () => {
diff --git a/test/helpers/conversation-facts-property-cases.ts b/test/helpers/conversation-facts-property-cases.ts
index 28972dabd8..b48a1af7f9 100644
--- a/test/helpers/conversation-facts-property-cases.ts
+++ b/test/helpers/conversation-facts-property-cases.ts
@@ -15,8 +15,10 @@
* row records holds exactly that count (a key holding no fact included), and a window marked failed holds either
* 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.
* 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); 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); 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
@@ -32,6 +34,7 @@ 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 { 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';
@@ -140,12 +143,16 @@ async function violations(engine: BrainEngine, slug: string, before: Fact[], o:
return { problems, after, fired };
}
-type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap';
-/** Steps, across every seed, that must exercise each path: about half of what the 30 seeds exercise on both engines (193, 165, 46, 133, 28, 21). */
-export const PROPERTY_PATH_FLOORS: Record<PropertyPath, number> = { moved: 96, failed_window: 82, marked_failed: 23, collected: 66, since: 14, cap: 10 };
+type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap' | 'grammar_lost';
+/**
+ * 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).
+ */
+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 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 };
+ const firedSteps: Record<PropertyPath, number> = { moved: 0, failed_window: 0, marked_failed: 0, collected: 0, since: 0, cap: 0, grammar_lost: 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 () => {
@@ -164,6 +171,29 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
await brain.seed(slug, chatPage(title, chatDays(FIRST_DAY, DAYS, seed)));
const log: string[] = [];
let facts = await factsOf(engine, slug);
+ // Its own stream, so the steps the main stream draws stay those of a run with no lost grammar.
+ const lost = rng(seed + 7919);
+ /** Rewrite the page to prose keeping up to three of its message lines (no grammar is detected while it holds facts), run, then restore the transcript and run; each run is checked like a step. */
+ const loseGrammar = async (step: number) => {
+ const truth = (await brain.body(slug)).truth;
+ const quoted = truth.split('\n').filter(line => line.startsWith('**')).slice(-(1 + Math.floor(lost() * 40))).slice(0, Math.floor(lost() * 4));
+ const prose = Array.from({ length: 12_000 }, (_, i) => `Paragraph ${i} of the notes: ${WORDS[Math.floor(lost() * WORDS.length)]} and ${WORDS[i % WORDS.length]}.`).join('\n\n');
+ for (const phase of ['lost', 'restored'] as const) {
+ await brain.seed(slug, chatPage(title, phase === 'lost' ? [prose, ...quoted].join('\n\n') : truth));
+ const detector = createPatternDetector();
+ detector.push((await brain.body(slug)).truth);
+ const lostGrammar = phase === 'lost' && detector.finish() === null && facts.length > 0;
+ const constraint = (['none', 'none', 'abort', 'limit'] as const)[Math.floor(lost() * 4)]!;
+ const o: RunOpts = constraint === 'abort' ? { abortAfter: 1 + Math.floor(lost() * 30) } : constraint === 'limit' ? { segmentLimit: 1 + Math.floor(lost() * 20) } : {};
+ const outcome = await run(engine, slug, o);
+ const checked = await violations(engine, slug, facts, o, outcome);
+ if (lostGrammar) checked.fired.add('grammar_lost');
+ log.push(`step ${step} (grammar ${phase}, ${quoted.length} message line(s) kept): ${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));
@@ -177,6 +207,8 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
try {
for (let step = 1; step <= PROPERTY_STEPS + 1; step++) {
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);
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') {