Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sweep): extract whole transcripts in windows across sweeps; harvest window 1 only (#5887)

garrytan5b50ae2a7c47
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 6c07828585..83994cee0a 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -69,6 +69,8 @@ import {
bankWritebackTurn,
decideCorpusMode,
gcCorpusArtifacts,
+ CORPUS_PROGRESS_SUFFIX,
+ CORPUS_PROGRESS_LOCK_SUFFIX,
HARVEST_RECEIPT_SUFFIX,
segmentHash,
} from '../core/context/corpus-segments.ts';
@@ -1788,6 +1790,8 @@ async function hookSessionEnd(io: HookIo): Promise<number> {
gcCorpusArtifacts(dir, retentionMs, [
CORPUS_INGESTED_SUFFIX,
CORPUS_CLAIM_SUFFIX,
+ CORPUS_PROGRESS_SUFFIX,
+ CORPUS_PROGRESS_LOCK_SUFFIX,
HARVEST_RECEIPT_SUFFIX,
]);
}
diff --git a/src/commands/sweep.ts b/src/commands/sweep.ts
index 58f374cd1a..b1c637b2e4 100644
--- a/src/commands/sweep.ts
+++ b/src/commands/sweep.ts
@@ -30,7 +30,9 @@ Runs the three bounded sweep passes against the connected brain:
2. link/timeline extraction (zero-LLM): the same deterministic extraction
"gbrain extract" runs, over recently-modified pages.
3. corpus ingest (spend-gated): unprocessed transcript .txt files run
- through facts extraction. Skipped in keyless mode (no provider key).
+ through facts extraction in turn-boundary windows (8 per file and 32
+ total per sweep; GBRAIN_CORPUS_WINDOWS_PER_SWEEP overrides the total);
+ longer files finish over later sweeps. Skipped in keyless mode.
Flags:
--once Required. One bounded sweep, then exit.
@@ -112,6 +114,9 @@ export async function runSweep(engine: BrainEngine, args: string[]): Promise<voi
console.log(` links removed: ${report.linksRemoved}`);
console.log(` timeline extracted: ${report.timelineExtracted}`);
console.log(` corpus ingested: ${report.corpusIngested}`);
+ for (const f of report.corpus_files) {
+ console.log(` ${f.file}: ${f.windows_done} window(s) extracted, ${f.windows_remaining} remaining`);
+ }
if (report.skipped.length > 0) {
console.log(' skipped:');
for (const s of report.skipped) {
diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.ts
index b45834371d..39ae589bc4 100644
--- a/src/core/context/checkpoint-harvest.ts
+++ b/src/core/context/checkpoint-harvest.ts
@@ -8,12 +8,14 @@
* Discipline (sweep pass 3, shared fencing):
* claim (acquireCorpusClaim, O_EXCL) → `.ingested` re-check under claim →
* capability gate THEN kill switch → dream-output guard →
- * runFactsPipeline under a 60s abort → `signal.aborted` POST-check
+ * window 1 of the turn-boundary windows (corpus-windows.ts; an existing
+ * `.progress` means window 1 is done) under a 60s abort → POST-check
* (the pipeline returns normally with partial results on abort — an
* aborted run writes NOTHING and releases the claim: retryable) →
* RECEIPT sidecar (link candidates) → idempotent manifest publish from
* the receipt (each slug verified via source-scoped getPage; a link that
- * resolves to nothing is a lie and is skipped) → `.ingested` LAST.
+ * resolves to nothing is a lie and is skipped) → `.ingested` LAST, or, when
+ * windows remain, the receipt is released and the sweep finishes the tail.
* A transient manifest failure leaves receipt + released claim; the retry
* re-publishes from the receipt WITHOUT re-extracting (no duplicate spend,
* no lost links).
@@ -35,6 +37,7 @@ import type { CapabilityReport } from '../capability.ts';
import { acquireCorpusClaim, CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX } from '../sweep.ts';
import { appendCheckpointManifest } from './session-state.ts';
import { corpusFileSessionId, corpusTextForExtraction, readSegmentLedger, selfCaptureSidecarJson, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';
+import { corpusFileStat, readCorpusProgress, runCorpusWindows } from './corpus-windows.ts';
import { isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';
import { writeHeartbeat } from './hook-heartbeat.ts';
@@ -269,8 +272,14 @@ async function runOne(job: HarvestJob): Promise<{
// manifest publish failed transiently. Re-publish WITHOUT re-extracting.
let receipt = await readReceipt(receiptPath);
let counts: { inserted: number; duplicate: number } | null = null;
+ // #5887: the harvest extracts window 1 only; when more remains, `.progress`
+ // stands in for `.ingested` and the sweep finishes the tail.
+ let windowsPending = receipt !== null && (await readCorpusProgress(full))?.finished === null;
if (!receipt) {
+ // An existing `.progress` means window 1 is done (an earlier harvest or
+ // the sweep wrote it): never re-extract it here.
+ if (await readCorpusProgress(full)) return { outcome: 'ok', reason: 'windows_pending' };
// Gates in the pinned sweep order: capability THEN kill switch. A
// gate-skip releases the claim and writes NO sidecar — when the gate
// opens later, the sweep (which applies the same gates) extracts.
@@ -283,6 +292,7 @@ async function runOne(job: HarvestJob): Promise<{
return { outcome: 'degraded', reason: 'extraction_disabled' };
}
+ const fileStat = corpusFileStat(await stat(full));
const raw = await readFile(full, 'utf-8');
const { isDreamOutput } = await import('../cycle/transcript-discovery.ts');
const { runFactsPipeline } = await import('../facts/backstop.ts');
@@ -297,17 +307,21 @@ async function runOne(job: HarvestJob): Promise<{
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), job.timeoutMs ?? HARVEST_JOB_TIMEOUT_MS);
currentAbort = abort;
- let r: Awaited<ReturnType<typeof runFactsPipeline>>;
+ let run: Awaited<ReturnType<typeof runCorpusWindows>>;
try {
- r = await runFactsPipeline(corpusTextForExtraction(job.file, raw), {
- engine: job.engine,
- sourceId: job.sourceId,
- sessionId: job.sessionId,
- source: 'hook:compact',
- mode: 'inline',
- remote: false,
- abortSignal: abort.signal,
- // visibility deliberately unset → resolveDefaultVisibility [ENG-8]
+ // Paste stripping happens per turn inside the window planner (#5812).
+ run = await runCorpusWindows({
+ full, raw, fileStat, maxWindows: 1, overBudget: () => false, signal: abort.signal,
+ extract: (text) => runFactsPipeline(text, {
+ engine: job.engine,
+ sourceId: job.sourceId,
+ sessionId: job.sessionId,
+ source: 'hook:compact',
+ mode: 'inline',
+ remote: false,
+ abortSignal: abort.signal,
+ // visibility deliberately unset → resolveDefaultVisibility [ENG-8]
+ }),
});
} finally {
clearTimeout(timer);
@@ -315,8 +329,11 @@ async function runOne(job: HarvestJob): Promise<{
}
// POST-check (codex round 2): runFactsPipeline returns normally with
// PARTIAL results on abort. An aborted run writes NOTHING (no receipt,
- // no .ingested) and releases the claim — fully retryable.
- if (abort.signal.aborted) return { outcome: 'degraded', reason: 'aborted' };
+ // no .ingested, no progress) and releases the claim — fully retryable.
+ if (abort.signal.aborted || run.status === 'aborted') return { outcome: 'degraded', reason: 'aborted' };
+ if (run.status === 'contended') return { outcome: 'degraded', reason: 'claimed_elsewhere' };
+ windowsPending = run.status !== 'complete';
+ const r = run.result;
counts = { inserted: r.inserted, duplicate: r.duplicate };
receipt = {
@@ -356,6 +373,18 @@ async function runOne(job: HarvestJob): Promise<{
}
}
+ if (windowsPending) {
+ // Window 1's links are banked and `.progress` is written: release the
+ // receipt; the sweep extracts the remaining windows and writes `.ingested`.
+ await rm(receiptPath, { force: true }).catch(() => {});
+ return {
+ outcome: 'ok',
+ reason: 'windows_pending',
+ ...(counts ? { inserted: counts.inserted, duplicate: counts.duplicate } : {}),
+ links: verified.length,
+ };
+ }
+
// `.ingested` LAST — the sweep now skips this segment; the receipt has
// served its purpose and is removed (GC would otherwise orphan-reap it).
await writeFile(
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 7393ab1011..58ed9c1be1 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -79,6 +79,14 @@ export const CORPUS_CLAIM_SUFFIX = '.in-progress';
/** Claims older than this belong to dead sweeps and are reclaimable. */
export const CORPUS_CLAIM_STALE_MS = 60 * 60 * 1000;
+/** #5887 skip reason per unfinished window run (the file waits for a later sweep). */
+const CORPUS_WINDOW_SKIP = {
+ aborted: 'budget_exhausted:corpus',
+ contended: 'corpus_in_progress',
+ partial: 'corpus_windows_pending',
+ changed: 'corpus_changed',
+} as const;
+
export interface SweepOpts {
/** Source to sweep. Default 'default' (the serve's registered source). */
sourceId?: string;
@@ -110,6 +118,8 @@ export interface SweepReport {
/** Stale sweep-owned edges reconciled away (#4196). */
linksRemoved: number;
timelineExtracted: number;
+ /** #5887: per corpus file windowed this sweep — windows extracted now and still remaining. */
+ corpus_files: Array<{ file: string; windows_done: number; windows_remaining: number }>;
skipped: SweepSkip[];
durationMs: number;
}
@@ -136,6 +146,7 @@ export async function runMaintenanceSweep(
linksExtracted: 0,
linksRemoved: 0,
timelineExtracted: 0,
+ corpus_files: [],
skipped: [],
durationMs: 0,
};
@@ -515,11 +526,14 @@ async function runLinksTimelinePass(
}
/**
- * Pass 3 body. One `runFactsPipeline` call per unprocessed corpus file —
- * the narrowest existing entry that takes raw transcript text through
- * extract → resolve → dedup → insert. Visibility left unset so the
+ * Pass 3 body. `runFactsPipeline` — the narrowest existing entry that takes
+ * raw transcript text through extract → resolve → dedup → insert — runs once
+ * per writeback turn file and once per turn-boundary window of every other
+ * corpus file (#5887, context/corpus-windows.ts: per-file and per-sweep
+ * window caps, `.progress` resume). Visibility left unset so the
* pipeline resolves the operator default via resolveDefaultVisibility
- * (backstop.ts:359, [ENG-8]). Sidecar written AFTER success only.
+ * (backstop.ts:359, [ENG-8]). `.ingested` written only after the file's last
+ * window succeeds.
*
* Concurrency: a `<file>.in-progress` claim sidecar (O_EXCL create) fences
* each file before its LLM call — a manual `gbrain sweep --once` racing the
@@ -559,12 +573,10 @@ async function runCorpusIngestPass(
const txtFiles = entries.filter(n => n.endsWith('.txt')).sort();
if (txtFiles.length === 0) return;
- const alreadyIngested = txtFiles.filter(n => entrySet.has(n + CORPUS_INGESTED_SUFFIX));
- skip('already_ingested', alreadyIngested.length);
-
- const candidates = txtFiles
- .filter(n => !entrySet.has(n + CORPUS_INGESTED_SUFFIX))
- .slice(0, batchLimit);
+ // #5887: finished files re-enter when changed since their `.progress`.
+ const windows = await import('./context/corpus-windows.ts');
+ const { candidates, alreadyIngested } = await windows.selectCorpusCandidates(dir, txtFiles, entrySet, batchLimit, overBudget);
+ skip('already_ingested', alreadyIngested);
if (candidates.length === 0) return;
// Ambient-writeback turn files (`.wb-` basenames) ride this pass as the
@@ -627,11 +639,16 @@ async function runCorpusIngestPass(
const { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } = await import('./ai/providers/claude-cli-scratch.ts');
const selfProjectDirs = claudeCliSelfProjectDirs();
+ let windowsLeft = windows.resolveCorpusWindowsPerSweepTotal(process.env, log);
for (let i = 0; i < candidates.length; i++) {
if (overBudget()) {
skip('budget_exhausted:corpus', candidates.length - i);
break;
}
+ if (windowsLeft <= 0) {
+ skip('corpus_window_cap', candidates.length - i);
+ break;
+ }
const name = candidates[i];
const full = join(dir, name);
@@ -647,7 +664,10 @@ async function runCorpusIngestPass(
// Re-check under the claim: another sweep may have finished this file
// between our readdir and our claim (it releases its claim only after
// writing the .ingested sidecar, so this closes the double-spend gap).
- const doneAlready = await stat(full + CORPUS_INGESTED_SUFFIX).then(() => true, () => false);
+ const doneAlready = await stat(full + CORPUS_INGESTED_SUFFIX).then(
+ () => windows.finishedCorpusFileState(full, name).then(s => s === 'done' || s === 'legacy', () => false),
+ () => false,
+ );
if (doneAlready) {
skip('already_ingested');
continue;
@@ -680,6 +700,7 @@ async function runCorpusIngestPass(
continue;
}
+ const fileStat = windows.corpusFileStat(await stat(full));
const raw = await readFile(full, 'utf-8');
// Anti-loop: never ingest dream-generated outputs. Marking them
@@ -702,8 +723,7 @@ async function runCorpusIngestPass(
const wbSourceId = wbMeta?.sourceId && isValidSourceId(wbMeta.sourceId)
? wbMeta.sourceId
: sourceId;
- // #5812: pasted blocks never reach the extractor (file unchanged).
- const r = await runFactsPipeline(corpusTextForExtraction(name, raw), {
+ const pipelineCtx: FactsBackstopCtx = {
engine,
sourceId: wbMeta ? wbSourceId : sourceId,
sessionId: wbMeta ? wbMeta.sessionId : `sweep:corpus:${name}`,
@@ -718,7 +738,29 @@ async function runCorpusIngestPass(
abortSignal: signal,
...(wbMeta && wbCfg.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),
// visibility deliberately unset → resolveDefaultVisibility [ENG-8]
- });
+ };
+ // #5812: pasted blocks never reach the extractor (file unchanged). A wb
+ // file is one gated turn: one call. Every other corpus file is windowed
+ // at turn boundaries (#5887) and may finish over several sweeps.
+ let r: Awaited<ReturnType<typeof runFactsPipeline>>;
+ if (wbMeta) {
+ windowsLeft -= 1;
+ r = await runFactsPipeline(corpusTextForExtraction(name, raw), pipelineCtx);
+ } else {
+ const run = await windows.runCorpusWindows({
+ full, raw, fileStat, overBudget, signal,
+ maxWindows: Math.min(windows.CORPUS_WINDOWS_PER_SWEEP, windowsLeft),
+ extract: text => runFactsPipeline(text, pipelineCtx),
+ });
+ windowsLeft -= run.windowsDone;
+ report.corpus_files.push({ file: name, windows_done: run.windowsDone, windows_remaining: run.windowsRemaining });
+ if (run.status !== 'complete') {
+ abortLoop = run.status === 'aborted';
+ skip(CORPUS_WINDOW_SKIP[run.status], abortLoop ? candidates.length - i : 1);
+ continue;
+ }
+ r = run.result;
+ }
// POST-check (adversarial review, same class the harvest FIFO pins):
// runFactsPipeline returns NORMALLY with partial results when the
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 5d9f834fe2..04058f8742 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -1636,4 +1636,24 @@ describe('session-end remainder (cathedral 5 dedup contract)', () => {
expect(names).toContain('live.txt');
expect(names).toContain('live.txt.in-progress');
});
+
+ test('#5887: session-end reaps orphaned .progress sidecars and keeps a resumed session\'s live .progress', async () => {
+ const projRoot = join(tmp, 'projects');
+ const ws = join(tmp, 'ws');
+ mkdirSync(ws, { recursive: true });
+ mkdirSync(corpus(), { recursive: true });
+ writeFileSync(join(corpus(), 'gone.txt.progress'), '{}');
+ writeFileSync(join(corpus(), 'gone.txt.progress.lock'), '');
+ writeFileSync(join(corpus(), 'sess-prog.txt.progress'), '{"generation":1}');
+ const t1 = seedTranscript(join(projRoot, 'p1'), 'r5.jsonl', [userLine('resumed session content')]);
+ await runHook(['session-end'], {
+ stdin: JSON.stringify({ session_id: 'sess-prog', transcript_path: t1, cwd: ws }),
+ transcriptRoot: projRoot,
+ });
+ const names = readdirSync(corpus());
+ expect(names).not.toContain('gone.txt.progress');
+ expect(names).not.toContain('gone.txt.progress.lock');
+ expect(names).toContain('sess-prog.txt');
+ expect(readFileSync(join(corpus(), 'sess-prog.txt.progress'), 'utf8')).toBe('{"generation":1}');
+ });
});
diff --git a/test/managed-sweep-corpus-windows.test.ts b/test/managed-sweep-corpus-windows.test.ts
new file mode 100644
index 0000000000..ccbeac55a2
--- /dev/null
+++ b/test/managed-sweep-corpus-windows.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #5887 on a managed brain: windowed corpus extraction publishes every window
+ * through the persistence coordinator, and a resumed session submits only its
+ * new window.
+ *
+ * 1. Protects: each window's facts commit as their own coordinated facts batch
+ * (the batch key digests the window text, so windows never collide), and a
+ * rewrite that appends a turn leaves the finished windows' batches alone.
+ * 2. Fails when: the sweep sends the transcript once (head only), re-sends
+ * finished windows after a resume, or writes facts outside the coordinator
+ * (the armed managed writer guard refuses).
+ * 3. sweep-corpus-windows.test.ts covers the file-side protocol unmanaged only.
+ * 4. No production seam: gateway test transports only.
+ *
+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const KEYED: CapabilityReport = {
+ embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' },
+ search: 'keyword-only',
+ mode: 'keyed',
+};
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-managed-sweep-windows-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+let inputs: string[] = [];
+
+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };
+beforeAll(async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (request): Promise<ChatResult> => {
+ const content = String(request.messages[0].content);
+ const text = content.slice(content.indexOf('<turn>\n') + '<turn>\n'.length, content.lastIndexOf('\n</turn>'));
+ inputs.push(text);
+ const facts = [...new Set(text.match(/\bT\d\d\b/g) ?? [])].map((m) => ({
+ fact: `Alice Example owns workstream ${m}`, kind: 'fact', entity: 'people/alice-example', confidence: 0.9, notability: 'high',
+ }));
+ return { text: JSON.stringify({ facts }), blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };
+ });
+ // Orthogonal vectors per distinct text, so cosine dedup never merges different window facts.
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map((v) => {
+ const vec = Array(1536).fill(0);
+ vec[[...v].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 1536, 7)] = 1;
+ return vec;
+ }) })) as never);
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ __setChatTransportForTests(null); __setEmbedTransportForTests(null);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+const body = (tag: string): string => {
+ let s = `${tag} `;
+ while (s.length < 5000) s += `${tag.toLowerCase()} detail words\n`;
+ return s.slice(0, 5000);
+};
+const corpus = (count: number): string =>
+ toCorpusText(Array.from({ length: count }, (_, i) => ({ role: i % 2 === 0 ? 'user' as const : 'assistant' as const, text: body(`T${String(i).padStart(2, '0')}`) })));
+
+test('managed: every window commits its own coordinated facts batch; a resume submits only the new window', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-sweep-windows-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const corpusDir = join(dir, 'corpus'); mkdirSync(corpusDir);
+ const sourceId = `windows-${randomUUID().slice(0, 8)}`;
+ inputs = [];
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+ await claimWorktree(engine, sourceId, root);
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/alice-example',
+ content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n', request_id: randomUUID() } });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await expect(engine.executeRaw(`INSERT INTO facts(source_id,fact,kind,source,visibility) VALUES($1,'uncoordinated','fact','test','private')`,
+ [sourceId])).rejects.toThrow(/writer_coordinator_required/);
+
+ const file = join(corpusDir, 'managed-session.txt');
+ writeFileSync(file, corpus(3));
+ const sweep = () => runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000 });
+ const batches = async () => engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*) AS n FROM persistence_requests WHERE source_id=$1 AND state='committed' AND intent->>'kind'='managed_facts_complete'`,
+ [sourceId]).then((r) => Number(r[0].n));
+ const active = async () => (await engine.executeRaw<{ fact: string }>(
+ `SELECT fact FROM facts WHERE source_id=$1 AND source='sweep:corpus' AND expired_at IS NULL ORDER BY fact`, [sourceId])).map((r) => r.fact);
+
+ const r1 = await sweep();
+ expect(r1.corpusIngested).toBe(1);
+ expect(inputs.length).toBe(3);
+ expect(await batches()).toBe(3);
+ expect(await active()).toEqual(['Alice Example owns workstream T00', 'Alice Example owns workstream T01', 'Alice Example owns workstream T02']);
+
+ writeFileSync(file + '.tmp-hook', corpus(4));
+ renameSync(file + '.tmp-hook', file);
+ rmSync(file + CORPUS_INGESTED_SUFFIX, { force: true });
+ rmSync(file + CORPUS_CLAIM_SUFFIX, { force: true });
+ const r2 = await sweep();
+ expect(r2.corpusIngested).toBe(1);
+ expect(inputs.length).toBe(4);
+ expect(inputs[3]).toMatch(/^\[assistant\]\nT03 /);
+ expect(await batches()).toBe(4);
+ expect((await active()).at(-1)).toBe('Alice Example owns workstream T03');
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}, 180_000);
diff --git a/test/sweep-corpus-windows.test.ts b/test/sweep-corpus-windows.test.ts
new file mode 100644
index 0000000000..c5e82db46f
--- /dev/null
+++ b/test/sweep-corpus-windows.test.ts
@@ -0,0 +1,323 @@
+/**
+ * #5887 — the sweep's corpus pass extracts whole transcripts, window by
+ * window, across sweeps; the compact harvest extracts window 1 only.
+ *
+ * Protects: facts past the extractor's 8,000-char head are extracted; a long
+ * file converges over sweeps under the per-file (8) and per-sweep (32) caps
+ * with no window sent twice; appends, compaction remainders and same-size or
+ * shorter rewrites cost only their new turns; legacy `.ingested` files stay
+ * done; a sweep whose claim the hook deleted never re-extracts the window
+ * another sweep is working on; a retried harvest never re-extracts window 1.
+ * Fails on the pre-#5887 sweep, which sent each file once, head only.
+ * Imports only modules that predate #5887 so it runs against the old tree.
+ *
+ * Hermetic in-memory PGLite + chat-transport stub (sweep.test.ts harness).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX, runMaintenanceSweep, type SweepReport } from '../src/core/sweep.ts';
+import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import {
+ __drainCheckpointHarvestForTests,
+ __resetCheckpointHarvestForTests,
+ HARVEST_RECEIPT_SUFFIX,
+ scheduleCheckpointHarvest,
+} from '../src/core/context/checkpoint-harvest.ts';
+import { appendSegmentLedger, segmentFileName, writeSegment } from '../src/core/context/corpus-segments.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const KEYED: CapabilityReport = {
+ embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' },
+ search: 'keyword-only',
+ mode: 'keyed',
+};
+
+let engine: PGLiteEngine;
+let dir: string;
+const tmpDirs: string[] = [];
+let inputs: string[];
+let onCall: ((text: string, n: number) => Promise<void> | void) | null;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts').catch(() => {});
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-windows-'));
+ tmpDirs.push(dir);
+ await engine.setConfig('dream.synthesize.session_corpus_dir', dir);
+ inputs = [];
+ onCall = null;
+ __resetCheckpointHarvestForTests();
+ __setChatTransportForTests(async (request): Promise<ChatResult> => {
+ const content = String(request.messages[0].content);
+ const text = content.slice(content.indexOf('<turn>\n') + '<turn>\n'.length, content.lastIndexOf('\n</turn>'));
+ inputs.push(text);
+ if (onCall) await onCall(text, inputs.length);
+ const facts = text.includes('TAILMARK')
+ ? [{ fact: 'Prefers a quiet office for focused work', kind: 'preference', entity: null, confidence: 0.9, notability: 'high' }]
+ : [];
+ return {
+ text: JSON.stringify({ facts }),
+ blocks: [],
+ stopReason: 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:test-stub',
+ providerId: 'anthropic',
+ };
+ });
+});
+
+afterEach(() => {
+ __setChatTransportForTests(null);
+});
+
+const sweep = (): Promise<SweepReport> =>
+ runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 120_000, batchLimit: 20 });
+
+/** `T07 t07 detail words ...` padded to `n` chars — a unique, greppable turn body. */
+const body = (tag: string, n = 5000): string => {
+ let s = `${tag} `;
+ while (s.length < n) s += `${tag.toLowerCase()} detail words\n`;
+ return s.slice(0, n);
+};
+const turns = (count: number, from = 0, n = 5000): Array<['user' | 'assistant', string]> =>
+ Array.from({ length: count }, (_, i) => [(from + i) % 2 === 0 ? 'user' : 'assistant', body(`T${String(from + i).padStart(2, '0')}`, n)]);
+const corpus = (list: Array<['user' | 'assistant', string]>): string =>
+ toCorpusText(list.map(([role, text]) => ({ role, text })));
+
+/** The session-end hook's resume rewrite: atomic replace, then drop `.ingested` and the claim. */
+function hookRewrite(file: string, text: string): void {
+ writeFileSync(file + '.tmp-hook', text);
+ renameSync(file + '.tmp-hook', file);
+ rmSync(file + CORPUS_INGESTED_SUFFIX, { force: true });
+ rmSync(file + CORPUS_CLAIM_SUFFIX, { force: true });
+}
+
+const markers = (texts: string[]): string[] => texts.flatMap((t) => t.match(/\b[RST]\d\d\b/g) ?? []);
+
+describe('sweep corpus windows (#5887)', () => {
+ test('a transcript past 8,000 chars reaches the extractor whole; every window opens with a role header', async () => {
+ const file = join(dir, 'long.txt');
+ writeFileSync(file, corpus([...turns(2), ['user', 'TAILMARK I prefer a quiet office for focused work.']]));
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(inputs.length).toBeGreaterThan(1);
+ for (const t of inputs) {
+ expect(t.length).toBeLessThanOrEqual(8000);
+ expect(t).toMatch(/^\[(user|assistant)\]\n/);
+ }
+ expect(inputs.join('\n')).toContain('TAILMARK');
+ const facts = await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source = 'sweep:corpus'`);
+ expect(facts.some((f) => f.fact.includes('quiet office'))).toBe(true);
+ });
+
+ test('a 20-window file finishes in three sweeps (8, 8, 4) with no window sent twice; corpus_files reports progress', async () => {
+ const file = join(dir, 'twenty.txt');
+ writeFileSync(file, corpus(turns(20)));
+ const r1 = await sweep();
+ expect(r1.corpus_files).toEqual([{ file: 'twenty.txt', windows_done: 8, windows_remaining: 12 }]);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ const r2 = await sweep();
+ expect(r2.corpus_files).toEqual([{ file: 'twenty.txt', windows_done: 8, windows_remaining: 4 }]);
+ const r3 = await sweep();
+ expect(r3.corpus_files).toEqual([{ file: 'twenty.txt', windows_done: 4, windows_remaining: 0 }]);
+ expect(r3.corpusIngested).toBe(1);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(true);
+ expect(markers(inputs)).toEqual(turns(20).map(([, b]) => b.slice(0, 3)));
+ const r4 = await sweep();
+ expect(inputs.length).toBe(20);
+ expect(r4.skipped).toContainEqual({ reason: 'already_ingested', count: 1 });
+ });
+
+ test('a resumed session that appends turns re-sends only the new turns', async () => {
+ const file = join(dir, 'resume.txt');
+ writeFileSync(file, corpus(turns(3)));
+ await sweep();
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T02']);
+ inputs = [];
+ hookRewrite(file, corpus(turns(4)));
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T03']);
+ });
+
+ test('a compaction rewrite to the remainder re-extracts nothing', async () => {
+ const file = join(dir, 'compacted.txt');
+ writeFileSync(file, corpus(turns(4)));
+ await sweep();
+ inputs = [];
+ hookRewrite(file, corpus(turns(2, 2)));
+ const r = await sweep();
+ expect(inputs).toEqual([]);
+ expect(r.corpusIngested).toBe(1);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(true);
+ });
+
+ test('same-size and shorter rewrites of a finished file are re-extracted even when a stale .ingested survives', async () => {
+ const file = join(dir, 'replaced.txt');
+ const original = corpus(turns(2));
+ writeFileSync(file, original);
+ await sweep();
+ inputs = [];
+ const sameSize = original.replaceAll('T00', 'S00').replaceAll('t00', 's00');
+ expect(Buffer.byteLength(sameSize)).toBe(Buffer.byteLength(original));
+ writeFileSync(file + '.tmp-x', sameSize);
+ renameSync(file + '.tmp-x', file);
+ await sweep();
+ // Resume is at the first unrecorded turn; turns after it are re-read.
+ expect(markers(inputs)).toEqual(['S00', 'T01']);
+ inputs = [];
+ writeFileSync(file + '.tmp-x', corpus([['user', 'R00 a shorter replacement turn']]));
+ renameSync(file + '.tmp-x', file);
+ await sweep();
+ expect(inputs.join('\n')).toContain('R00');
+ });
+
+ test('a legacy .ingested file is not re-extracted, and its later growth extracts only the appended turns', async () => {
+ const file = join(dir, 'legacy.txt');
+ writeFileSync(file, corpus(turns(3)));
+ writeFileSync(file + CORPUS_INGESTED_SUFFIX, JSON.stringify({ ingested_at: new Date().toISOString() }) + '\n');
+ const r1 = await sweep();
+ expect(inputs).toEqual([]);
+ expect(r1.skipped).toContainEqual({ reason: 'already_ingested', count: 1 });
+ hookRewrite(file, corpus(turns(4)));
+ await sweep();
+ expect(markers(inputs)).toEqual(['T03']);
+ });
+
+ test('a 20,000-char pasted user turn puts zero paste text into any window', async () => {
+ const paste = `<pasted_content id="7">\n${'PASTEMARK third-party text. '.repeat(720)}\n</pasted_content id="7">`;
+ const file = join(dir, 'paste.txt');
+ writeFileSync(file, corpus([['user', `${body('OWNHEAD', 6000)} ${paste} ${body('OWNTAIL', 6000)}`], ['assistant', 'Noted.']]));
+ await sweep();
+ const all = inputs.join('\n');
+ expect(inputs.length).toBeGreaterThan(1);
+ expect(all).not.toContain('PASTEMARK');
+ expect(all).toContain('OWNHEAD');
+ expect(all).toContain('OWNTAIL');
+ });
+
+ test('a 20,000-char single assistant turn: every window carries the [assistant] header', async () => {
+ const file = join(dir, 'oversized.txt');
+ const big = body('ASSTMARK', 20_000);
+ writeFileSync(file, corpus([['user', 'Summarize the plan.'], ['assistant', big]]));
+ await sweep();
+ const chunks = inputs.flatMap((t) => t.split(/\n\n(?=\[(?:user|assistant)\]\n)/)).filter((p) => p.includes('asstmark'));
+ expect(chunks.length).toBeGreaterThanOrEqual(3);
+ for (const c of chunks) expect(c.startsWith('[assistant]\n')).toBe(true);
+ // The extractor trims each window, so compare the words, not the newlines at cuts.
+ const words = (t: string) => t.split(/\s+/).filter(Boolean);
+ expect(chunks.flatMap((c) => words(c.slice('[assistant]\n'.length)))).toEqual(words(big));
+ });
+
+ test('two sweeps racing one file after the hook deleted the claim never extract a window twice', async () => {
+ const file = join(dir, 'race.txt');
+ writeFileSync(file, corpus(turns(3)));
+ let release!: () => void;
+ const released = new Promise<void>((r) => { release = r; });
+ let entered!: () => void;
+ const inFirstWindow = new Promise<void>((r) => { entered = r; });
+ onCall = async (_text, n) => {
+ if (n === 1) { entered(); await released; }
+ };
+ const first = sweep();
+ await inFirstWindow;
+ rmSync(file + CORPUS_CLAIM_SUFFIX, { force: true }); // the hook's resume path drops claims
+ const second = await sweep();
+ release();
+ const r1 = await first;
+ expect(second.skipped).toContainEqual({ reason: 'corpus_in_progress', count: 1 });
+ expect(r1.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T02']);
+ });
+
+ test('an append that lands between two windows is extracted exactly once', async () => {
+ const file = join(dir, 'between.txt');
+ writeFileSync(file, corpus(turns(3)));
+ onCall = (_text, n) => { if (n === 2) hookRewrite(file, corpus(turns(4))); };
+ const r1 = await sweep();
+ expect(r1.corpusIngested).toBe(0);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ onCall = null;
+ const r2 = await sweep();
+ expect(r2.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T02', 'T03']);
+ });
+
+ test('the 33rd window across files waits for the next sweep', async () => {
+ for (const f of ['a', 'b', 'c', 'd', 'e']) writeFileSync(join(dir, `${f}.txt`), corpus(turns(8)));
+ const r1 = await sweep();
+ expect(inputs.length).toBe(32);
+ expect(r1.skipped).toContainEqual({ reason: 'corpus_window_cap', count: 1 });
+ expect(existsSync(join(dir, 'e.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);
+ await sweep();
+ expect(inputs.length).toBe(40);
+ expect(existsSync(join(dir, 'e.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);
+ });
+
+ test('GBRAIN_CORPUS_WINDOWS_PER_SWEEP=2 extracts two windows in a sweep', async () => {
+ writeFileSync(join(dir, 'knob.txt'), corpus(turns(5)));
+ await withEnv({ GBRAIN_CORPUS_WINDOWS_PER_SWEEP: '2' }, () => sweep());
+ expect(inputs.length).toBe(2);
+ expect(markers(inputs)).toEqual(['T00', 'T01']);
+ });
+
+ test('a transport failure keeps finished windows; the retry resumes at the failed window', async () => {
+ const file = join(dir, 'flaky.txt');
+ writeFileSync(file, corpus(turns(3)));
+ onCall = (_text, n) => { if (n === 2) throw new Error('fixture transport failure'); };
+ const r1 = await sweep();
+ expect(r1.corpusIngested).toBe(0);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ onCall = null;
+ const r2 = await sweep();
+ expect(r2.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T01', 'T02']);
+ });
+});
+
+describe('compact harvest extracts window 1 only (#5887)', () => {
+ test('a long segment: harvest window 1, a retried harvest re-extracts nothing, one sweep finishes the rest', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-sweep-windows-home-'));
+ tmpDirs.push(home);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const text = corpus(turns(4));
+ const w = writeSegment(dir, 'sess-long', text);
+ appendSegmentLedger(dir, 'sess-long', w.hash);
+ const file = segmentFileName('sess-long', w.hash);
+ const full = join(dir, file);
+ const job = { engine, sourceId: 'default', sessionId: 'sess-long', corpusDir: dir, file, capabilities: KEYED };
+
+ expect(scheduleCheckpointHarvest(job).status).toBe('scheduled');
+ await __drainCheckpointHarvestForTests();
+ expect(markers(inputs)).toEqual(['T00']);
+ expect(existsSync(full + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ expect(existsSync(full + HARVEST_RECEIPT_SUFFIX)).toBe(false);
+ expect(JSON.parse(readFileSync(full + '.progress', 'utf8')).windows_done).toBe(1);
+
+ expect(scheduleCheckpointHarvest(job).status).toBe('scheduled');
+ await __drainCheckpointHarvestForTests();
+ expect(inputs.length).toBe(1);
+
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T02', 'T03']);
+ expect(existsSync(full + CORPUS_INGESTED_SUFFIX)).toBe(true);
+ });
+ });
+});
diff --git a/test/sweep.test.ts b/test/sweep.test.ts
index 2582f26e7e..7380c85826 100644
--- a/test/sweep.test.ts
+++ b/test/sweep.test.ts
@@ -724,6 +724,7 @@ describe('runMaintenanceSweep — budget + never-throw', () => {
linksExtracted: 1,
linksRemoved: 0,
timelineExtracted: 0,
+ corpus_files: [],
skipped: [{ reason: 'budget_exhausted:corpus', count: 2 }],
durationMs: 10,
};