Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(large-pages): PR 4 4b extract_atoms per window on segmented pages; doctor reads segment receipts
garrytan4ebe5f704ccd
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 1b297d95c9..3a91ec71ec 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -119,8 +119,8 @@ src/core/cycle/edge-contradictions.ts removeTimelineLine call:serializeMarkdownsrc/core/cycle/edge-contradictions.ts removeTimelineLine field SEGWsrc/core/cycle/extract-atoms-page-state.ts transferLegacyAtomPageState field META compares two snapshots; segmented page: getter throws page_body_segmentedsrc/core/cycle/extract-atoms.ts discoverExtractablePages field STREAM see sql row; CAS is on content_hash + knowledge_revision-src/core/cycle/extract-atoms.ts discoverExtractablePages sql STREAM minCompiledTruthChars is false for NULL: segmented pages are never discovered (skip until per-segment extraction, PR 4)-src/core/cycle/extract-atoms.ts minCompiledTruthChars sql STREAM false for a segmented page (NULL body): skip+src/core/cycle/extract-atoms.ts discoverExtractablePages sql STREAM segmented pages are matched by body_storage instead and extracted per occurrence window (extract-atoms-segments.ts, PR 4 4b)+src/core/cycle/extract-atoms.ts minCompiledTruthChars sql STREAM false for a segmented page (NULL body); discovery ORs body_storage = 'segmented' (PR 4 4b)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms call:serializeMarkdown SEGWsrc/core/cycle/extract-facts.ts canonicalCacheState field INLINE inline arm; a segmented page compares its stored regions with the canonical file by length and SHA-256 (segmentedBodyMatchesFile)src/core/cycle/extract-facts.ts planFenceReconcile field NONE view.timeline is the parsed facts fence of the timeline section (FactsFenceView); a segmented page reads it from its marker segments (segmentedFactsFenceView)diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.tsindex 8b18d9ea0c..fce2b657bc 100644--- a/src/commands/doctor/checks/extraction-input.ts+++ b/src/commands/doctor/checks/extraction-input.ts@@ -9,11 +9,18 @@* read. Warn when a receipt has a remedy (the atoms cap, an oversized* conversation input); facts-only receipts are reported as info. Reads the* database only.+ *+ * PR 4 (Wave B incremental derivation, transcripts): a segmented page's paid+ * derivations keep their receipt per occurrence on page_segment_derivations+ * (`unread_windows`: the run stopped before every window was read, at the+ * per-page spend cap or a window limit; the next run resumes there). Both tables+ * are read; a page counts once per pipeline and receipt kind.*/import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { agentFix, checkError } from '../check-fix.ts';import { EXTRACT_MAX_INPUT_CHARS_KEY } from '../../../core/cycle/extract-atoms-input.ts';+import { PAGE_EMBED_CAP_KEY } from '../../../core/page-embedding-budget.ts';interface ReceiptGroup { pipeline: string; kind: string; pages: number; samples: string[] }@@ -23,37 +30,51 @@ const REMEDY: Record<string, string> = {conversation_facts: 'the parser input (page body or raw_transcript sidecar) is over the conversation body cap and was not read; trim the sidecar under the cap or remove raw_transcript from the page frontmatter, then gbrain extract-conversation-facts --slug <slug>',};+const UNREAD_WINDOWS = 'unread_windows';+const UNREAD_REMEDY = `the run stopped before every window of the page was read (the receipt's reason: the per-page spend cap, a window limit or a skipped window); the next run resumes where it stopped, and when the cap stopped it: gbrain config set ${PAGE_EMBED_CAP_KEY} <usd>`;+const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_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.pipeline] ?? 'see the receipt in page_extraction_state'}`;+ `${g.pipeline}/${g.kind}: ${g.pages} page(s) (e.g. ${g.samples.join(', ')}); ${remedy(g) ?? 'see the receipt in page_extraction_state'}`;async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];try {const rows = await connectedEngine(ctx).executeRaw<{ pipeline: string; kind: string; pages: number; samples: string[] }>(- `SELECT s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, count(*)::int AS pages,- (array_agg(p.source_id || ':' || p.slug ORDER BY s.updated_at DESC))[1:3] AS samples- FROM page_extraction_state s JOIN pages p ON p.id = s.page_id AND p.deleted_at IS NULL- WHERE s.input_truncated IS NOT NULL+ `WITH receipts AS (+ SELECT s.page_id, s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, s.updated_at+ FROM page_extraction_state s WHERE s.input_truncated IS NOT NULL+ UNION ALL+ SELECT d.page_id, d.pipeline, COALESCE(d.receipt->>'kind', 'unknown') AS kind, max(d.updated_at) AS updated_at+ FROM page_segment_derivations d WHERE d.receipt IS NOT NULL GROUP BY 1, 2, 3)+ SELECT r.pipeline, r.kind, count(DISTINCT r.page_id)::int AS pages,+ (array_agg(p.source_id || ':' || p.slug ORDER BY r.updated_at DESC))[1:3] AS samples+ FROM receipts r JOIN pages p ON p.id = r.page_id AND p.deleted_at IS NULLGROUP BY 1, 2 ORDER BY 1, 2`);const groups: ReceiptGroup[] = rows.map(r => ({ pipeline: r.pipeline, kind: r.kind, pages: Number(r.pages), samples: r.samples ?? [] }));- const details = { groups: groups.map(g => ({ ...g, remedy: REMEDY[g.pipeline] ?? null })) };+ const details = { groups: groups.map(g => ({ ...g, remedy: remedy(g) })) };if (!groups.length) {checks.push({ name: 'extraction_input_truncated', status: 'ok', message: 'Every page extraction read all of its input (no head-only, tail-window or size-skip receipts).', details });return checks;}const summary = `Page extractions that read only part of their input: ${groups.map(describe).join('. ')}.`;- const actionable = groups.filter(g => g.pipeline !== 'facts_backstop');+ const actionable = groups.filter(g => g.pipeline !== 'facts_backstop' || g.kind === UNREAD_WINDOWS);if (!actionable.length) {checks.push({ name: 'extraction_input_truncated', status: 'ok', severity: 'info', readiness_state: 'degraded', message: summary, details });return checks;}- const atoms = actionable.find(g => g.pipeline === 'extract_atoms');+ const atoms = actionable.find(g => g.pipeline === 'extract_atoms' && g.kind !== UNREAD_WINDOWS);+ const capped = actionable.some(g => g.kind === UNREAD_WINDOWS);checks.push({ name: 'extraction_input_truncated', status: 'warn', message: summary, details,...(atoms? { fix: agentFix(['gbrain', 'config', 'set', EXTRACT_MAX_INPUT_CHARS_KEY, '<n>'],'A higher cap lets the next extract_atoms cycle read more of each cut page; it raises model spend, so the value is the user\'s call.', 'extraction_input_truncated',{ ask_user: true, consent: ['paid'], inputs: [{ name: 'n', how: 'a character count above the cut pages\' sizes, chosen with the user' }] }) }- : { fix_unavailable_reason: 'operator_judgement' as const }) });+ : capped+ ? { fix: agentFix(['gbrain', 'config', 'set', PAGE_EMBED_CAP_KEY, '<usd>'],+ 'A higher per-page cap lets the next run read the windows the cap stopped; it raises model spend, so the value is the user\'s call.', 'extraction_input_truncated',+ { ask_user: true, consent: ['paid'], inputs: [{ name: 'usd', how: 'a per-page dollar cap chosen with the user' }] }) }+ : { fix_unavailable_reason: 'operator_judgement' as const }) });} catch (error) {checks.push(checkError('extraction_input_truncated', 'read the extraction receipts', error, { details: { health: 'unknown' } }));}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 55aa501c0a..e467dd5da5 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1025,6 +1025,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// PR 4 (Wave B incremental derivation, transcripts)// PR 4 4b{ 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: 'The per-page spend cap now also covers fact and atom extraction on large pages; doctor lists pages it stopped.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.tsindex 83d9583d41..ac18f52c5a 100644--- a/src/core/cycle/extract-atoms-input.ts+++ b/src/core/cycle/extract-atoms-input.ts@@ -67,6 +67,7 @@ export interface ExtractAtomsInput {* the #6503 disposition holds (no completion stamp, nothing retired).*/export function extractAtomsInput(item: ExtractAtomsItem, maxInputChars: number, watermark: StoredWatermark | null = null): ExtractAtomsInput {+ if (item.kind === 'page' && item.window) return { promptContent: item.content, truncated: false, inputChars: item.content.length };if (item.kind === 'page') {const plan = planExtraction(item.content, watermark, { cap: maxInputChars, pipeline: 'extract_atoms', emptyTail: 'head' });return { promptContent: plan.text, truncated: plan.mode !== 'full', inputChars: item.content.length, plan };diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.tsindex f6bbf52149..6bc3f1da2a 100644--- a/src/core/cycle/extract-atoms-page-state.ts+++ b/src/core/cycle/extract-atoms-page-state.ts@@ -3,6 +3,7 @@ import type { PageSnapshot } from '../page-state/types.ts';import { stableJson } from '../persistence/digest.ts';import type { BrainEngine } from '../engine.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import type { PageEmbedGrant } from '../page-embedding-budget.ts';/*** gbrain#4148: consecutive same-content failures of a content-deterministic@@ -23,6 +24,19 @@ export interface AtomPageInput {content: string;contentHash: string;identity?: AtomPageIdentity;+ /** Discovery found a segmented page: `content` is empty until extract-atoms-segments.ts expands it into windows. */+ segmented?: boolean;+ /** PR 4 4b: `content` is one window of a segmented page's occurrence, not the page. */+ window?: AtomPageWindow;+}++// PR 4 (Wave B incremental derivation, transcripts)+/** One window of a segmented page (extract-atoms-segments.ts); its methods are bound to the page's derivation plan. */+export interface AtomPageWindow {+ /** Reserve this window's model call against the page's spend cap. Null: refused, the page's remaining windows are skipped and the receipt recorded. */+ reserve(model: string, maxOutputTokens: number): Promise<{ grant?: Pick<PageEmbedGrant, 'settle'> } | null>;+ /** Record the window extracted with these atoms. Returns the atom slugs retired when this settles the page. */+ settle(atomSlugs: string[]): Promise<string[]>;}export class AtomPageStateError extends Error {@@ -142,3 +156,36 @@ export async function transferLegacyAtomPageState(engine: SqlEngine, before: Pag[after.page.id, after.sourceIncarnation, after.page.content_hash, after.revision, state.fail_count, state.tombstoned]);return rows.length > 0;}++/**+ * Soft-delete a source's atoms from earlier extractions (a different or+ * provisional source_hash) that the current, completed extraction did not+ * re-produce. Imported atoms (`imported_from`) and managed atoms are left+ * alone. Best-effort: a failure leaves duplicates, never loses current atoms.+ */+export async function retireStaleAtoms(+ engine: BrainEngine,+ sourceId: string,+ origin: { key: 'source_slug' | 'source_path'; value: string },+ hash16: string,+ currentSlugs: string[],+): Promise<string[]> {+ try {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages+ WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL+ AND frontmatter->>'${origin.key}' = $2+ AND COALESCE(frontmatter->>'source_hash', '') <> $3+ AND (frontmatter->>'imported_from') IS NULL+ AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'+ AND NOT (slug = ANY($4::text[]))`,+ [sourceId, origin.value, hash16, currentSlugs],+ );+ const stale = rows.map(r => r.slug);+ for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));+ return stale;+ } catch (err) {+ console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);+ return [];+ }+}diff --git a/src/core/cycle/extract-atoms-segments.ts b/src/core/cycle/extract-atoms-segments.tsnew file mode 100644index 0000000000..9f9b2f348c--- /dev/null+++ b/src/core/cycle/extract-atoms-segments.ts@@ -0,0 +1,135 @@+/**+ * extract_atoms over a segmented page (wave-b spec 8.2 "extract_atoms", 8.3; PR 4 lane 4b). Discovery finds a+ * segmented page with no complete scan state for its content hash; expandSegmentedAtomPages turns it into work items+ * that are <= input-cap windows of its new or changed occurrences, cut at line starts, newest first. The phase loop+ * extracts each window like a page item and, instead of the page completion stamp, settles the window on the+ * occurrence's page_segment_derivations row (kind extract_atoms: segment sha, context hash, each window's text sha and+ * the atom slugs it produced). An append offers only the new text's windows; a window whose text an earlier run+ * extracted under the same context is never offered again, so a rewritten tail keeps its earlier windows' atoms.+ *+ * Each window's call reserves against the page's spend cap (reservePageSpend, atoms:<model>) first; a refusal skips the+ * page's remaining windows and records an unread_windows receipt on each unfinished occurrence's row. When every live+ * occurrence is settled, atoms of windows that left the page (and atoms of an earlier whole-page extraction) are+ * retired and the page's scan state is stamped complete for its content hash, so discovery skips it until it changes.+ * The completion CAS stays on content_hash + knowledge_revision (completeAtomReceipts). Managed brains do not extract+ * segmented pages (their publication path is whole-page).+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { estimateChatCallUsd, reservePageSpend } from '../page-embedding-budget.ts';+import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';+import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';+import { lineWindows } from '../facts/backstop-segments.ts';+import { retireStaleAtoms, writeAtomPageState, type AtomPageInput, type AtomPageWindow } from './extract-atoms-page-state.ts';++const KIND = 'extract_atoms';+/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */+export const EXTRACT_ATOMS_DERIVATION_VERSION = 1;+/** Windows one run offers per page; the rest wait for the next run (the page is not stamped complete). */+export const MAX_ATOM_WINDOWS_PER_PAGE_RUN = 16;++interface WindowRecord { ordinal: number; sha: string; atoms: string[] }+interface OccurrenceState { occurrenceId: number; sha256: Uint8Array; contextHash: Uint8Array; total: number; done: Map<number, WindowRecord> }++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');++/** Segmented pages become their windows; other pages pass through. Returns the atoms retired by pages that settled with nothing left to extract. */+export async function expandSegmentedAtomPages(engine: BrainEngine, sourceId: string, pages: readonly AtomPageInput[],+ opts: { managed: boolean; cap: number; dryRun: boolean }): Promise<{ pages: AtomPageInput[]; retired: string[] }> {+ const out: AtomPageInput[] = [];+ const retired: string[] = [];+ for (const page of pages) {+ if (!page.segmented) { out.push(page); continue; }+ if (opts.managed || !page.identity) continue;+ const windows = await planPage(engine, sourceId, page, opts);+ if (windows.items.length) out.push(...windows.items);+ else if (windows.settled && !opts.dryRun) retired.push(...await windows.settle());+ }+ return { pages: out, retired };+}++async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInput, opts: { cap: number; dryRun: boolean }) {+ const pageId = page.identity!.pageId;+ const { body, occurrences } = await readConversationOccurrences(engine, pageId);+ const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256,+ contextHash: segmentDerivationContextHash(KIND, { entryState: { region: o.row.region }, page: { cap: opts.cap } }) }));+ const prior = await engine.readSegmentDerivations(pageId, { kind: KIND });+ const plan = planSegmentDerivations(KIND, EXTRACT_ATOMS_DERIVATION_VERSION, live, prior);+ const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));+ const extracted = new Map<string, string[]>();+ for (const row of [...plan.retired, ...prior]) {+ if (row.version === EXTRACT_ATOMS_DERIVATION_VERSION) for (const w of records(row)) extracted.set(`${hex(row.contextHash)}:${w.sha}`, w.atoms ?? []);+ }+ const states = new Map<number, OccurrenceState>();+ const items: AtomPageInput[] = [];+ let unread = false;+ let stop: 'cap_reached' | null = null;+ let open = 0;+ const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));+ const row = (state: OccurrenceState): SegmentDerivationInput => {+ const finished = state.done.size === state.total;+ return { pageId, kind: KIND, occurrenceId: state.occurrenceId, version: EXTRACT_ATOMS_DERIVATION_VERSION, segmentSha256: state.sha256,+ contextHash: state.contextHash, state: finished ? 'done' : 'partial', output: { windows: [...state.done.values()].sort((a, b) => a.ordinal - b.ordinal) },+ receipt: finished || !stop ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: state.done.size, windows_total: state.total } };+ };+ const settlePage = async (): Promise<string[]> => {+ const keep = new Set<string>();+ for (const current of plan.current) for (const w of records(current)) for (const slug of w.atoms ?? []) keep.add(slug);+ for (const state of states.values()) for (const w of state.done.values()) for (const slug of w.atoms) keep.add(slug);+ const gone = await retireStaleAtoms(engine, sourceId, { key: 'source_slug', value: page.slug }, '', [...keep]);+ await writeAtomPageState(engine, sourceId, page, 'complete');+ return gone;+ };+ for (const occurrence of [...occurrences].reverse()) {+ const segment = todo.get(occurrence.row.occurrenceId);+ if (!segment) continue;+ if (items.length >= MAX_ATOM_WINDOWS_PER_PAGE_RUN) { unread = true; break; }+ const old = priorRow.get(segment.occurrenceId);+ const same = old && old.version === EXTRACT_ATOMS_DERIVATION_VERSION && hex(old.contextHash) === hex(segment.contextHash);+ const texts = lineWindows(await readOccurrenceText(engine, body, occurrence.row), opts.cap);+ const state: OccurrenceState = { occurrenceId: segment.occurrenceId, sha256: segment.sha256, contextHash: segment.contextHash, total: texts.length,+ done: new Map((same ? records(old) : []).map(w => [w.ordinal, { ...w, atoms: w.atoms ?? [] }])) };+ states.set(segment.occurrenceId, state);+ for (let ordinal = texts.length - 1; ordinal >= 0; ordinal--) {+ const text = texts[ordinal]!;+ const key = sha(text);+ if (state.done.get(ordinal)?.sha === key) continue;+ state.done.delete(ordinal);+ const reused = extracted.get(`${hex(segment.contextHash)}:${key}`);+ if (reused || !text.trim()) { state.done.set(ordinal, { ordinal, sha: key, atoms: reused ?? [] }); continue; }+ if (items.length >= MAX_ATOM_WINDOWS_PER_PAGE_RUN) { unread = true; continue; }+ open++;+ const window: AtomPageWindow = {+ async reserve(model, maxOutputTokens) {+ if (opts.dryRun) return {};+ if (stop) return null;+ const decision = await reservePageSpend(engine, { id: pageId, body_storage: 'segmented' }, `atoms:${model}`,+ estimateChatCallUsd(model, text.length, maxOutputTokens));+ if (decision.kind === 'grant') return { grant: decision.grant };+ if (decision.kind !== 'refused') return {};+ stop = 'cap_reached';+ const unfinished = [...states.values()].filter(s => s.done.size < s.total);+ if (unfinished.length) await engine.upsertSegmentDerivations(unfinished.map(row));+ return null;+ },+ async settle(atomSlugs) {+ state.done.set(ordinal, { ordinal, sha: key, atoms: atomSlugs });+ await engine.upsertSegmentDerivations([row(state)]);+ open--;+ return open === 0 && !unread && !stop ? settlePage() : [];+ },+ };+ items.push({ ...page, segmented: false, content: text, window });+ }+ }+ if (!opts.dryRun) {+ if (states.size) await engine.upsertSegmentDerivations([...states.values()].map(row));+ await engine.retireSegmentDerivations(pageId, live.map(segment => segment.occurrenceId), { kind: KIND });+ }+ return { items, settled: !unread && open === 0, settle: settlePage };+}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 130fb4ac66..2753db3113 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -71,6 +71,8 @@ import { derivedWriteThrough, reportFileHolds } from './derived-write-through.tsimport { serializeMarkdown } from '../markdown.ts';import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone, type ExtractAtomsInput, type ExtractAtomsItem } from './extract-atoms-input.ts';import { commitExtractionPlan, readPageWatermark } from '../extraction-watermark.ts';+import { expandSegmentedAtomPages } from './extract-atoms-segments.ts';+import { spendGrant } from '../page-embedding-budget.ts';import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';@@ -94,8 +96,7 @@ import { OperationError } from '../ops/contract.ts';import { isOpPageSlug } from '../ops/context.ts';import type { WriteReceipt } from '../persistence/types.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';-import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';+import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, retireStaleAtoms, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';import { deriveTrust, lowerDerivedPage } from '../trust/taint.ts';import { derivedGateInput } from '../trust/derived-gate.ts';import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';@@ -409,7 +410,7 @@ export async function discoverExtractablePages((SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,p.slug,p.compiled_truth,- p.content_hash+ p.content_hash, p.body_storageFROM pages pWHERE p.source_id = $1AND p.type = ANY($2::text[])@@ -418,12 +419,12 @@ export async function discoverExtractablePages(AND COALESCE(p.frontmatter->>'imported_from', '') <> 'markdown-greenfield'AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'${RAW_SOURCE_HOLDER_EXCLUSION_SQL}- AND ${minCompiledTruthChars('$3')}+ AND (p.body_storage = 'segmented' OR ${minCompiledTruthChars('$3')})${MANAGED_ATOM_DISCOVERY_SQL}${PAGE_SCAN_STATE_EXCLUSION_SQL}${connectorExclusion}${hasFilter ? "AND p.slug = ANY($5::text[])" : ''}- AND NOT EXISTS (+ AND (p.body_storage = 'segmented' OR NOT EXISTS (SELECT 1FROM pages atomWHERE atom.type = 'atom'@@ -431,7 +432,7 @@ export async function discoverExtractablePages(AND atom.frontmatter->>'source_hash' = substring(p.content_hash from 1 for 16)AND COALESCE(atom.frontmatter->>'managed_extraction', '') <> 'true'AND atom.deleted_at IS NULL- )+ ))ORDER BY p.updated_at DESCLIMIT $4`;@@ -451,12 +452,14 @@ export async function discoverExtractablePages(slug: string;compiled_truth: string;content_hash: string;+ body_storage: string | null;}>(sql, params);return rows.map((r) => ({slug: r.slug,- content: r.compiled_truth,+ content: r.compiled_truth ?? '',contentHash: r.content_hash,- identity: { pageId: r.id, sourceIncarnation: r.source_incarnation, revision: r.knowledge_revision },+ identity: { pageId: Number(r.id), sourceIncarnation: r.source_incarnation, revision: r.knowledge_revision },+ ...(r.body_storage === 'segmented' ? { segmented: true } : {}),}));} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -761,6 +764,9 @@ export async function runPhaseExtractAtoms(await resolvePageDiscoveryLimit(engine),);}+ const segmented = await expandSegmentedAtomPages(engine, sourceId, pages, { managed: managed !== null, cap: maxInputChars, dryRun: opts.dryRun ?? false });+ pages = segmented.pages;+ if (segmented.retired.length) await atomFiles?.write([], segmented.retired);// 2. Apply transcript-side source-hash idempotency in ONE batch query// instead of N per-hash round trips. Page-side idempotency lives in@@ -828,7 +834,7 @@ export async function runPhaseExtractAtoms(}const pageItems: WorkItem[] = [];for (const p of pages) {- if (seenHashes.has(p.contentHash)) { duplicatesSkipped++; continue; }+ if (!p.window && seenHashes.has(p.contentHash)) { duplicatesSkipped++; continue; }seenHashes.add(p.contentHash);pageItems.push({ kind: 'page', ...p });}@@ -995,7 +1001,14 @@ export async function runPhaseExtractAtoms(let inputTruncated = 0; // #6503: items cut at the input cap this run (partial disposition, see extract-atoms-input.ts)async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {- await writeAtomPageState(engine, sourceId, item, 'complete');+ if (item.window) await atomFiles?.write([], await item.window.settle([])); // PR 4 4b: a segmented page's window settles on its derivation row+ else await writeAtomPageState(engine, sourceId, item, 'complete');+ }+ /** PR 4 4b: a segmented page's window reserves its call against the page's spend cap first; null: refused, the item is skipped. */+ async function chatWithinPageCap<T>(item: WorkItem, call: () => Promise<T>): Promise<T | null> {+ const reserved = item.kind === 'page' && item.window ? await item.window.reserve(extractModel, maxOutputTokens) : {};+ if (!reserved) pagesSkipped++;+ return reserved ? spendGrant(reserved.grant, call) : null;}/** Large pages A7: a page's watermark moves past the text this item read once its writes committed (a pending batch keeps the old one). */async function commitAtomsWatermark(item: ExtractAtomsItem, input: ExtractAtomsInput, published: readonly { state: string }[]): Promise<void> {@@ -1099,15 +1112,15 @@ export async function runPhaseExtractAtoms(const cutLine = truncated ? inputTruncatedLine(originLabel, input, maxInputChars) : null; // A7: a complete appended-tail read prints nothingif (cutLine) { inputTruncated++; console.error(cutLine); } // counted only for a model call- const result = await chat({+ const result = await chatWithinPageCap(item, () => chat({model: extractModel,...atomsPrompt(dateGrounding, originLabel, promptContent),maxTokens: maxOutputTokens, responseSchema: ATOMS_RESPONSE_SCHEMA,abortSignal: opts.signal,- });- // Post-await yield: closes the "long LLM call past TTL" hazard- // codex flagged. The 30s throttle inside maybeYield bounds the- // actual refresh rate so this is cheap when calls are fast.+ }));+ if (!result) continue;+ // Post-await yield: closes the "long LLM call past TTL" hazard codex flagged. The 30s throttle+ // inside maybeYield bounds the actual refresh rate so this is cheap when calls are fast.await maybeYield();llmHalt.reset();// #4540: optional per-item pacing between successful LLM calls.@@ -1304,7 +1317,7 @@ export async function runPhaseExtractAtoms(const retired = truncated ? [] : await completeUnmanagedItem(engine, sourceId, item, hash16, importedSlugs);await atomFiles?.write(importedSlugs, retired);if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);- else if (item.kind === 'page') await stampAtomsScanHash(item);+ else if (item.kind === 'page' && !item.window) await stampAtomsScanHash(item);await commitAtomsWatermark(item, input, []);}} else {@@ -1468,43 +1481,11 @@ export async function runPhaseExtractAtoms(async function completeUnmanagedItem(engine: BrainEngine, sourceId: string,item: { kind: 'transcript'; filePath: string } | ({ kind: 'page' } & AtomPageInput), hash16: string, importedSlugs: string[]): Promise<string[]> {await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);+ if (item.kind === 'page' && item.window) return item.window.settle(importedSlugs);return retireStaleAtoms(engine, sourceId, item.kind === 'page'? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);}-/**- * Soft-delete a source's atoms from earlier extractions (a different or- * provisional source_hash) that the current, completed extraction did not- * re-produce. Imported atoms (`imported_from`) and managed atoms are left- * alone. Best-effort: a failure leaves duplicates, never loses current atoms.- */-async function retireStaleAtoms(- engine: BrainEngine,- sourceId: string,- origin: { key: 'source_slug' | 'source_path'; value: string },- hash16: string,- currentSlugs: string[],-): Promise<string[]> {- try {- const rows = await engine.executeRaw<{ slug: string }>(- `SELECT slug FROM pages- WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL- AND frontmatter->>'${origin.key}' = $2- AND COALESCE(frontmatter->>'source_hash', '') <> $3- AND (frontmatter->>'imported_from') IS NULL- AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'- AND NOT (slug = ANY($4::text[]))`,- [sourceId, origin.value, hash16, currentSlugs],- );- const stale = rows.map(r => r.slug);- for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));- return stale;- } catch (err) {- console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);- return [];- }-}-/*** Canonical slug stem for an atom title. Routes through slugifySegment (the* same normalizer the FS-import path uses) and RE-STRIPS a trailing dash afterdiff --git a/test/e2e/conversation-facts-incremental-postgres.test.ts b/test/e2e/conversation-facts-incremental-postgres.test.tsindex 18a75a4f17..24b193dd2a 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, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';+import { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';import { hasDatabase } from './helpers.ts';(hasDatabase() ? describe : describe.skip)('conversation facts incremental [postgres]', () => {@@ -14,4 +14,6 @@ import { hasDatabase } from './helpers.ts';afterAll(async () => { await brain.close(); }, 120_000);defineConversationFactsIncrementalCases({ getBrain: () => brain });defineSegmentedBackstopCases({ getBrain: () => brain });+ defineSegmentedAtomsCases({ getBrain: () => brain });+ defineSegmentReceiptDoctorCases({ getBrain: () => brain });});diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.tsindex 9912561e16..b43d404942 100644--- a/test/helpers/conversation-facts-incremental-cases.ts+++ b/test/helpers/conversation-facts-incremental-cases.ts@@ -25,6 +25,11 @@ 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';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import { MAX_ATOM_WINDOWS_PER_PAGE_RUN } from '../../src/core/cycle/extract-atoms-segments.ts';+import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/extraction-input.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import type { Check } from '../../src/commands/doctor.ts';const SPEAKERS = ['Alice Example', 'Bob Example', 'Carol Example'];const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast', 'retention', 'deploy'];@@ -287,3 +292,117 @@ export function defineSegmentedBackstopCases(opts: { getBrain: () => AppendBrain}}, 600_000);}++/**+ * extract_atoms over a segmented page (wave-b spec 8.2 "extract_atoms"): an import extracts every input-cap window of+ * every occurrence once (one atom per window from the fake model), across runs when a run's window budget stops it; an+ * append by a remote writer extracts only windows whose text no run extracted before, and once the page settles the+ * atoms of windows that left the page are retired and every other atom stays; a cap the newest window does not fit+ * refuses before any call. Fake chat (the phase's _chat seam), counted by prompt.+ */+export function defineSegmentedAtomsCases(opts: { getBrain: () => AppendBrain }): void {+ const slug = `notes/atoms-segmented-${randomUUID().slice(0, 8)}`;+ const cap = 50_000;+ let prompts: string[] = [];+ let calls = 0;+ let before: string[] = [];+ const chat = async (o: ChatOpts): Promise<ChatResult> => {+ prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));+ const title = `window atom ${++calls}`;+ const text = JSON.stringify({ atoms: [{ title, atom_type: 'insight', body: `Body for ${title}.`, source_quote: null, lesson: null, concepts: null, virality_score: null, emotional_register: null }] });+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };+ };+ /** Runs the phase until a run makes no call; returns the calls made for page S (other pages in the brain are extracted too). */+ const drain = async (engine: BrainEngine, s: string): Promise<number> => {+ prompts = [];+ for (let run = 0; run < 20; run++) {+ const made = prompts.length;+ await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [] });+ if (prompts.length === made) break;+ }+ prompts = prompts.filter(p => p.includes('Source: ' + s + '\n'));+ return prompts.length;+ };+ const windowsOf = async (brain: AppendBrain, s: string): Promise<string[]> => {+ const [page] = await brain.engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]);+ const truth = Buffer.from((await brain.body(s)).truth, 'utf8');+ return (await brain.engine.readManifest(Number(page!.id)))+ .flatMap(row => lineWindows(truth.subarray(row.byteStart, row.byteStart + row.byteLen).toString('utf8'), cap)).filter(w => w.trim());+ };+ const atoms = async (engine: BrainEngine, s: string) => engine.executeRaw<{ slug: string; live: boolean }>(+ `SELECT slug, deleted_at IS NULL AS live FROM pages WHERE source_id='default' AND type='atom' AND frontmatter->>'source_slug'=$1`, [s]);+ const rowsOf = async (engine: BrainEngine, s: string) => {+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]);+ return engine.readSegmentDerivations(Number(page!.id), { kind: 'extract_atoms' });+ };+ const digest = (text: string) => createHash('sha256').update(text).digest('hex');++ test('an import extracts every window of every occurrence once, one atom each; a settled page extracts nothing', async () => {+ const brain = opts.getBrain();+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');+ await brain.engine.setConfig('cycle.extract_atoms.max_input_chars', String(cap));+ await brain.seed(slug, chatPage('Atoms', chatDays(700, 100, 5)).replace('type: conversation', 'type: meeting'));+ before = await windowsOf(brain, slug);+ const made = await drain(brain.engine, slug);+ const rows = await rowsOf(brain.engine, slug);+ const stored = await atoms(brain.engine, slug);+ expect(before.length).toBeGreaterThan(MAX_ATOM_WINDOWS_PER_PAGE_RUN);+ expect({ calls: made, covered: before.filter(w => prompts.filter(p => p.includes(w)).length === 1).length, rows: [...new Set(rows.map(r => r.state))],+ atoms: stored.filter(a => a.live).length })+ .toEqual({ calls: before.length, covered: before.length, rows: ['done'], atoms: before.length });+ expect(await drain(brain.engine, slug)).toBe(0);+ }, 600_000);++ test('an append by a remote writer extracts only the new windows and retires only the atoms of windows that left the page', async () => {+ const brain = opts.getBrain();+ const appended = chatDays(800, 2, 5);+ expect(await brain.call('append_page', { slug, text: appended, request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ const after = await windowsOf(brain, slug);+ const old = new Set(before.map(digest));+ const live = new Set(after.map(digest));+ const fresh = after.filter(w => !old.has(digest(w)));+ const made = await drain(brain.engine, slug);+ const stored = await atoms(brain.engine, slug);+ const recorded = new Set((await rowsOf(brain.engine, slug)).flatMap(r => ((r.output as { windows: { atoms: string[] }[] }).windows).flatMap(w => w.atoms)));+ expect(fresh.length).toBeLessThanOrEqual(Math.ceil(appended.length / cap) + 2);+ expect({ calls: made, covered: fresh.every(w => prompts.some(p => p.includes(w))), live: stored.filter(a => a.live).length,+ retired: stored.filter(a => !a.live).length, recorded: stored.filter(a => a.live).every(a => recorded.has(a.slug)) })+ .toEqual({ calls: fresh.length, covered: true, live: live.size, retired: [...old].filter(h => !live.has(h)).length, recorded: true });+ }, 600_000);++ test('a cap the newest window does not fit refuses before any call and records the unread windows', async () => {+ const brain = opts.getBrain();+ const capped = `notes/atoms-capped-${randomUUID().slice(0, 8)}`;+ await brain.seed(capped, chatPage('Atoms capped', chatDays(900, 100, 6)).replace('type: conversation', 'type: meeting'));+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, '0.000001');+ try {+ const made = await drain(brain.engine, capped);+ const rows = await rowsOf(brain.engine, capped);+ expect({ calls: made, receipts: [...new Set(rows.map(r => JSON.stringify({ state: r.state, reason: (r.receipt as { reason?: string } | null)?.reason ?? null })))] })+ .toEqual({ calls: 0, receipts: [JSON.stringify({ state: 'partial', reason: 'cap_reached' })] });+ expect(rows.length).toBeGreaterThan(0);+ } finally {+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');+ }+ }, 600_000);+}++/** Doctor's extraction_input_truncated reads page_segment_derivations receipts too (wave-b spec 8.1), not only page_extraction_state. */+export function defineSegmentReceiptDoctorCases(opts: { getBrain: () => AppendBrain }): void {+ test('doctor lists a segmented page whose windows the cap left unread, with the per-page cap as the fix', async () => {+ const { engine, seed } = opts.getBrain();+ const s = `notes/doctor-unread-${randomUUID().slice(0, 8)}`;+ await seed(s, chatPage('Doctor unread', chatDays(950, 100, 5)).replace('type: conversation', 'type: note'));+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]);+ const [first] = await engine.readManifest(Number(page!.id));+ await engine.upsertSegmentDerivations([{ pageId: Number(page!.id), kind: 'extract_atoms', occurrenceId: first!.occurrenceId, version: 1,+ segmentSha256: first!.sha256, contextHash: new Uint8Array(32), state: 'partial', output: { windows: [] },+ receipt: { kind: 'unread_windows', pipeline: 'extract_atoms', reason: 'cap_reached', windows_read: 0, windows_total: 3 } }]);+ const check = (await extractionInputTruncatedEntry.run({ 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[] }> }).groups;+ expect({ status: check.status, argv: (check as { fix?: { argv: string[] } }).fix?.argv,+ listed: groups.some(g => g.pipeline === 'extract_atoms' && g.kind === 'unread_windows' && g.samples.includes(`default:${s}`)) })+ .toEqual({ status: 'warn', argv: ['gbrain', 'config', 'set', PAGE_EMBED_CAP_KEY, '<usd>'], listed: true });+ }, 600_000);+}diff --git a/test/large-pages/conversation-facts-incremental.test.ts b/test/large-pages/conversation-facts-incremental.test.tsindex a9281eceaf..a2db329e47 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, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';+import { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';let brain: AppendBrain;@@ -14,4 +14,6 @@ afterAll(async () => { await brain.close(); }, 120_000);describe('conversation facts incremental [pglite]', () => {defineConversationFactsIncrementalCases({ getBrain: () => brain });defineSegmentedBackstopCases({ getBrain: () => brain });+ defineSegmentedAtomsCases({ getBrain: () => brain });+ defineSegmentReceiptDoctorCases({ getBrain: () => brain });});