Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(large-pages): PR 4 4b facts backstop extracts only unextracted windows of a segmented page

garrytanbf245aedbe70
diff --git a/src/core/facts/backstop-segments.ts b/src/core/facts/backstop-segments.ts
new file mode 100644
index 0000000000..1a866498a5
--- /dev/null
+++ b/src/core/facts/backstop-segments.ts
@@ -0,0 +1,116 @@
+/**
+ * The facts backstop over a segmented page (wave-b spec 8.2 "Facts backstop", 8.3; PR 4 lane 4b): new occurrences
+ * only, in MAX_TURN_TEXT_CHARS windows cut at line starts, newest first, each window reserved against the page's
+ * spend cap (reservePageSpend, facts:<model>) before its extraction.
+ *
+ * Per occurrence a page_segment_derivations row (kind facts_backstop) records the segment sha, a context hash (region,
+ * model, window cap, observation date) and the windows extracted (ordinal, text sha, facts inserted). A window an
+ * earlier run extracted under the same context is never extracted again: in the same occurrence (a partial run), or
+ * verbatim in a retired one (a rewritten tail keeps its earlier windows), so an append pays for its new text plus the
+ * one window it grew. Replaces planSegmentedExtraction's whole-body pass and its watermark for segmented pages; the
+ * page_extraction_state receipt is cleared, a stopped occurrence's receipt lives on its row.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { estimateChatCallUsd, reservePageSpend, spendGrant } from '../page-embedding-budget.ts';
+import { setExtractionReceipt } from '../extraction-watermark.ts';
+import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';
+import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';
+import { MAX_TURN_TEXT_CHARS, getFactsExtractionMaxTokens } from './extract.ts';
+
+const KIND = 'facts_backstop';
+/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */
+export const FACTS_BACKSTOP_DERIVATION_VERSION = 1;
+
+interface WindowRecord { ordinal: number; sha: string; facts: number }
+
+const records = (row: SegmentDerivationRow | undefined): WindowRecord[] => {
+ const windows = (row?.output as { windows?: unknown } | null)?.windows;
+ return Array.isArray(windows) ? windows as WindowRecord[] : [];
+};
+const sha = (text: string) => createHash('sha256').update(text).digest('hex');
+const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
+
+/** Consecutive windows of at most \`cap\` characters covering \`text\`, cut after a newline when one falls in the window, never inside a surrogate pair. */
+export function lineWindows(text: string, cap: number): string[] {
+ const out: string[] = [];
+ let start = 0;
+ while (start < text.length) {
+ let end = Math.min(text.length, start + cap);
+ if (end < text.length) {
+ const newline = text.lastIndexOf('\n', end - 1);
+ if (newline >= start) end = newline + 1;
+ else if (text.charCodeAt(end - 1) >= 0xd800 && text.charCodeAt(end - 1) <= 0xdbff) end--;
+ }
+ out.push(text.slice(start, end));
+ start = end;
+ }
+ return out;
+}
+
+export interface SegmentedBackstopRun<R extends { inserted: number; skipped_reason?: unknown }> {
+ engine: BrainEngine;
+ page: { id: number; body_storage: 'segmented'; body_bytes?: number | null };
+ model: string;
+ /** Observation date the extractor is told (part of the context: a change re-extracts). */
+ observation: string | null;
+ signal?: AbortSignal;
+ /** One window through the backstop pipeline. A result with \`skipped_reason\` stops the run; that window stays unextracted. */
+ extract(text: string): Promise<R>;
+}
+
+/**
+ * The backstop's windows of every new or changed occurrence of a segmented page, newest first, until the cap refuses
+ * or a window is skipped. Returns each window's pipeline result, in call order, and why the run stopped (null: done).
+ */
+export async function runSegmentedBackstop<R extends { inserted: number; skipped_reason?: unknown }>(run: SegmentedBackstopRun<R>):
+ Promise<{ results: R[]; stop: 'cap_reached' | 'skipped' | null }> {
+ const { engine, page } = run;
+ const { body, occurrences } = await readConversationOccurrences(engine, page.id);
+ const context = { model: run.model, cap: MAX_TURN_TEXT_CHARS, observation: run.observation };
+ const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256,
+ contextHash: segmentDerivationContextHash(KIND, { entryState: { region: o.row.region }, page: context }) }));
+ const prior = await engine.readSegmentDerivations(page.id, { kind: KIND });
+ const plan = planSegmentDerivations(KIND, FACTS_BACKSTOP_DERIVATION_VERSION, live, prior);
+ const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));
+ const extracted = new Set<string>();
+ for (const row of [...plan.retired, ...prior]) {
+ if (row.version === FACTS_BACKSTOP_DERIVATION_VERSION) for (const w of records(row)) extracted.add(`${hex(row.contextHash)}:${w.sha}`);
+ }
+ const maxTokens = await getFactsExtractionMaxTokens(engine);
+ const results: R[] = [];
+ const derived: SegmentDerivationInput[] = [];
+ let stop: 'cap_reached' | 'skipped' | null = null;
+ const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));
+ for (const occurrence of [...occurrences].reverse()) {
+ const segment = todo.get(occurrence.row.occurrenceId);
+ if (!segment || stop) continue;
+ const old = priorRow.get(segment.occurrenceId);
+ const done = new Map((old && old.version === FACTS_BACKSTOP_DERIVATION_VERSION && hex(old.contextHash) === hex(segment.contextHash) ? records(old) : [])
+ .map(w => [w.ordinal, w]));
+ const windows = lineWindows(await readOccurrenceText(engine, body, occurrence.row), MAX_TURN_TEXT_CHARS);
+ for (let ordinal = windows.length - 1; ordinal >= 0; ordinal--) {
+ const text = windows[ordinal]!;
+ const key = sha(text);
+ if (done.get(ordinal)?.sha === key) continue;
+ if (extracted.has(`${hex(segment.contextHash)}:${key}`) || !text.trim()) { done.set(ordinal, { ordinal, sha: key, facts: 0 }); continue; }
+ if (run.signal?.aborted) { stop = 'skipped'; break; }
+ const decision = await reservePageSpend(engine, page, `facts:${run.model}`, estimateChatCallUsd(run.model, text.length, maxTokens));
+ if (decision.kind === 'refused') { stop = 'cap_reached'; break; }
+ const result = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined, () => run.extract(text));
+ results.push(result);
+ if (result.skipped_reason) { stop = 'skipped'; break; }
+ done.set(ordinal, { ordinal, sha: key, facts: result.inserted });
+ extracted.add(`${hex(segment.contextHash)}:${key}`);
+ }
+ const kept = windows.flatMap((text, ordinal) => done.get(ordinal)?.sha === sha(text) ? [done.get(ordinal)!] : []);
+ const finished = kept.length === windows.length;
+ derived.push({ pageId: page.id, kind: KIND, occurrenceId: segment.occurrenceId, version: FACTS_BACKSTOP_DERIVATION_VERSION,
+ segmentSha256: segment.sha256, contextHash: segment.contextHash, state: finished ? 'done' : 'partial', output: { windows: kept },
+ receipt: finished ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: kept.length, windows_total: windows.length } });
+ }
+ if (derived.length) await engine.upsertSegmentDerivations(derived);
+ await engine.retireSegmentDerivations(page.id, live.map(segment => segment.occurrenceId), { kind: KIND });
+ await setExtractionReceipt(engine, page.id, KIND, null);
+ return { results, stop };
+}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 9e832869a8..f65ab7df00 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -60,9 +60,9 @@ import { maintenanceTransaction } from '../persistence/attribution.ts';
import type { FactNotabilityFilter } from './notability-filter.ts';
import { intentContentOrigin } from '../trust/channel.ts';
import { readTaintInputs, derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';
-import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, mergeGateTally, type GateTally } from '../trust/derived-gate.ts';
import { decideFactWrite } from '../write-gate-store.ts';
-import { commitExtractionPlan, planExtraction, planSegmentedExtraction, readPageWatermark, type InputTruncated } from '../extraction-watermark.ts';
+import { commitExtractionPlan, planExtraction, readPageWatermark, type InputTruncated } from '../extraction-watermark.ts';
// The notability-filter vocabulary lives in notability-filter.ts; re-exported for existing importers.
export { NOTABILITY_FILTERS, coerceNotabilityFilter, type FactNotabilityFilter } from './notability-filter.ts';
@@ -588,19 +588,16 @@ async function runPipeline(
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
): Promise<PipelineResult & { input_truncated?: InputTruncated }> {
+ if (parsedPage.segmentedPageId !== undefined) return runSegmentedPipeline(parsedPage, parsedPage.segmentedPageId, ctx, abortSignal);
// Large pages A7: past the watermark the extractor reads only the appended
// tail; without a usable one it reads the head and the receipt says so.
const { MAX_TURN_TEXT_CHARS } = await import('./extract.ts');
const { pageId, stored } = await readPageWatermark(ctx.engine, ctx.sourceId, parsedPage.slug, 'facts_backstop');
- // A segmented page is planned over its segments; its whole body is never one string, so the turn text is the plan's.
- const planOpts = { cap: MAX_TURN_TEXT_CHARS, pipeline: 'facts_backstop', emptyTail: 'skip' } as const;
- const plan = parsedPage.segmentedPageId !== undefined
- ? await planSegmentedExtraction(ctx.engine, parsedPage.segmentedPageId, stored, planOpts)
- : planExtraction(parsedPage.compiled_truth, stored, planOpts);
+ const plan = planExtraction(parsedPage.compiled_truth, stored, { cap: MAX_TURN_TEXT_CHARS, pipeline: 'facts_backstop', emptyTail: 'skip' });
if (!plan.text) return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };
const result = await runPipelineWithBody(
{
- turnText: parsedPage.segmentedPageId !== undefined ? plan.text : parsedPage.compiled_truth,
+ turnText: parsedPage.compiled_truth,
...(plan.mode === 'full' ? {} : { extractText: plan.text }),
isDreamGenerated: false, // eligibility check already rejected dream pages
ref: parsedPage.slug,
@@ -616,6 +613,27 @@ async function runPipeline(
return plan.truncated ? { ...result, input_truncated: plan.truncated } : result;
}
+/**
+ * A segmented page (wave-b spec 8.2): the windows of its new occurrences only, newest first under the per-page spend
+ * cap (backstop-segments.ts), each through the pipeline as its own turn; the window results summed.
+ */
+async function runSegmentedPipeline(parsedPage: ParsedPageInput, pageId: number, ctx: FactsBackstopCtx, abortSignal?: AbortSignal): Promise<PipelineResult> {
+ const observationDate = resolveObservationDate({ slug: parsedPage.slug, frontmatter: parsedPage.frontmatter });
+ const { getFactsExtractionModel } = await import('./extract.ts');
+ const { runSegmentedBackstop } = await import('./backstop-segments.ts');
+ const { results } = await runSegmentedBackstop<PipelineResult>({ engine: ctx.engine, page: { id: pageId, body_storage: 'segmented' },
+ model: ctx.model ?? await getFactsExtractionModel(ctx.engine), observation: observationDate ? JSON.stringify(observationDate) : null, signal: abortSignal,
+ extract: text => runPipelineWithBody({ turnText: text, isDreamGenerated: false, ref: parsedPage.slug, pageSlug: parsedPage.slug, observationDate }, ctx, abortSignal) });
+ const sum = (a?: number, b?: number) => a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);
+ return results.reduce<PipelineResult>((a, b) => ({
+ inserted: a.inserted + b.inserted, duplicate: a.duplicate + b.duplicate, superseded: a.superseded + b.superseded,
+ fact_ids: [...a.fact_ids, ...b.fact_ids], entity_slugs: [...new Set([...a.entity_slugs, ...b.entity_slugs])],
+ skipped_reason: a.skipped_reason ?? b.skipped_reason, write_gate: mergeGateTally(a.write_gate, b.write_gate),
+ fence_refused: sum(a.fence_refused, b.fence_refused), would_dedup_same_page: sum(a.would_dedup_same_page, b.would_dedup_same_page),
+ withdrawn_skipped: sum(a.withdrawn_skipped, b.withdrawn_skipped), refused: a.refused || b.refused ? [...a.refused ?? [], ...b.refused ?? []] : undefined,
+ }), { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] });
+}
+
/**
* Inner pipeline body. Shared between runFactsBackstop (page-shape entry)
* and runFactsPipeline (raw turn-text entry). Eligibility + kill-switch
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 7eed7773a9..1acf2b5170 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -20,8 +20,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
import { deriveDateContext, parseConversation } from '../conversation-parser/parse.ts';
import { writeDerivedFacts } from '../persistence/derived-facts.ts';
-import { reservationCostUsd } from '../budget/reservation-cost.ts';
-import { reservePageSpend, spendGrant } from '../page-embedding-budget.ts';
+import { estimateChatCallUsd, reservePageSpend, spendGrant } from '../page-embedding-budget.ts';
import { setExtractionReceipt } from '../extraction-watermark.ts';
import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor, sourceWindowKey, type SegmentDerivationInput,
type SegmentDerivationRow, type SourceWindow } from '../page-body/derivations.ts';
@@ -39,11 +38,6 @@ import { getFactsExtractionMaxTokens, resolveFactsExtractionModel } from './extr
const KIND = 'conversation_facts';
/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */
export const CONVERSATION_FACTS_DERIVATION_VERSION = 1;
-/** Rough characters per token for a reservation estimate, and the system prompt and header overhead per call. */
-const CHARS_PER_TOKEN = 4;
-const PROMPT_OVERHEAD_TOKENS = 1500;
-/** Per-1M-token rates for a model without a price: the reservation must still bound the spend. */
-const UNPRICED_CHAT_RATE = { input: 15, output: 75 };
/** The run counters this pass moves (a subset of ExtractConversationFactsResult). */
export interface SegmentedConversationCounters {
@@ -95,12 +89,6 @@ async function occurrenceWindows(engine: BrainEngine, body: SegmentedBody, occur
});
}
-/** What one extractor call may cost at most: the prompt estimate plus the full output ceiling. */
-function windowEstimateUsd(model: string, text: string, maxTokens: number): number {
- const input = Math.ceil(text.length / CHARS_PER_TOKEN) + PROMPT_OVERHEAD_TOKENS;
- return reservationCostUsd(model, 'chat', input, maxTokens) ?? (input * UNPRICED_CHAT_RATE.input + maxTokens * UNPRICED_CHAT_RATE.output) / 1_000_000;
-}
-
/**
* 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.
@@ -160,7 +148,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
if (run.segmentLimit > 0 && extractedWindows >= run.segmentLimit) { stop = 'segment_limit'; break; }
if (run.signal?.aborted) throw new Error('aborted');
if (run.dryRun) { extractedWindows++; continue; }
- const decision = await reservePageSpend(engine, page, `facts:${model}`, windowEstimateUsd(model, w.text, maxTokens));
+ const decision = await reservePageSpend(engine, page, `facts:${model}`, estimateChatCallUsd(model, w.text.length, maxTokens));
if (decision.kind === 'refused') { stop = 'cap_reached'; break; }
const out = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined,
() => extractConversationWindow(run, page, w.seg, w.text, 0, entityHints));
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index 08de886e8a..eb56a9c8ee 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -37,6 +37,7 @@ import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './conte
import type { BodyStorage, ManifestRow } from './page-body/types.ts';
import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';
import { estimateCostFromChars } from './embedding-pricing.ts';
+import { reservationCostUsd } from './budget/reservation-cost.ts';
import { PAGE_INLINE_MAX_BYTES, budgetRowAppliesFilter, isLargePageBytes } from './page-size-policy.ts';
import { isEmbedSkipped } from './embed-skip.ts';
import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';
@@ -237,6 +238,18 @@ export async function reservePageSpend(engine: BrainEngine, page: BudgetPage, si
});
}
+/** Rough characters per token and the system prompt overhead of one chat call, for a reservation estimate. */
+const CHARS_PER_TOKEN = 4;
+const PROMPT_OVERHEAD_TOKENS = 1500;
+/** Per-1M-token rates for a chat model without a price: the reservation still bounds the spend. */
+const UNPRICED_CHAT_RATE = { input: 15, output: 75 };
+
+/** What one chat call over `chars` of input may cost at most (the prompt estimate plus the full output ceiling): the estimate a paid derivation reserves. */
+export function estimateChatCallUsd(model: string, chars: number, maxOutputTokens: number): number {
+ const input = Math.ceil(chars / CHARS_PER_TOKEN) + PROMPT_OVERHEAD_TOKENS;
+ return reservationCostUsd(model, 'chat', input, maxOutputTokens) ?? (input * UNPRICED_CHAT_RATE.input + maxOutputTokens * UNPRICED_CHAT_RATE.output) / 1_000_000;
+}
+
export interface PageBudgetReport { slug: string; source_id: string; state: Exclude<PageBudgetState, 'open'>; reason: string | null;
spent_usd: number; cap_usd: number | null; pending_chunks: number; pending_chars: number }
diff --git a/test/e2e/conversation-facts-incremental-postgres.test.ts b/test/e2e/conversation-facts-incremental-postgres.test.ts
index 2fef346981..18a75a4f17 100644
--- a/test/e2e/conversation-facts-incremental-postgres.test.ts
+++ b/test/e2e/conversation-facts-incremental-postgres.test.ts
@@ -5,7 +5,7 @@
*/
import { afterAll, beforeAll, describe } from 'bun:test';
import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
-import { defineConversationFactsIncrementalCases } from '../helpers/conversation-facts-incremental-cases.ts';
+import { defineConversationFactsIncrementalCases, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';
import { hasDatabase } from './helpers.ts';
(hasDatabase() ? describe : describe.skip)('conversation facts incremental [postgres]', () => {
@@ -13,4 +13,5 @@ import { hasDatabase } from './helpers.ts';
beforeAll(async () => { brain = await openAppendBrain('postgres'); }, 120_000);
afterAll(async () => { await brain.close(); }, 120_000);
defineConversationFactsIncrementalCases({ getBrain: () => brain });
+ defineSegmentedBackstopCases({ getBrain: () => brain });
});
diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.ts
index 1542ed6058..9912561e16 100644
--- a/test/helpers/conversation-facts-incremental-cases.ts
+++ b/test/helpers/conversation-facts-incremental-cases.ts
@@ -20,6 +20,11 @@ import { runExtractConversationFactsCore } from '../../src/commands/extract-conv
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 type { AppendBrain } from './append-brain.ts';
+import { runFactsBackstop } from '../../src/core/facts/backstop.ts';
+import { lineWindows } from '../../src/core/facts/backstop-segments.ts';
+import { MAX_TURN_TEXT_CHARS } from '../../src/core/facts/extract.ts';
+import { truthLead } from '../../src/core/page-body/segment-blocks.ts';
+import { __setChatTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';
const SPEAKERS = ['Alice Example', 'Bob Example', 'Carol Example'];
const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast', 'retention', 'deploy'];
@@ -200,3 +205,85 @@ ${chatDays(100, 3, 1)}`;
await engine.setConfig('facts.extraction_model', '');
}, 600_000);
}
+
+/**
+ * The facts backstop over a segmented page (wave-b spec 8.2 "Facts backstop"): an import extracts every
+ * MAX_TURN_TEXT_CHARS window of every occurrence once; an append (by a remote writer) extracts only the windows no run
+ * extracted before (the new text plus the window it grew), never the page again; an unchanged page extracts nothing;
+ * a cap the first window does not fit refuses before any call. Fake chat transport, counted by prompt.
+ */
+export function defineSegmentedBackstopCases(opts: { getBrain: () => AppendBrain }): void {
+ const slug = `notes/backstop-segmented-${randomUUID().slice(0, 8)}`;
+ let prompts: string[] = [];
+ let firstPrompts: string[] = [];
+ const pageOf = async (engine: BrainEngine, s: string) => (await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]))[0]!;
+ const backstop = async (engine: BrainEngine, s: string) => {
+ const page = await pageOf(engine, s);
+ return runFactsBackstop({ slug: s, type: 'note', compiled_truth: await truthLead(engine, Number(page.id), 4096), frontmatter: {}, segmentedPageId: Number(page.id) },
+ { engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline' });
+ };
+ const install = () => {
+ prompts = [];
+ __setChatTransportForTests(async (o: ChatOpts): Promise<ChatResult> => {
+ prompts.push(JSON.stringify(o.messages));
+ return { text: '{"facts":[]}', blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ };
+
+ test('an import extracts each window of each occurrence once; an unchanged page extracts nothing', async () => {
+ const { engine, seed, body } = opts.getBrain();
+ await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await seed(slug, chatPage('Backstop', chatDays(400, 100, 5)).replace('type: conversation', 'type: note'));
+ const page = await pageOf(engine, slug);
+ const truth = Buffer.from((await body(slug)).truth, 'utf8');
+ const manifest = await engine.readManifest(Number(page.id));
+ const expected = manifest.flatMap(row => lineWindows(truth.subarray(row.byteStart, row.byteStart + row.byteLen).toString('utf8'), MAX_TURN_TEXT_CHARS));
+ install();
+ try {
+ await backstop(engine, slug);
+ firstPrompts = prompts;
+ const rows = await engine.readSegmentDerivations(Number(page.id), { kind: 'facts_backstop' });
+ expect(manifest.length).toBeGreaterThan(2);
+ expect({ calls: prompts.length, distinct: new Set(prompts).size, rows: rows.length, states: [...new Set(rows.map(r => r.state))] })
+ .toEqual({ calls: expected.length, distinct: expected.length, rows: manifest.length, states: ['done'] });
+ install();
+ await backstop(engine, slug);
+ expect(prompts.length).toBe(0);
+ } finally { __setChatTransportForTests(null); }
+ }, 600_000);
+
+ test('an append by a remote writer extracts only the new text\'s windows', async () => {
+ const brain = opts.getBrain();
+ const appended = chatDays(500, 3, 5);
+ expect(await brain.call('append_page', { slug, text: appended, request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ install();
+ try {
+ await backstop(brain.engine, slug);
+ expect(prompts.filter(p => firstPrompts.includes(p))).toEqual([]);
+ expect(prompts.length).toBeGreaterThanOrEqual(Math.ceil(appended.length / MAX_TURN_TEXT_CHARS));
+ expect(prompts.length).toBeLessThanOrEqual(Math.ceil(appended.length / MAX_TURN_TEXT_CHARS) + 2);
+ const page = await pageOf(brain.engine, slug);
+ const rows = await brain.engine.readSegmentDerivations(Number(page.id), { kind: 'facts_backstop' });
+ expect({ rows: rows.length, states: [...new Set(rows.map(r => r.state))] }).toEqual({ rows: (await brain.engine.readManifest(Number(page.id))).length, states: ['done'] });
+ } finally { __setChatTransportForTests(null); }
+ }, 600_000);
+
+ test('a cap the newest window does not fit refuses before any call', async () => {
+ const { engine, seed } = opts.getBrain();
+ const capped = `notes/backstop-capped-${randomUUID().slice(0, 8)}`;
+ await seed(capped, chatPage('Backstop capped', chatDays(600, 100, 6)).replace('type: conversation', 'type: note'));
+ await engine.setConfig(PAGE_EMBED_CAP_KEY, '0.000001');
+ install();
+ try {
+ await backstop(engine, capped);
+ const page = await pageOf(engine, capped);
+ const rows = await engine.readSegmentDerivations(Number(page.id), { kind: 'facts_backstop' });
+ expect({ calls: prompts.length, receipts: rows.map(r => r.receipt) })
+ .toEqual({ calls: 0, receipts: [expect.objectContaining({ kind: 'unread_windows', pipeline: 'facts_backstop', reason: 'cap_reached', windows_read: 0 })] });
+ } finally {
+ __setChatTransportForTests(null);
+ await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ }
+ }, 600_000);
+}
diff --git a/test/large-pages/conversation-facts-incremental.test.ts b/test/large-pages/conversation-facts-incremental.test.ts
index af6c398f6a..a9281eceaf 100644
--- a/test/large-pages/conversation-facts-incremental.test.ts
+++ b/test/large-pages/conversation-facts-incremental.test.ts
@@ -4,7 +4,7 @@
*/
import { afterAll, beforeAll, describe } from 'bun:test';
import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
-import { defineConversationFactsIncrementalCases } from '../helpers/conversation-facts-incremental-cases.ts';
+import { defineConversationFactsIncrementalCases, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';
let brain: AppendBrain;
@@ -13,4 +13,5 @@ afterAll(async () => { await brain.close(); }, 120_000);
describe('conversation facts incremental [pglite]', () => {
defineConversationFactsIncrementalCases({ getBrain: () => brain });
+ defineSegmentedBackstopCases({ getBrain: () => brain });
});