Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages PR 2 lane 2e2: count prior conversation facts before reading the window

garrytan874c571d3e30
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index e25f3fc392..342864195a 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -533,14 +533,14 @@ function filterOutSlug(entries: string[], sourceId: string, slug: string): strin
/**
* The body cap, pre-parse: a skip leaves a durable receipt (doctor: extraction_input_truncated); a page under the cap
* clears an earlier one. A segmented page over the window cap is extracted from its newest window only when it has no
- * conversation facts: the run clears them all, and the window may not see them again (lossless until PR 4's anchors).
+ * conversation facts (the run clears them all; lossless until PR 4's anchors): one with any arrives unread (window.priorFacts).
*/
async function skippedForSize(state: ExtractCoreState, snapshot: ConversationPageSnapshot): Promise<boolean> {
const origin = snapshot.oversizedSidecarBytes === undefined ? 'page' : 'sidecar';
const bytes = snapshot.oversizedSidecarBytes ?? Buffer.byteLength(snapshot.body, 'utf8');
const over = bytes > MAX_PAGE_BODY_BYTES;
const window = snapshot.window;
- const priorFacts = window && !over ? await countConversationFacts(state.engine, state.sourceId, snapshot.page.slug) : 0;
+ const priorFacts = window?.priorFacts ?? 0;
if (over || priorFacts > 0) {
state.result.pages_skipped_too_large++;
process.stderr.write(`[extract-conversation-facts] SKIP ${snapshot.page.slug}: ${over ? `${origin === 'sidecar' ? 'raw_transcript sidecar ' : ''}`
@@ -784,7 +784,7 @@ async function preparePageSnapshot(
page: Page,
): Promise<ConversationPageSnapshot> {
try {
- const { body, window } = await readConversationInput(engine, page);
+ const { body, window } = await readConversationInput(engine, page, { priorFacts: () => countConversationFacts(engine, page.source_id, page.slug) });
return { page, body, ...(window ? { window } : {}), versionToken: snapshotVersionToken(page, body) };
} catch (error) {
if (!(error instanceof ConversationBodyTooLargeError)) throw error;
diff --git a/src/core/conversation-parser/body.ts b/src/core/conversation-parser/body.ts
index 9f686301ca..cc58d29a1d 100644
--- a/src/core/conversation-parser/body.ts
+++ b/src/core/conversation-parser/body.ts
@@ -5,7 +5,7 @@ import type { Page } from '../types.ts';
import { loadSourceRow } from '../contextual-retrieval-service.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
-import { readSegmentedConversationInput, type SegmentedConversationInput } from '../page-body/segment-conversation.ts';
+import { CONVERSATION_WINDOW_BYTES, readSegmentedConversationInput, type SegmentedConversationInput } from '../page-body/segment-conversation.ts';
/**
* The largest conversation parser input (UTF-8 bytes): the page ceiling plus
@@ -132,11 +132,14 @@ export async function readConversationBodyForParsing(
/**
* readConversationBodyForParsing with the window it read: a segmented page's summary body is read through ranged
- * reads, and one over CONVERSATION_WINDOW_BYTES is its newest window (page-body/segment-conversation.ts).
+ * reads, and one over CONVERSATION_WINDOW_BYTES is its newest window (page-body/segment-conversation.ts). With
+ * `priorFacts`, a page over the window that has conversation facts is not read at all: its input is empty and the
+ * window carries the count (the run keeps those facts and skips the page).
*/
export async function readConversationInput(
engine: BrainEngine,
page: Page,
+ opts: { priorFacts?: () => Promise<number> } = {},
): Promise<SegmentedConversationInput> {
const rawTranscript = extractRawTranscriptPath(page);
if (rawTranscript) {
@@ -155,5 +158,9 @@ export async function readConversationInput(
);
}
}
- return isSegmentedPage(page) ? readSegmentedConversationInput(engine, page) : { body: readSummaryBody(page) };
+ if (!isSegmentedPage(page)) return { body: readSummaryBody(page) };
+ const totalBytes = Number(page.body_bytes);
+ const priorFacts = totalBytes > CONVERSATION_WINDOW_BYTES ? await opts.priorFacts?.() ?? 0 : 0;
+ if (priorFacts > 0) return { body: '', window: { totalBytes, fallbackDate: null, priorFacts } };
+ return readSegmentedConversationInput(engine, page);
}
diff --git a/src/core/page-body/segment-conversation.ts b/src/core/page-body/segment-conversation.ts
index 952655b07a..31e9f2f76e 100644
--- a/src/core/page-body/segment-conversation.ts
+++ b/src/core/page-body/segment-conversation.ts
@@ -30,6 +30,8 @@ export interface ConversationWindow {
totalBytes: number;
/** The day-header date in force where the window starts, or null. */
fallbackDate: string | null;
+ /** The window was not read: the page has this many conversation facts, which a window run would clear (conversation-parser/body.ts). */
+ priorFacts?: number;
}
export interface SegmentedConversationInput { body: string; window?: ConversationWindow }
diff --git a/test/large-pages/segmented-conversation-facts.test.ts b/test/large-pages/segmented-conversation-facts.test.ts
index 49c1fc58a5..147f184f2a 100644
--- a/test/large-pages/segmented-conversation-facts.test.ts
+++ b/test/large-pages/segmented-conversation-facts.test.ts
@@ -16,13 +16,14 @@
* the window's bytes;
* - one that already has conversation facts is skipped as in Wave A
* (`skipped_too_large`, `window_rule: prior_facts_kept`): no extraction,
- * and every fact, including those outside the window, is kept.
+ * every fact, including those outside the window, is kept, and the
+ * window is never read (no segment text fetched, 0 segment bytes).
* 2. Fails when: a segmented page reads its throwing body getters, the window
* is not the body's suffix or starts inside a forced run, its date context
- * is lost, a read exceeds the window, or a window run clears facts it
- * cannot see.
+ * is lost, a read exceeds the window, a window run clears facts it
+ * cannot see, or a skipped page reads its window first.
* 3. Why existing coverage misses it: conversation-facts tests use inline pages.
- * Seams: `segmentedPassWork.bytes` counts bytes read.
+ * Seams: `segmentedPassWork.bytes` counts bytes read; a readSegmentTexts spy wraps the engine method.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -196,7 +197,7 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {
}
}, 1_800_000);
- test('a page over the window that already has conversation facts keeps every one: skipped_too_large naming the rule, no extraction, nothing cleared', async () => {
+ test('a page over the window that already has conversation facts keeps every one: skipped_too_large naming the rule, no extraction, nothing cleared, the window never read', async () => {
const outcomes: unknown[] = [];
const expected: unknown[] = [];
for (const [index, engine] of engines.entries()) {
@@ -212,14 +213,26 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {
const before = await facts();
expect(before.filter(row => row.source === 'cli:extract-conversation-facts')).toHaveLength(2);
let calls = 0;
- const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2, force: true,
- extractor: async () => { calls++; return [{ fact: 'Carol Example ships the forecast', kind: 'fact', entity_slug: null, source: 'cli:extract-conversation-facts' }]; } });
+ // The window is never read: no segment text is fetched and no segment byte counted.
+ const original = engine.readSegmentTexts.bind(engine);
+ let segmentReads = 0;
+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => { segmentReads += shas.length; return original(sourceId, shas); }) as BrainEngine['readSegmentTexts'];
+ const bytesBefore = segmentedPassWork.bytes;
+ let result: Awaited<ReturnType<typeof runExtractConversationFactsCore>>;
+ try {
+ result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2, force: true,
+ extractor: async () => { calls++; return [{ fact: 'Carol Example ships the forecast', kind: 'fact', entity_slug: null, source: 'cli:extract-conversation-facts' }]; } });
+ } finally {
+ // The spy is an own property; deleting it restores the prototype method.
+ delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;
+ }
+ const bytesRead = segmentedPassWork.bytes - bytesBefore;
const receipt = await receiptOf(engine, huge.id);
- outcomes.push({ engine: index, calls, skipped: result.pages_skipped_too_large, processed: result.pages_processed,
+ outcomes.push({ engine: index, calls, segmentReads, bytesRead, skipped: result.pages_skipped_too_large, processed: result.pages_processed,
factsKept: Bun.deepEquals(await facts(), before),
receipt: { kind: receipt?.kind, processed_chars: receipt?.processed_chars, total_bytes: receipt?.total_bytes, cap_bytes: receipt?.cap_bytes,
window_rule: receipt?.window_rule, prior_facts: receipt?.prior_facts } });
- expected.push({ engine: index, calls: 0, skipped: 1, processed: 0, factsKept: true,
+ expected.push({ engine: index, calls: 0, segmentReads: 0, bytesRead: 0, skipped: 1, processed: 0, factsKept: true,
receipt: { kind: 'skipped_too_large', processed_chars: 0, total_bytes: Number(huge.body_bytes), cap_bytes: CONVERSATION_WINDOW_BYTES,
window_rule: 'prior_facts_kept', prior_facts: 2 } });
}