Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(corpus): turn-boundary window planner and CAS .progress for corpus extraction (#5887)
garrytan06cc38ec3b72
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.tsindex a40aaf74bb..a036d8b8f5 100644--- a/src/core/context/corpus-segments.ts+++ b/src/core/context/corpus-segments.ts@@ -81,6 +81,11 @@ export function ledgerFileName(sessionId: string): string {* publish). Lives HERE so the engine-free hook lane can GC orphaned receipts* without importing the engine-typed harvest module. */export const HARVEST_RECEIPT_SUFFIX = '.receipt.json';+/** #5887 window-progress sidecar (context/corpus-windows.ts) and its CAS+ * lock. Engine-free home so the hook's GC reaps both with the `.txt`; the+ * hook's resume rewrite never deletes them. */+export const CORPUS_PROGRESS_SUFFIX = '.progress';+export const CORPUS_PROGRESS_LOCK_SUFFIX = '.progress.lock';/*** Inverse of `segmentFileName`: `{sessionId, hash}` when `name` is a corpusdiff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.tsnew file mode 100644index 0000000000..e808156333--- /dev/null+++ b/src/core/context/corpus-windows.ts@@ -0,0 +1,517 @@+/**+ * corpus-windows.ts — #5887: windowed fact extraction of session-corpus files.+ *+ * The extractor reads at most MAX_TURN_TEXT_CHARS (8,000) characters per+ * call, so a long transcript passed whole lost everything after its head.+ * Here a corpus file (`toCorpusText` output: `[user]` / `[assistant]` blocks+ * separated by blank lines) is cut into windows that each fit the extractor:+ *+ * - Turns are found only at the exact `\n\n[user]\n` / `\n\n[assistant]\n`+ * markers `toCorpusText` emits (plus a marker at offset 0).+ * - Each whole user turn is paste-stripped FIRST (#5812), then the stripped+ * text is windowed, so a paste that crosses a window boundary never leaks.+ * - Windows hold whole turns; a turn longer than a window is split, and every+ * continuation repeats its `[role]` header, so assistant text is never read+ * as the user's own words.+ *+ * Progress lives in `<file>.progress` (never deleted by the hook's resume+ * rewrite; GC'd with the `.txt`): a generation counter, the hashes of finished+ * turns, an optional continuation into a split turn, the file stat of the+ * snapshot that finished, and a lease. A rewrite (append, compaction+ * remainder, same-size or shorter replacement) resumes at the first turn+ * whose hash is not recorded. Every write is compare-and-set under an O_EXCL+ * lock file: a commit lands only when the generation, the last recorded turn+ * hash and the lease owner still match and the progress grows. The lease stops+ * a second sweep (whose claim the hook deleted on rewrite) from extracting a+ * window the first sweep is still working on. Callers keep the existing+ * `.in-progress` claim discipline; this module never touches claims.+ */++import { createHash, randomUUID } from 'node:crypto';+import { readFile, rename, rm, stat, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { MAX_TURN_TEXT_CHARS } from '../facts/extract.ts';+import type { runFactsPipeline } from '../facts/backstop.ts';+import { stripPastedContent } from '../transcripts/pasted-content.ts';+import { CORPUS_PROGRESS_LOCK_SUFFIX, CORPUS_PROGRESS_SUFFIX, parseWbFileName } from './corpus-segments.ts';++/** Per-file window cap per sweep; longer files converge over later sweeps. */+export const CORPUS_WINDOWS_PER_SWEEP = 8;+/** Cross-file window total per sweep (override: GBRAIN_CORPUS_WINDOWS_PER_SWEEP). */+export const CORPUS_WINDOWS_PER_SWEEP_TOTAL = 32;+/** A lease older than this belongs to a dead extractor (matches the claim's hour). */+export const CORPUS_PROGRESS_LEASE_STALE_MS = 60 * 60 * 1000;++const LOCK_STALE_MS = 30_000;+const LOCK_ATTEMPTS = 40;+const LOCK_RETRY_MS = 25;+const MAX_RECORDED_TURNS = 20_000;+const MAX_ENTITY_SLUGS = 500;++type PipelineResult = Awaited<ReturnType<typeof runFactsPipeline>>;++export interface CorpusTurn {+ role: 'user' | 'assistant' | null;+ /** UTF-8 byte offsets of the turn in the raw file (header included). */+ start: number;+ end: number;+ /** SHA-256 of the raw turn text (trailing whitespace trimmed). */+ sha256: string;+ header: string;+ /** Extractor-facing body: pastes stripped (user turns), trimmed. */+ body: string;+}++export interface CorpusWindow {+ text: string;+ /** Index of the last turn this window touches. */+ endTurn: number;+ /** Offset into that turn's body where the window stops; null when the turn finished. */+ endOffset: number | null;+}++export interface CorpusFileStat {+ size: number;+ mtime_ms: number;+ ino: number;+}++export interface CorpusProgress {+ version: 1;+ generation: number;+ turns: Array<{ start: number; end: number; sha256: string }>;+ continuation: { turn_sha256: string; stripped_offset: number } | null;+ windows_done: number;+ /** Stat of the snapshot whose every window finished; null while windows remain. */+ finished: CorpusFileStat | null;+ totals: { inserted: number; duplicate: number; superseded: number };+ entity_slugs: string[];+ skipped_reason?: string;+ lease: { owner: string; at: number } | null;+}++export interface CorpusWindowRun {+ status: 'complete' | 'partial' | 'aborted' | 'contended' | 'changed';+ windowsDone: number;+ windowsRemaining: number;+ /** Cumulative across every sweep that worked on this file. */+ result: PipelineResult;+}++const sha256 = (text: string): string => createHash('sha256').update(text).digest('hex');++let invalidKnobWarned = false;++/**+ * The cross-file window total for one sweep. `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`+ * overrides it with a positive integer; anything else falls back to the+ * default with one warning per process.+ */+export function resolveCorpusWindowsPerSweepTotal(+ env: Record<string, string | undefined> = process.env,+ warn: (msg: string) => void = () => {},+): number {+ const raw = env.GBRAIN_CORPUS_WINDOWS_PER_SWEEP;+ if (raw === undefined || raw.trim() === '') return CORPUS_WINDOWS_PER_SWEEP_TOTAL;+ const n = Number(raw.trim());+ if (Number.isSafeInteger(n) && n > 0) return n;+ if (!invalidKnobWarned) {+ invalidKnobWarned = true;+ warn(`[sweep] GBRAIN_CORPUS_WINDOWS_PER_SWEEP=${JSON.stringify(raw)} is not a positive integer; using ${CORPUS_WINDOWS_PER_SWEEP_TOTAL}`);+ }+ return CORPUS_WINDOWS_PER_SWEEP_TOTAL;+}++/** TEST SEAM: re-arm the once-per-process invalid-knob warning. */+export function __resetCorpusWindowsWarningForTests(): void {+ invalidKnobWarned = false;+}++/** Split corpus text into turns at the exact `toCorpusText` markers. */+export function parseCorpusTurns(raw: string): CorpusTurn[] {+ const starts: Array<{ at: number; role: 'user' | 'assistant' }> = [];+ if (raw.startsWith('[user]\n')) starts.push({ at: 0, role: 'user' });+ else if (raw.startsWith('[assistant]\n')) starts.push({ at: 0, role: 'assistant' });+ const USER = '\n\n[user]\n';+ const ASSISTANT = '\n\n[assistant]\n';+ let nextUser = raw.indexOf(USER);+ let nextAssistant = raw.indexOf(ASSISTANT);+ while (nextUser >= 0 || nextAssistant >= 0) {+ const isUser = nextAssistant < 0 || (nextUser >= 0 && nextUser < nextAssistant);+ const at = isUser ? nextUser : nextAssistant;+ starts.push({ at: at + 2, role: isUser ? 'user' : 'assistant' });+ if (isUser) nextUser = raw.indexOf(USER, at + 2);+ else nextAssistant = raw.indexOf(ASSISTANT, at + 2);+ }++ let charAt = 0;+ let byteAt = 0;+ const bytes = (index: number): number => {+ byteAt += Buffer.byteLength(raw.slice(charAt, index), 'utf8');+ charAt = index;+ return byteAt;+ };+ const turns: CorpusTurn[] = [];+ const push = (role: CorpusTurn['role'], from: number, to: number): void => {+ const span = raw.slice(from, to);+ const header = role ? `[${role}]\n` : '';+ const rawBody = span.slice(header.length);+ const body = (role === 'user' ? stripPastedContent(rawBody).text : rawBody).trim();+ const start = bytes(from);+ turns.push({ role, start, end: bytes(to), sha256: sha256(span.trimEnd()), header, body });+ };+ const firstAt = starts.length ? starts[0].at : raw.length;+ if (firstAt > 0) {+ const preambleEnd = starts.length ? firstAt - 2 : raw.length;+ if (raw.slice(0, preambleEnd).trim()) push(null, 0, preambleEnd);+ }+ for (let k = 0; k < starts.length; k++) {+ push(starts[k].role, starts[k].at, k + 1 < starts.length ? starts[k + 1].at - 2 : raw.length);+ }+ return turns;+}++function isHigh(code: number): boolean { return code >= 0xd800 && code <= 0xdbff; }+function isLow(code: number): boolean { return code >= 0xdc00 && code <= 0xdfff; }++/** Cut point in (from, max]: a newline, else a space, in the window's back half; never inside a surrogate pair. */+function cutPoint(body: string, from: number, max: number): number {+ if (max >= body.length) return body.length;+ const floor = from + Math.floor((max - from) / 2);+ const newline = body.lastIndexOf('\n', max - 1);+ if (newline >= floor) return newline + 1;+ const space = body.lastIndexOf(' ', max - 1);+ if (space >= floor) return space + 1;+ return isHigh(body.charCodeAt(max - 1)) && isLow(body.charCodeAt(max)) ? max - 1 : max;+}++/**+ * Plan every remaining window from `from`. Whole turns are packed together;+ * a turn that does not fit a fresh window is split with its header repeated.+ * A window whose text is empty only records empty (paste-only) turns as done.+ */+export function planCorpusWindows(+ turns: CorpusTurn[],+ from: { turn: number; offset: number },+ maxChars: number = MAX_TURN_TEXT_CHARS,+): CorpusWindow[] {+ const windows: CorpusWindow[] = [];+ let parts: string[] = [];+ let len = 0;+ let last: { turn: number; offset: number | null } = { turn: from.turn - 1, offset: null };+ const flush = (): void => {+ windows.push({ text: parts.join('\n\n'), endTurn: last.turn, endOffset: last.offset });+ parts = [];+ len = 0;+ };+ for (let t = from.turn; t < turns.length; t++) {+ const { header, body } = turns[t];+ let offset = t === from.turn ? Math.min(from.offset, body.length) : 0;+ if (offset >= body.length) {+ last = { turn: t, offset: null };+ continue;+ }+ while (offset < body.length) {+ const sep = parts.length ? 2 : 0;+ const room = maxChars - len - sep - header.length;+ const rest = body.length - offset;+ if (rest <= room) {+ parts.push(header + body.slice(offset));+ len += sep + header.length + rest;+ last = { turn: t, offset: null };+ break;+ }+ if (parts.length && (header.length + rest <= maxChars || room < maxChars / 4)) {+ flush();+ continue;+ }+ const cut = cutPoint(body, offset, offset + room);+ parts.push(header + body.slice(offset, cut));+ len += sep + header.length + (cut - offset);+ offset = cut;+ last = { turn: t, offset: cut < body.length ? cut : null };+ flush();+ }+ }+ if (parts.length) flush();+ else if (last.turn >= from.turn && last.turn > (windows.at(-1)?.endTurn ?? from.turn - 1)) flush();+ return windows;+}++/** Where extraction resumes: the first turn whose hash is not recorded. */+export function resumePoint(turns: CorpusTurn[], progress: CorpusProgress | null): { turn: number; offset: number } {+ if (!progress) return { turn: 0, offset: 0 };+ const done = new Set(progress.turns.map((t) => t.sha256));+ let turn = 0;+ while (turn < turns.length && done.has(turns[turn].sha256)) turn++;+ const cont = progress.continuation;+ const offset = cont && turn < turns.length && turns[turn].sha256 === cont.turn_sha256+ ? Math.min(cont.stripped_offset, turns[turn].body.length)+ : 0;+ return { turn, offset };+}++function isFileStat(v: unknown): v is CorpusFileStat {+ const s = v as CorpusFileStat;+ return !!s && typeof s === 'object' && Number.isFinite(s.size) && Number.isFinite(s.mtime_ms) && Number.isFinite(s.ino);+}++function parseProgress(text: string): CorpusProgress | null {+ let p: CorpusProgress;+ try { p = JSON.parse(text) as CorpusProgress; } catch { return null; }+ if (!p || typeof p !== 'object' || p.version !== 1 || !Number.isSafeInteger(p.generation)) return null;+ if (!Array.isArray(p.turns) || !p.turns.every((t) => t && typeof t.sha256 === 'string')) return null;+ if (p.continuation !== null && !(p.continuation && typeof p.continuation.turn_sha256 === 'string'+ && Number.isSafeInteger(p.continuation.stripped_offset))) return null;+ if (p.finished !== null && !isFileStat(p.finished)) return null;+ if (!p.totals || !Array.isArray(p.entity_slugs)) return null;+ return p;+}++/** The progress sidecar, or null when absent or unparseable (replayed safely). I/O errors throw. */+export async function readCorpusProgress(full: string): Promise<CorpusProgress | null> {+ try {+ return parseProgress(await readFile(full + CORPUS_PROGRESS_SUFFIX, 'utf8'));+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw e;+ }+}++export function corpusFileStat(st: { size: number; mtimeMs: number; ino: number }): CorpusFileStat {+ return { size: st.size, mtime_ms: st.mtimeMs, ino: st.ino };+}++export function sameCorpusFileStat(a: CorpusFileStat | null, b: CorpusFileStat): boolean {+ return !!a && a.size === b.size && a.mtime_ms === b.mtime_ms && a.ino === b.ino;+}++async function acquireLock(lockPath: string): Promise<boolean> {+ for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt++) {+ try {+ await writeFile(lockPath, `${process.pid}\n`, { flag: 'wx', mode: 0o600 });+ return true;+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') return false;+ }+ const age = await stat(lockPath).then((s) => Date.now() - s.mtimeMs, () => 0);+ if (age > LOCK_STALE_MS) await rm(lockPath, { force: true }).catch(() => {});+ else await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));+ }+ return false;+}++/**+ * Compare-and-set: under the lock, `next` sees the current progress and+ * returns the replacement, or null to refuse. The generation always advances.+ * Returns the written progress, or null when refused or the lock is busy.+ */+async function updateProgress(+ full: string,+ next: (cur: CorpusProgress | null) => Omit<CorpusProgress, 'generation'> | null,+): Promise<CorpusProgress | null> {+ const lockPath = full + CORPUS_PROGRESS_LOCK_SUFFIX;+ if (!(await acquireLock(lockPath))) return null;+ try {+ const cur = await readCorpusProgress(full);+ const proposed = next(cur);+ if (!proposed) return null;+ const written: CorpusProgress = { ...proposed, generation: (cur?.generation ?? 0) + 1 };+ const path = full + CORPUS_PROGRESS_SUFFIX;+ const tmp = `${path}.tmp-${process.pid}`;+ await writeFile(tmp, JSON.stringify(written) + '\n', { mode: 0o600 });+ await rename(tmp, path);+ return written;+ } finally {+ await rm(lockPath, { force: true }).catch(() => {});+ }+}++function freshProgress(): Omit<CorpusProgress, 'generation'> {+ return {+ version: 1,+ turns: [],+ continuation: null,+ windows_done: 0,+ finished: null,+ totals: { inserted: 0, duplicate: 0, superseded: 0 },+ entity_slugs: [],+ lease: null,+ };+}++const lastSha = (p: CorpusProgress | null): string | null => p?.turns.at(-1)?.sha256 ?? null;++function resultOf(p: CorpusProgress): PipelineResult {+ return {+ ...p.totals,+ fact_ids: [],+ entity_slugs: [...p.entity_slugs],+ ...(p.skipped_reason ? { skipped_reason: p.skipped_reason as PipelineResult['skipped_reason'] } : {}),+ };+}++/**+ * How a corpus file that HAS an `.ingested` sidecar stands:+ * 'done' — its `.progress` finished this exact file (stat match);+ * 'changed' — rewritten since; re-enter (turn hashes decide resume);+ * 'legacy' — finished before `.progress` existed and not rewritten+ * since (the sidecar is newer than the file): adopt;+ * 'legacy_changed' — finished before `.progress` existed, rewritten after.+ * Writeback turn files are immutable single turns: always 'done'.+ */+export async function finishedCorpusFileState(+ full: string,+ name: string,+): Promise<'done' | 'changed' | 'legacy' | 'legacy_changed'> {+ if (parseWbFileName(name)) return 'done';+ const st = await stat(full);+ const progress = await readCorpusProgress(full);+ if (progress) return sameCorpusFileStat(progress.finished, corpusFileStat(st)) ? 'done' : 'changed';+ const ingested = await stat(full + '.ingested');+ return ingested.mtimeMs >= st.mtimeMs ? 'legacy' : 'legacy_changed';+}++/**+ * V6 — record a file finished before windowed extraction as fully extracted+ * at its current turns, so later growth extracts only the appended turns and+ * the head is never re-sent. Writes only when no progress exists yet.+ */+export async function adoptFinishedCorpusFile(full: string): Promise<boolean> {+ const st = corpusFileStat(await stat(full));+ const raw = await readFile(full, 'utf8');+ const after = corpusFileStat(await stat(full));+ if (!sameCorpusFileStat(st, after)) return false;+ const turns = parseCorpusTurns(raw);+ const written = await updateProgress(full, (cur) => cur ? null : {+ ...freshProgress(),+ turns: turns.slice(-MAX_RECORDED_TURNS).map(({ start, end, sha256: h }) => ({ start, end, sha256: h })),+ finished: st,+ });+ return written !== null;+}++/**+ * Extract up to `maxWindows` non-empty windows of `raw` (the snapshot whose+ * stat is `fileStat`), committing `.progress` after each one. `complete`+ * means every window of this snapshot is done (the caller may write+ * `.ingested`); `partial` means the cap stopped it; `aborted` means the+ * signal or budget fired (nothing uncommitted is recorded); `contended`+ * means another extractor holds the lease or advanced the progress first.+ * Transport errors throw after the lease is released.+ */+export async function runCorpusWindows(opts: {+ full: string;+ raw: string;+ fileStat: CorpusFileStat;+ maxWindows: number;+ extract: (text: string) => Promise<PipelineResult>;+ overBudget: () => boolean;+ signal: AbortSignal;+}): Promise<CorpusWindowRun> {+ const { full, fileStat, signal } = opts;+ const owner = `${process.pid}:${randomUUID()}`;+ const now = Date.now();+ let state = await updateProgress(full, (cur) => {+ if (cur?.lease && cur.lease.owner !== owner && now - cur.lease.at < CORPUS_PROGRESS_LEASE_STALE_MS) return null;+ return { ...(cur ?? freshProgress()), lease: { owner, at: now } };+ });+ const turns = parseCorpusTurns(opts.raw);+ if (!state) {+ const cur = await readCorpusProgress(full).catch(() => null);+ const remaining = planCorpusWindows(turns, resumePoint(turns, cur)).filter((w) => w.text).length;+ return { status: 'contended', windowsDone: 0, windowsRemaining: remaining, result: resultOf(cur ?? { ...freshProgress(), generation: 0 }) };+ }++ let cursor = resumePoint(turns, state);+ const windows = planCorpusWindows(turns, cursor);+ let done = 0;+ let status: CorpusWindowRun['status'] = 'complete';+ let holding = true;+ try {+ for (let w = 0; w < windows.length; w++) {+ const win = windows[w];+ if (win.text) {+ if (done >= opts.maxWindows) { status = 'partial'; break; }+ if (opts.overBudget() || signal.aborted) { status = 'aborted'; break; }+ }+ const r = win.text ? await opts.extract(win.text) : null;+ if (signal.aborted) { status = 'aborted'; break; }+ const finishedTurns = turns.slice(cursor.turn, win.endOffset === null ? win.endTurn + 1 : win.endTurn);+ const isLast = w === windows.length - 1;+ const expectGen = state.generation;+ const expectLast = lastSha(state);+ const advances = finishedTurns.length > 0 || (win.endOffset ?? 0) > cursor.offset;+ const next: CorpusProgress | null = await updateProgress(full, (cur) => {+ if (!advances || !cur || cur.generation !== expectGen || lastSha(cur) !== expectLast || cur.lease?.owner !== owner) return null;+ const slugs = r ? [...new Set([...cur.entity_slugs, ...r.entity_slugs])].slice(-MAX_ENTITY_SLUGS) : cur.entity_slugs;+ return {+ ...cur,+ turns: [...cur.turns, ...finishedTurns.map(({ start, end, sha256: h }) => ({ start, end, sha256: h }))].slice(-MAX_RECORDED_TURNS),+ continuation: win.endOffset === null ? null : { turn_sha256: turns[win.endTurn].sha256, stripped_offset: win.endOffset },+ windows_done: cur.windows_done + (r ? 1 : 0),+ finished: isLast ? fileStat : null,+ totals: r+ ? { inserted: cur.totals.inserted + r.inserted, duplicate: cur.totals.duplicate + r.duplicate, superseded: cur.totals.superseded + r.superseded }+ : cur.totals,+ entity_slugs: slugs,+ ...(r?.skipped_reason ? { skipped_reason: r.skipped_reason } : {}),+ lease: isLast ? null : { owner, at: Date.now() },+ };+ });+ if (!next) { status = 'contended'; break; }+ state = next;+ if (r) done++;+ if (isLast) holding = false;+ cursor = win.endOffset === null ? { turn: win.endTurn + 1, offset: 0 } : { turn: win.endTurn, offset: win.endOffset };+ }+ if (windows.length === 0) {+ const finished = await updateProgress(full, (cur) =>+ cur && cur.lease?.owner === owner ? { ...cur, finished: fileStat, continuation: null, lease: null } : null);+ if (finished) {+ state = finished;+ holding = false;+ } else status = 'contended';+ }+ } finally {+ if (holding) {+ const released = await updateProgress(full, (cur) =>+ cur && cur.lease?.owner === owner ? { ...cur, lease: null } : null).catch(() => null);+ if (released) state = released;+ }+ }+ const remaining = planCorpusWindows(turns, cursor).filter((w) => w.text).length;+ // Rewritten while extracting: the snapshot's progress stands, but the file+ // is not done; its new turns wait for the next run.+ if (status === 'complete' && !sameCorpusFileStat(fileStat, corpusFileStat(await stat(full)))) status = 'changed';+ return { status, windowsDone: done, windowsRemaining: status === 'complete' || status === 'changed' ? 0 : remaining, result: resultOf(state) };+}++/**+ * The sweep's candidate list: files without `.ingested`, plus finished files+ * that changed since `.progress` recorded them (stat compare, no rehash). A+ * pre-window `.ingested` file is adopted at its current turns (budget+ * permitting) so only later growth is extracted. Returns the candidates (at+ * most `batchLimit`) and how many files are already done.+ */+export async function selectCorpusCandidates(+ dir: string,+ txtFiles: string[],+ entrySet: Set<string>,+ batchLimit: number,+ overBudget: () => boolean,+): Promise<{ candidates: string[]; alreadyIngested: number }> {+ const candidates: string[] = [];+ let alreadyIngested = 0;+ for (const name of txtFiles) {+ const full = join(dir, name);+ let state: Awaited<ReturnType<typeof finishedCorpusFileState>> | 'new' = 'new';+ if (entrySet.has(name + '.ingested')) {+ state = await finishedCorpusFileState(full, name).catch(() => 'changed' as const);+ if (state === 'legacy' && !overBudget()) await adoptFinishedCorpusFile(full).catch(() => false);+ }+ if (state === 'done' || state === 'legacy') alreadyIngested++;+ else if (candidates.length < batchLimit) candidates.push(name);+ }+ return { candidates, alreadyIngested };+}diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex 09c283296b..2c6d9b42d7 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -349,7 +349,8 @@ export function buildExtractorSystem(admitsLow: boolean): string {return admitsLow ? EXTRACTOR_SYSTEM_ADMITS_LOW : EXTRACTOR_SYSTEM_SKIPS_LOW;}-const MAX_TURN_TEXT_CHARS = 8000;+/** Extractor input ceiling; corpus windows (context/corpus-windows.ts) are cut to fit it. */+export const MAX_TURN_TEXT_CHARS = 8000;/*** #4863 — JSON Schema for the extractor reply, sent as `responseSchema` ondiff --git a/test/corpus-windows.test.ts b/test/corpus-windows.test.tsnew file mode 100644index 0000000000..c269c6c6c7--- /dev/null+++ b/test/corpus-windows.test.ts@@ -0,0 +1,212 @@+/**+ * #5887 — corpus window planner and `.progress` compare-and-set, engine-free.+ *+ * Protects: windows open with their `[role]` header and fit the extractor's+ * 8,000-char ceiling; pastes are stripped per whole turn before windowing;+ * a split turn resumes from its continuation offset without losing or+ * repeating a character (including astral and multi-byte text); progress+ * advances only under the matching generation and lease; the per-sweep+ * total knob validates its input. The sweep-level behavior (multi-sweep+ * convergence, rewrites, races, harvest) lives in sweep-corpus-windows.test.ts.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import {+ CORPUS_WINDOWS_PER_SWEEP_TOTAL,+ __resetCorpusWindowsWarningForTests,+ corpusFileStat,+ parseCorpusTurns,+ planCorpusWindows,+ readCorpusProgress,+ resolveCorpusWindowsPerSweepTotal,+ resumePoint,+ runCorpusWindows,+} from '../src/core/context/corpus-windows.ts';+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';++const dirs: string[] = [];+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });++const corpus = (turns: Array<['user' | 'assistant', string]>): string =>+ toCorpusText(turns.map(([role, text]) => ({ role, text })));+const filler = (tag: string, n: number): string => {+ let s = `${tag} `;+ while (s.length < n) s += `${tag.toLowerCase()} detail words\n`;+ return s.slice(0, n);+};+const empty = { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };++describe('planCorpusWindows', () => {+ test('every window opens with a role header and fits 8,000 chars; a split turn repeats its header', () => {+ const raw = corpus([+ ['user', filler('U0', 3000)],+ ['assistant', filler('A1', 20_000)],+ ['user', filler('U2', 500)],+ ]);+ const windows = planCorpusWindows(parseCorpusTurns(raw), { turn: 0, offset: 0 });+ expect(windows.length).toBeGreaterThanOrEqual(3);+ expect(windows.filter((w) => w.text.includes('[assistant]\n')).length).toBeGreaterThanOrEqual(3);+ for (const w of windows) {+ expect(w.text.length).toBeLessThanOrEqual(8000);+ expect(w.text).toMatch(/^\[(user|assistant)\]\n/);+ }+ const assistantText = windows+ .flatMap((w) => w.text.split(/\n\n(?=\[(?:user|assistant)\]\n)/))+ .filter((part) => part.startsWith('[assistant]\n'))+ .map((part) => part.slice('[assistant]\n'.length))+ .join('');+ expect(assistantText).toBe(filler('A1', 20_000).trim());+ // No assistant chunk ever rides under a user header.+ for (const w of windows) {+ for (const part of w.text.split(/\n\n(?=\[(?:user|assistant)\]\n)/)) {+ if (part.startsWith('[user]\n')) expect(part).not.toContain('a1 detail');+ }+ }+ });++ test('a paste crossing every window boundary never reaches a window (strip per turn, then window)', () => {+ const paste = `<pasted_content id="9">\n${filler('PASTEMARK', 20_000)}\n</pasted_content id="9">`;+ const raw = corpus([+ ['user', `${filler('OWNHEAD', 6000)} ${paste} ${filler('OWNTAIL', 6000)}`],+ ['assistant', 'Noted.'],+ ]);+ const windows = planCorpusWindows(parseCorpusTurns(raw), { turn: 0, offset: 0 });+ const all = windows.map((w) => w.text).join('\n');+ expect(all).not.toContain('PASTEMARK');+ expect(all).not.toContain('pasted_content');+ expect(all).toContain('OWNHEAD');+ expect(all).toContain('OWNTAIL');+ for (const w of windows) expect(w.text.length).toBeLessThanOrEqual(8000);+ });++ test('only exact toCorpusText markers start turns; a bracket mid-line does not', () => {+ const raw = corpus([['user', 'see [assistant] in prose\nand\n[user] at a line start']]);+ const turns = parseCorpusTurns(raw);+ expect(turns.length).toBe(1);+ expect(turns[0].role).toBe('user');+ });++ test('turn byte offsets index the raw UTF-8 file', () => {+ const raw = corpus([['user', 'héllo 😀 wörld'], ['assistant', 'ok']]);+ const turns = parseCorpusTurns(raw);+ const buf = Buffer.from(raw, 'utf8');+ expect(buf.subarray(turns[1].start, turns[1].end).toString('utf8').trimEnd()).toBe('[assistant]\nok');+ expect(buf.subarray(turns[0].start, turns[0].end).toString('utf8')).toBe('[user]\nhéllo 😀 wörld');+ });+});++describe('resumePoint', () => {+ test('a compaction remainder resumes after its last recorded turn', () => {+ const full = corpus([['user', 'one'], ['assistant', 'two'], ['user', 'three'], ['assistant', 'four']]);+ const turns = parseCorpusTurns(full);+ const progress = {+ version: 1 as const, generation: 3, turns: turns.map(({ start, end, sha256 }) => ({ start, end, sha256 })),+ continuation: null, windows_done: 1, finished: null, totals: { inserted: 0, duplicate: 0, superseded: 0 },+ entity_slugs: [], lease: null,+ };+ const remainder = parseCorpusTurns(corpus([['user', 'three'], ['assistant', 'four'], ['user', 'five']]));+ expect(resumePoint(remainder, progress)).toEqual({ turn: 2, offset: 0 });+ });+});++describe('runCorpusWindows', () => {+ function tmpFile(name: string, raw: string): { full: string; stat: ReturnType<typeof corpusFileStat> } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-corpus-windows-'));+ dirs.push(dir);+ const full = join(dir, name);+ writeFileSync(full, raw);+ return { full, stat: corpusFileStat(statSync(full)) };+ }++ test('a restart inside a multi-byte split turn resumes at the continuation without losing a character', async () => {+ const body = '漢字テキスト😀'.repeat(2500);+ const raw = corpus([['user', body]]);+ const { full, stat } = tmpFile('mb.txt', raw);+ const seen: string[] = [];+ const extract = async (text: string) => { seen.push(text); return empty; };+ const ctl = new AbortController();+ const first = await runCorpusWindows({ full, raw, fileStat: stat, maxWindows: 1, extract, overBudget: () => false, signal: ctl.signal });+ expect(first.status).toBe('partial');+ const mid = await readCorpusProgress(full);+ expect(mid?.continuation?.stripped_offset).toBeGreaterThan(0);+ const second = await runCorpusWindows({ full, raw, fileStat: stat, maxWindows: 99, extract, overBudget: () => false, signal: ctl.signal });+ expect(second.status).toBe('complete');+ const rebuilt = seen.map((t) => {+ expect(t.startsWith('[user]\n')).toBe(true);+ expect(t.length).toBeLessThanOrEqual(8000);+ expect(/[\uD800-\uDBFF]$/.test(t) || /^\[user\]\n[\uDC00-\uDFFF]/.test(t)).toBe(false);+ return t.slice('[user]\n'.length);+ }).join('');+ expect(rebuilt).toBe(body);+ });++ test('a live lease held by another extractor refuses the run with zero extraction', async () => {+ const raw = corpus([['user', filler('X', 9000)]]);+ const { full, stat } = tmpFile('leased.txt', raw);+ writeFileSync(full + '.progress', JSON.stringify({+ version: 1, generation: 4, turns: [], continuation: null, windows_done: 0, finished: null,+ totals: { inserted: 0, duplicate: 0, superseded: 0 }, entity_slugs: [], lease: { owner: 'other:1', at: Date.now() },+ }));+ let calls = 0;+ const run = await runCorpusWindows({+ full, raw, fileStat: stat, maxWindows: 8, overBudget: () => false, signal: new AbortController().signal,+ extract: async () => { calls++; return empty; },+ });+ expect(run.status).toBe('contended');+ expect(calls).toBe(0);+ expect(JSON.parse(readFileSync(full + '.progress', 'utf8')).generation).toBe(4);+ });++ test('progress moved by someone else during a window is never overwritten backwards', async () => {+ const raw = corpus([['user', filler('A', 6000)], ['assistant', filler('B', 6000)], ['user', filler('C', 6000)]]);+ const { full, stat } = tmpFile('cas.txt', raw);+ let calls = 0;+ const run = await runCorpusWindows({+ full, raw, fileStat: stat, maxWindows: 8, overBudget: () => false, signal: new AbortController().signal,+ extract: async () => {+ calls++;+ // Another writer replaces progress mid-window (a stale-lease takeover).+ const cur = JSON.parse(readFileSync(full + '.progress', 'utf8'));+ writeFileSync(full + '.progress', JSON.stringify({ ...cur, generation: cur.generation + 10, lease: { owner: 'other:2', at: Date.now() } }));+ return empty;+ },+ });+ expect(run.status).toBe('contended');+ expect(calls).toBe(1);+ const after = JSON.parse(readFileSync(full + '.progress', 'utf8'));+ expect(after.lease.owner).toBe('other:2');+ expect(after.turns).toEqual([]);+ });++ test('an aborted window records nothing', async () => {+ const raw = corpus([['user', filler('A', 6000)], ['assistant', filler('B', 6000)]]);+ const { full, stat } = tmpFile('abort.txt', raw);+ const ctl = new AbortController();+ const run = await runCorpusWindows({+ full, raw, fileStat: stat, maxWindows: 8, overBudget: () => false, signal: ctl.signal,+ extract: async () => { ctl.abort(); return { ...empty, inserted: 1 }; },+ });+ expect(run.status).toBe('aborted');+ const p = await readCorpusProgress(full);+ expect(p?.turns).toEqual([]);+ expect(p?.windows_done).toBe(0);+ expect(p?.lease).toBeNull();+ });+});++describe('resolveCorpusWindowsPerSweepTotal (GBRAIN_CORPUS_WINDOWS_PER_SWEEP)', () => {+ test('a positive integer overrides; invalid values fall back with one warning', () => {+ __resetCorpusWindowsWarningForTests();+ const warnings: string[] = [];+ const warn = (m: string) => warnings.push(m);+ expect(resolveCorpusWindowsPerSweepTotal({}, warn)).toBe(CORPUS_WINDOWS_PER_SWEEP_TOTAL);+ expect(resolveCorpusWindowsPerSweepTotal({ GBRAIN_CORPUS_WINDOWS_PER_SWEEP: '2' }, warn)).toBe(2);+ expect(resolveCorpusWindowsPerSweepTotal({ GBRAIN_CORPUS_WINDOWS_PER_SWEEP: '0' }, warn)).toBe(32);+ expect(resolveCorpusWindowsPerSweepTotal({ GBRAIN_CORPUS_WINDOWS_PER_SWEEP: 'lots' }, warn)).toBe(32);+ expect(resolveCorpusWindowsPerSweepTotal({ GBRAIN_CORPUS_WINDOWS_PER_SWEEP: '1.5' }, warn)).toBe(32);+ expect(warnings.length).toBe(1);+ expect(warnings[0]).toContain('GBRAIN_CORPUS_WINDOWS_PER_SWEEP');+ });+});