Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sweep): review fixes for the corpus failure cap (#6785, #6786)
garrytan9d11cca4dd3b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13b6ce0350..522cbfa1f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,13 +30,14 @@ After upgrading, transcripts an earlier verify marked this way are extracted aga### Itemized changes-- `src/core/context/corpus-segments.ts`: `corpusFileCompletion` is the one completion classifier for sweep selection, the under-claim re-check and retention GC (`corpusSidecarState` for the HTTP drain and the doctor backlog). A sidecar whose `skipped` is `chat_unavailable` is pending, and only finished files get the plain retention; unavailable, partial and rewritten files keep the un-ingested ceiling. The failure record format (`<file>.failures.json`, `CORPUS_WINDOW_FAILURE_CAP` 5) lives here too, and the session-end hook reaps it with its `.txt`.-- `src/core/context/corpus-windows.ts`: `runCorpusWindows` returns `unavailable` without recording the window, and rewinds a progress an earlier build finished as `chat_unavailable` to its retired turns under the same compare-and-set that takes the lease. A failure thrown after a chat call counts against the window's start and the source incarnation; neither tail growth nor the error label resets it, and a commit of that window clears it. One change of the extraction-config fingerprint (model, provider, key presence; no values) re-arms a stopped window once.-- `src/core/sweep.ts`: the corpus pass runs the facts-absorb owner-readiness preflight (#5362) per source before any model call, applies the failure cap to writeback turn files as well, stops the pass on `chat_unavailable`, and logs thrown errors with their code. `corpus: false` skips the pass. `armCorpusDrain` logs the sweep's diagnostics (each distinct line once) and its skip reasons whenever they change.-- `src/core/context/checkpoint-harvest.ts`: the compact and writeback lanes run the same preflight; the compact lane writes no receipt for an `unavailable`, backing-off or stopped window.+- `src/core/context/corpus-segments.ts`: `corpusFileCompletion` is the one completion classifier for sweep selection, the under-claim re-check, retention GC, the HTTP drain and the doctor backlog, so a rewritten file counts as pending everywhere. A sidecar whose `skipped` is `chat_unavailable` is pending, and only finished files get the plain retention; unavailable, partial and rewritten files keep the un-ingested ceiling. The failure record format (`<file>.failures.json`, `CORPUS_WINDOW_FAILURE_CAP` 5) lives here too, and the session-end hook reaps it with its `.txt`.+- `src/core/context/corpus-windows.ts`: `runCorpusWindows` returns `unavailable` without recording the window, and rewinds a progress an earlier build finished as `chat_unavailable` to its retired turns under the same compare-and-set that takes the lease. A failure thrown after an admitted chat call counts against the window's start and the source incarnation, and so does a paid window whose progress could not be committed; a call the spend guard refuses before the provider does not count, however the extractor wraps the refusal. Neither tail growth nor the error label resets the count, and a commit of that window clears it. Selection serves backing-off and stopped files after every other candidate, so they never take a whole batch. One change of the extraction-config fingerprint (model, provider, key presence; no values) re-arms a stopped window once.+- `src/core/sweep.ts`: the corpus pass runs the facts-absorb owner-readiness preflight (#5362) per source before any model call, applies the failure cap to writeback turn files as well, stops the pass on `chat_unavailable`, charges every attempted window (a thrown one included) against the per-sweep total, and logs thrown errors with their code. `corpus: false` skips the pass. `armCorpusDrain` logs the sweep's diagnostics (each distinct line once) and its skip reasons whenever they change.+- `src/core/context/checkpoint-harvest.ts`: the compact and writeback lanes run the same preflight and the same failure cap; neither writes a receipt or sidecar for an `unavailable`, backing-off or stopped window.+- `src/core/context-engine.ts`: the OpenClaw `compact()` inline harvest on Postgres (rung 3) runs the same preflight, leaves a segment with a failing window to the sweep, keeps a `chat_unavailable` segment pending, and records any other skip reason in its sidecar.- `src/core/bootstrap/verify.ts`: the in-process sweep runs passes 1 and 2 only.- `gbrain sweep --retry-failed [--apply] [--json]` (`src/commands/sweep.ts`); doctor `memory_writeback` warns about stopped windows and names `gbrain sweep --retry-failed --apply` (paid) as its fix. `corpus_chat_unavailable`, `corpus_window_backoff` and `corpus_window_dead_lettered` are registered, so `gbrain errors <code>` explains them.-- Tests: `test/sweep-corpus-chat-unavailable-6786.test.ts` (unservable model in the sweep and the compact harvest; legacy sidecars with and without `.progress`, asserting the facts exist; GC then sweep and sweep then GC with an aged file) and `test/sweep-corpus-failure-cap-6785.test.ts` (a claim landing mid-call, the harvest preflight, the drain log, the retry schedule, the re-arm, doctor's fix and the operator retry). A new `bootstrap-verify.serial.test.ts` case runs the real verify with a keyed report and no gateway. The new behavior cases fail on the previous tree.+- Tests: `test/sweep-corpus-chat-unavailable-6786.test.ts` (unservable model in the sweep and the compact harvest; legacy sidecars with and without `.progress`, asserting the facts exist; GC then sweep and sweep then GC with an aged file), `test/sweep-corpus-failure-cap-6785.test.ts` (a claim landing mid-call, the harvest preflight, the drain log, the retry schedule, the re-arm, doctor's fix and the operator retry, stopped files ahead of a healthy one, the window total under thrown windows, an uncommitted paid window, a refused call, the writeback harvest cap, and the drain and backlog classifier) and two rung-3 cases in `test/e2e/context-engine-rung3-extraction.test.ts`. A new `bootstrap-verify.serial.test.ts` case runs the real verify with a keyed report and no gateway. The new behavior cases fail on the previous tree.## [0.60.251.0] - 2026-10-15diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 07eaadb737..b55df7ee5f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -646,7 +646,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.251.0', text: 'A take graded only in the database (for example by `grade_takes` on a source without managed persistence) keeps its grade when its page is published again from a fence that has no resolution cells: a prose edit, a re-import, a sync or `revert_version` to a version from before the grade. Before, every such publish erased the grade. A fence that carries resolution cells still writes them, and a take whose claim is edited in place (same row number) now drops the old claim\'s grade.' },{ since: '0.60.251.0', text: 'After `purge_fact` or a page purge, no read returns the purged text from what the purge hid: a page a purge hid for re-derivation now reads as missing in `get_page` and `fetch` (even with `include_deleted`) and returns no `get_versions` history, and a page purge now hides rows derived from the page and its facts, as `purge_fact` already did. `purge_fact` now redacts every retained version of a page (it stopped after 5,000), and its receipt\'s `pages` and `page_versions` stores also report a page or version that still states the claim in its title or frontmatter, alongside prose (`out_of_scope: source_prose`).' },// #6785/#6786 corpus hotfix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.- { since: '0.60.251.0', text: 'A session transcript whose extraction answered `chat_unavailable` (no usable extraction model, as in every `gbrain bootstrap verify` before this release) is no longer marked ingested: it stays pending, and files an earlier build marked `skipped: chat_unavailable` are extracted again by the next sweeps. That is a one-time paid catch-up after upgrading, bounded by the sweep window caps (8 windows per file and 32 per sweep; `GBRAIN_CORPUS_WINDOWS_PER_SWEEP` lowers the total) and paused by `GBRAIN_SWEEP=0` or `gbrain config set facts.extraction_enabled false`. Nothing is rewritten during the upgrade, and retention keeps those files for 3x `dream.synthesize.corpus_retention_days` until they are extracted. `bootstrap verify` no longer runs the corpus pass. The sweep and both harvest lanes check a claimed but not activated canonical worktree before any model call and skip it as `writer_coordinator_required`, naming `gbrain sources writer status <source>`. A corpus window that fails after its model call is retried on the next sweep, then after 10, 20 and 40 minutes, then no longer paid for (`corpus_window_dead_lettered`) until `gbrain sweep --retry-failed --apply` (paid, preview without `--apply`) or one extraction model or provider change. The `serve --http` corpus drain writes its skip reasons and failures to stderr.' },+ { since: '0.60.251.0', text: 'A session transcript whose extraction answered `chat_unavailable` (no usable extraction model, as in every `gbrain bootstrap verify` before this release) is no longer marked ingested: it stays pending, and files an earlier build marked `skipped: chat_unavailable` are extracted again by the next sweeps. That is a one-time paid catch-up after upgrading, bounded by the sweep window caps (8 windows per file and 32 per sweep; `GBRAIN_CORPUS_WINDOWS_PER_SWEEP` lowers the total) and paused by `GBRAIN_SWEEP=0` or `gbrain config set facts.extraction_enabled false`. Nothing is rewritten during the upgrade, and retention keeps those files for 3x `dream.synthesize.corpus_retention_days` until they are extracted. `bootstrap verify` no longer runs the corpus pass. The sweep, both harvest lanes and the OpenClaw `compact()` inline harvest check a claimed but not activated canonical worktree before any model call and skip it as `writer_coordinator_required`, naming `gbrain sources writer status <source>`. A corpus window that fails after its model call is retried on the next sweep, then after 10, 20 and 40 minutes, then no longer paid for (`corpus_window_dead_lettered`) until `gbrain sweep --retry-failed --apply` (paid, preview without `--apply`) or one extraction model or provider change. The `serve --http` corpus drain writes its skip reasons and failures to stderr.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex 4976dba859..5de57d7ea6 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -14,6 +14,7 @@*/import type { OpenclawBoundaryTail } from './context/corpus-segments.ts';+import type { BrainEngine } from './engine.ts';import { readFileSync, existsSync, statSync } from 'fs';import { join } from 'path';import { buildReflexAddition, warmReflex, type ResolveEntitiesFn as ReflexResolveEntitiesFn } from './context/reflex.ts';@@ -914,6 +915,30 @@ async function recordOpenclawSeat(dir: string, sessionId: string, sessionFile: s} catch { /* provenance and telemetry never fail the checkpoint */ }}+/**+ * Rung 3: why a segment is left to the sweep before any model call, or null.+ * #6786: finished by the one completion classifier (a `chat_unavailable`+ * sidecar is pending). #6785: a failing window, whose retry cap the sweep owns.+ */+async function rung3SegmentHold(fullPath: string, name: string): Promise<string | null> {+ const segs = await import('./context/corpus-segments.ts');+ if (!segs.corpusFileAwaitsExtraction(fullPath, name)) return 'already_ingested';+ const failing = segs.readCorpusFailure(fullPath);+ if (!failing) return null;+ return failing.count >= segs.CORPUS_WINDOW_FAILURE_CAP ? 'corpus_window_dead_lettered' : 'corpus_window_backoff';+}++/** Rung 3, #6785: the owner-readiness preflight; true when a claimed, not activated worktree holds the source. */+async function rung3WriterHeld(engine: BrainEngine, sourceId: string): Promise<boolean> {+ try {+ await (await import('./persistence/filesystem-guard.ts')).assertSourceLegacyWriter(engine, sourceId);+ return false;+ } catch (e) {+ if ((e as { code?: unknown }).code !== 'writer_coordinator_required') throw e;+ return true;+ }+}+// ── Engine Implementation ───────────────────────────────────────────────export function createGBrainContextEngine(ctx: {@@ -1197,10 +1222,8 @@ export function createGBrainContextEngine(ctx: {// identical content maps to the same filename — if a prior run (or the// sweep) already ingested it, re-running the pipeline is pure duplicate// LLM spend absorbed only by fact-level dedup.- const { existsSync: ingested } = await import('node:fs');- if (ingested(fullPath + sweep.CORPUS_INGESTED_SUFFIX)) {- return { status: 'banked', reason: 'already_ingested' };- }+ const held = await rung3SegmentHold(fullPath, segName(w.hash));+ if (held) return { status: 'banked', reason: held };const gate = await (await import('./context/capture-consent.ts')).gateCorpusFile(pg, fullPath, 'compact');if (gate.action !== 'extract') return { status: 'banked', reason: gate.reason };const { extractionAvailableForEngine } = await import('./facts/extraction-availability.ts');@@ -1211,6 +1234,7 @@ export function createGBrainContextEngine(ctx: {const fileSource = await (await import('./context/corpus-source.ts')).resolveCorpusFileSource(pg, root, segName(w.hash), 'spool');if (!fileSource.ok) return { status: 'banked', reason: fileSource.reason };const sourceId = fileSource.sourceId;+ if (await rung3WriterHeld(pg, sourceId)) return { status: 'banked', reason: 'writer_coordinator_required' };if (deadlineHit()) return { status: 'banked', reason: 'deadline' };const { runFactsPipeline } = await import('./facts/backstop.ts');const abort = new AbortController();@@ -1237,6 +1261,8 @@ export function createGBrainContextEngine(ctx: {// Post-check: the pipeline returns normally with PARTIALS on abort — an// aborted run writes no sidecar and stays sweep-retryable.if (abort.signal.aborted) return { status: 'banked', reason: 'aborted' };+ // #6786: no servable model is not an outcome; the segment stays pending for the sweep.+ if (r.skipped_reason === 'chat_unavailable') return { status: 'banked', reason: 'extract_skipped_chat_unavailable' };const verified: Array<{ slug: string; title: string }> = [];for (const slug of r.entity_slugs) {try {@@ -1261,6 +1287,7 @@ export function createGBrainContextEngine(ctx: {ingested_at: new Date().toISOString(),facts_inserted: r.inserted,facts_duplicate: r.duplicate,+ ...(r.skipped_reason ? { skipped: r.skipped_reason } : {}),links_banked: published ? verified.length : 0,}) + '\n');if (!published) return { status: 'harvested', links: verified, reason: 'manifest_failed' };diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.tsindex 6551688c98..f55671adbe 100644--- a/src/core/context/checkpoint-harvest.ts+++ b/src/core/context/checkpoint-harvest.ts@@ -37,7 +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, parseSegmentFileName, readSegmentLedger, selfCaptureSidecarJson, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';-import { corpusFileStat, readCorpusProgress, runCorpusWindows } from './corpus-windows.ts';+import { corpusFileStat, readCorpusProgress, runCorpusTurn, runCorpusWindows } from './corpus-windows.ts';import { isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';import { writeHeartbeat } from './hook-heartbeat.ts';import { OperationError } from '../ops/contract.ts';@@ -431,6 +431,7 @@ async function runOne(job: HarvestJob): Promise<{// Paste stripping happens per turn inside the window planner (#5812).run = await runCorpusWindows({full, raw, fileStat, maxWindows: 1, overBudget: () => false, signal: abort.signal,+ failures: { fingerprint: await harvestFingerprint(job) },...(job.sourceIncarnation ? { source: { id: job.sourceId, incarnation: job.sourceIncarnation } } : {}),extract: (text) => runFactsPipeline(text, {engine: job.engine,@@ -593,25 +594,33 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: strconst abort = new AbortController();const timer = setTimeout(() => abort.abort(), job.timeoutMs ?? HARVEST_JOB_TIMEOUT_MS);currentAbort = abort;- let r: Awaited<ReturnType<typeof runFactsPipeline>>;+ let turn: Awaited<ReturnType<typeof runCorpusTurn>>;try {- r = await runFactsPipeline(corpusTextForExtraction(job.file, raw), {- engine: job.engine,- sourceId: job.sourceId,- sessionId: job.sessionId,- source: 'hook:writeback',- mode: 'inline',- remote: false,- abortSignal: abort.signal,- notabilityFilter: gate.mode === 'salient' ? 'medium-and-up' : 'all',- // visibility deliberately unset → resolveDefaultVisibility [ENG-8] —- // the backstop inherits extract_facts' contract, never widened (req 6).+ // #6785: the same failure cap as the sweep's turn files (one record per file).+ turn = await runCorpusTurn({+ full, signal: abort.signal, incarnation: job.sourceIncarnation ?? null,+ failures: { fingerprint: await harvestFingerprint(job) },+ extract: () => runFactsPipeline(corpusTextForExtraction(job.file, raw), {+ engine: job.engine,+ sourceId: job.sourceId,+ sessionId: job.sessionId,+ source: 'hook:writeback',+ mode: 'inline',+ remote: false,+ abortSignal: abort.signal,+ notabilityFilter: gate.mode === 'salient' ? 'medium-and-up' : 'all',+ // visibility deliberately unset → resolveDefaultVisibility [ENG-8] —+ // the backstop inherits extract_facts' contract, never widened (req 6).+ }),});} finally {clearTimeout(timer);currentAbort = null;}if (abort.signal.aborted) return { outcome: 'degraded', reason: 'aborted' };+ if (turn.status === 'unavailable') return { outcome: 'degraded', reason: 'extract_skipped_chat_unavailable' };+ if (turn.status !== 'complete') return { outcome: 'degraded', reason: `corpus_window_${turn.status}` };+ const r = turn.result;if (r.skipped_reason) {// Non-transport extraction skip (refusal / content_filter /// malformed_output / non_terminal_stop / chat_unavailable): NOT terminal@@ -643,6 +652,12 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str* write after extraction; the turn stays banked (no sidecar) for the sweep,* which holds it under the same check until `gbrain sources writer activate`.*/+/** #6785: the extraction-config fingerprint a capped window re-arms on (null: never re-arms). */+async function harvestFingerprint(job: HarvestJob): Promise<string | null> {+ const { extractionConfigFingerprint } = await import('../facts/extraction-availability.ts');+ return extractionConfigFingerprint(job.engine).catch(() => null);+}+async function writerRefused(job: HarvestJob): Promise<boolean> {const { assertSourceLegacyWriter } = await import('../persistence/filesystem-guard.ts');try {diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.tsindex cbfbf75d30..1c0c905970 100644--- a/src/core/context/corpus-segments.ts+++ b/src/core/context/corpus-segments.ts@@ -699,6 +699,15 @@ export function corpusFileFinished(state: CorpusFileCompletion): boolean {return state === 'done' || state === 'legacy';}+/** Whether a corpus file still waits for extraction, by `corpusFileCompletion`; a file that is gone does not. */+export function corpusFileAwaitsExtraction(full: string, name: string): boolean {+ try {+ return !corpusFileFinished(corpusFileCompletion(full, name));+ } catch {+ return existsSync(full);+ }+}+/*** #6785: per-file record of the one corpus window (or writeback turn) whose* extraction keeps failing after the model call. Written under the file's@@ -757,7 +766,7 @@ export function listCorpusFailures(dir: string): Array<{ name: string; full: str}export interface CorpusBacklog {- /** `.txt` files with no final `.ingested` sidecar. */+ /** `.txt` files not finished by `corpusFileCompletion` (no final sidecar, or windows left). */pending: number;/** mtime of the oldest pending file, or null with none pending. */oldestPendingMtimeMs: number | null;@@ -777,7 +786,7 @@ export function corpusBacklog(dir: string, retentionMs: number, now = Date.now()const present = new Set(names);for (const name of names) {if (!name.endsWith('.txt')) continue;- if (present.has(name + INGESTED_SUFFIX) && corpusSidecarState(join(dir, name)) === 'final') continue;+ if (present.has(name + INGESTED_SUFFIX) && !corpusFileAwaitsExtraction(join(dir, name), name)) continue;let mtimeMs: number;try {mtimeMs = statSync(join(dir, name)).mtimeMs;diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.tsindex 46dee3c7b5..3fc980ec39 100644--- a/src/core/context/corpus-windows.ts+++ b/src/core/context/corpus-windows.ts@@ -32,7 +32,7 @@ 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 { isAIInvocationPolicyError, withAIInvocationPreflight } from '../ai/invocation-guard.ts';+import { isAIInvocationPolicyError, withAIInvocationGuard } from '../ai/invocation-guard.ts';import { parseCorpusTurns, type CorpusTurn } from './corpus-turns.ts';import {CORPUS_FAILURE_SUFFIX, CORPUS_NON_TERMINAL_SKIPS, CORPUS_PROGRESS_LOCK_SUFFIX, CORPUS_PROGRESS_SUFFIX, CORPUS_WINDOW_FAILURE_CAP,@@ -435,11 +435,29 @@ function rearms(record: CorpusFailureRecord, fingerprint: string | null): boolea}/**- * #6785: run one extraction; when it throws after reaching a chat model call- * (the spend), count a failure against the window at `key`, then rethrow.- * A throw before any model call, an abort, a spend-policy refusal, or capture- * switched off mid-call (the next sweep retires the file) costs nothing to- * retry and is not counted.+ * #6785: whether the file's recorded failing window is backing off or+ * stopped right now. Selection serves these files last, so stopped files+ * never take every batch slot from healthy ones.+ */+export function corpusFileParked(full: string, fingerprint: string | null, nowMs: number): boolean {+ const record = readCorpusFailure(full);+ return !!record && corpusFailureGate(record, record.key, record.source_incarnation, fingerprint, nowMs) !== 'run';+}++function isPolicyRefusal(e: unknown): boolean {+ for (let cur: unknown = e, depth = 0; cur && depth < 8; cur = (cur as { cause?: unknown }).cause, depth++) {+ if (isAIInvocationPolicyError(cur)) return true;+ }+ return false;+}++/**+ * #6785: run one extraction; when it throws after a chat model call was+ * admitted (the spend), count a failure against the window at `key`, then+ * rethrow. A throw before any admitted model call (a spend-policy refusal+ * included, however the extractor wraps it), an abort, or capture switched+ * off mid-call (the next sweep retires the file) costs nothing to retry and+ * is not counted.*/export async function extractUnderFailureCount<T>(failure: { full: string; record: CorpusFailureRecord | null; key: string; incarnation: string | null; fingerprint: string | null; nowMs: () => number; signal?: AbortSignal },@@ -447,10 +465,14 @@ export async function extractUnderFailureCount<T>(): Promise<T> {let chatCalled = false;try {- return await withAIInvocationPreflight(async (call) => { if (call.kind === 'chat') chatCalled = true; }, extract);+ // Inherit: an outer guard admits first, so this one only sees admitted calls.+ return await withAIInvocationGuard(async (call) => {+ if (call.kind === 'chat') chatCalled = true;+ return { settle: async () => {} };+ }, extract, { inherit: true });} catch (e) {const counts = chatCalled && !failure.signal?.aborted && !(e instanceof Error && e.name === 'AbortError')- && !isAIInvocationPolicyError(e) && (e as { code?: unknown } | null)?.code !== 'ambient_capture_off';+ && !isPolicyRefusal(e) && (e as { code?: unknown } | null)?.code !== 'ambient_capture_off';if (counts) {await recordCorpusFailure(failure.full, failure.record, failure.key, failure.incarnation, failure.fingerprint, failure.nowMs(), e).catch(() => {});}@@ -514,6 +536,8 @@ export async function runCorpusTurn(opts: {signal?: AbortSignal;incarnation: string | null;failures?: { fingerprint: string | null; now?: () => number };+ /** Incremented before each attempted extraction, thrown or not: the caller's window budget. */+ attempted?: { count: number };extract: () => Promise<PipelineResult>;}): Promise<{ status: 'complete'; result: PipelineResult } | { status: 'unavailable' | 'backoff' | 'dead_lettered' }> {const fingerprint = opts.failures?.fingerprint ?? null;@@ -521,6 +545,7 @@ export async function runCorpusTurn(opts: {const record = readCorpusFailure(opts.full);const gate = corpusFailureGate(record, CORPUS_TURN_FAILURE_KEY, opts.incarnation, fingerprint, clock());if (gate !== 'run') return { status: gate };+ if (opts.attempted) opts.attempted.count++;const result = await extractUnderFailureCount({ full: opts.full, record, key: CORPUS_TURN_FAILURE_KEY, incarnation: opts.incarnation, fingerprint, nowMs: clock, signal: opts.signal },opts.extract,@@ -568,6 +593,8 @@ export async function runCorpusWindows(opts: {source?: CorpusProgressSource;/** #6785: the extraction-config fingerprint that may re-arm a capped window once (null: never), and the clock. */failures?: { fingerprint: string | null; now?: () => number };+ /** Incremented before each attempted window, thrown or not: the caller's window budget. */+ attempted?: { count: number };}): Promise<CorpusWindowRun> {const { full, fileStat, signal, source } = opts;const incarnation = source?.incarnation ?? null;@@ -608,6 +635,7 @@ export async function runCorpusWindows(opts: {const gate = corpusFailureGate(failure, key, incarnation, fingerprint, clock());if (gate !== 'run') { status = gate; break; }const text = win.text;+ if (opts.attempted) opts.attempted.count++;r = await extractUnderFailureCount({ full, record: failure, key, incarnation, fingerprint, nowMs: clock, signal }, () => opts.extract(text));if (r.skipped_reason && CORPUS_NON_TERMINAL_SKIPS.includes(r.skipped_reason)) { status = 'unavailable'; break; }}@@ -617,7 +645,7 @@ export async function runCorpusWindows(opts: {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) => {+ const commit = 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 {@@ -634,7 +662,22 @@ export async function runCorpusWindows(opts: {lease: isLast ? null : { owner, at: Date.now() },};});- if (!next) { status = 'contended'; break; }+ // #6785: a paid window whose progress did not commit is paid again next time; it counts like a thrown one.+ const countUncommitted = (e: unknown) => r+ ? recordCorpusFailure(full, failure, key, incarnation, fingerprint, clock(), e).catch(() => failure)+ : Promise.resolve(failure);+ let next: CorpusProgress | null;+ try {+ next = await commit;+ } catch (e) {+ await countUncommitted(e);+ throw e;+ }+ if (!next) {+ failure = await countUncommitted({ code: 'corpus_progress_contended' });+ status = 'contended';+ break;+ }state = next;if (failure?.key === key) {await clearCorpusFailure(full).catch(() => {});@@ -672,7 +715,9 @@ export async function runCorpusWindows(opts: {* 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.+ * most `batchLimit`), the files `parked` says are backing off or stopped+ * (#6785: at most `batchLimit`, served after every candidate so they never+ * starve healthy files), and how many files are already done.*/export async function selectCorpusCandidates(dir: string,@@ -680,8 +725,10 @@ export async function selectCorpusCandidates(entrySet: Set<string>,batchLimit: number,overBudget: () => boolean,-): Promise<{ candidates: string[]; alreadyIngested: number }> {+ parked: (full: string) => boolean = () => false,+): Promise<{ candidates: string[]; deferred: string[]; alreadyIngested: number }> {const candidates: string[] = [];+ const deferred: string[] = [];let alreadyIngested = 0;for (const name of txtFiles) {const full = join(dir, name);@@ -691,7 +738,9 @@ export async function selectCorpusCandidates(if (state === 'legacy' && !overBudget()) await adoptFinishedCorpusFile(full).catch(() => false);}if (corpusFileFinished(state)) alreadyIngested++;- else if (candidates.length < batchLimit) candidates.push(name);+ else if (entrySet.has(name + CORPUS_FAILURE_SUFFIX) && parked(full)) {+ if (deferred.length < batchLimit) deferred.push(name);+ } else if (candidates.length < batchLimit) candidates.push(name);}- return { candidates, alreadyIngested };+ return { candidates, deferred, alreadyIngested };}diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 943168e83e..dcc5c9059c 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -631,6 +631,11 @@ async function runCorpusIngestPass(const windows = await import('./context/corpus-windows.ts');type Candidate = { base: string; name: string; location: 'spool' | 'legacy'; label: string };const candidates: Candidate[] = [];+ const deferred: Candidate[] = [];+ // #6785: a capped window re-arms once when this fingerprint changed since its last failure.+ const { extractionConfigFingerprint } = await import('./facts/extraction-availability.ts');+ const fingerprint = await extractionConfigFingerprint(engine).catch(() => null);+ const parkedAt = now();for (const [base, location] of [[spoolDir, 'spool'], [dir, 'legacy']] as const) {let entries: string[];try {@@ -643,12 +648,14 @@ async function runCorpusIngestPass(const txtFiles = entries.filter(n => n.endsWith('.txt')).sort();if (txtFiles.length === 0) continue;// #5887: finished files re-enter when changed since their `.progress`.- const picked = await windows.selectCorpusCandidates(base, txtFiles, entrySet, batchLimit - candidates.length, overBudget);+ const picked = await windows.selectCorpusCandidates(base, txtFiles, entrySet, batchLimit - candidates.length, overBudget,+ (full) => windows.corpusFileParked(full, fingerprint, parkedAt));skip('already_ingested', picked.alreadyIngested);- for (const name of picked.candidates) {- candidates.push({ base, name, location, label: location === 'spool' ? join(CORPUS_SPOOL_SUBDIR, name) : name });- }+ const label = (name: string) => location === 'spool' ? join(CORPUS_SPOOL_SUBDIR, name) : name;+ for (const name of picked.candidates) candidates.push({ base, name, location, label: label(name) });+ for (const name of picked.deferred) deferred.push({ base, name, location, label: label(name) });}+ candidates.push(...deferred.slice(0, Math.max(0, batchLimit - candidates.length)));if (candidates.length === 0) return;// #6091: every corpus file answers to the capture gate, resolved once per@@ -696,9 +703,6 @@ async function runCorpusIngestPass(return;}- // #6785: a capped window re-arms once when this fingerprint changed since its last failure.- const { extractionConfigFingerprint } = await import('./facts/extraction-availability.ts');- const fingerprint = await extractionConfigFingerprint(engine).catch(() => null);const writerRefused = await corpusWriterPreflight(engine, log);const { runFactsPipeline } = await import('./facts/backstop.ts');@@ -727,6 +731,7 @@ async function runCorpusIngestPass(}let abortLoop = false;+ const attempted = { count: 0 };try {// Re-check under the claim: another sweep may have finished this file// between our readdir and our claim (it releases its claim only after@@ -806,10 +811,9 @@ async function runCorpusIngestPass(let r: Awaited<ReturnType<typeof runFactsPipeline>>;if (wbMeta) {const turn = await windows.runCorpusTurn({- full, signal, incarnation: fileSource.incarnation, failures: { fingerprint, now },+ full, signal, incarnation: fileSource.incarnation, failures: { fingerprint, now }, attempted,extract: () => runFactsPipeline(corpusTextForExtraction(name, raw), pipelineCtx),});- if (turn.status !== 'backoff' && turn.status !== 'dead_lettered') windowsLeft -= 1;if (turn.status !== 'complete') {abortLoop = turn.status === 'unavailable';skip(CORPUS_WINDOW_SKIP[turn.status], abortLoop ? candidates.length - i : 1);@@ -823,9 +827,8 @@ async function runCorpusIngestPass(source: { id: fileSource.sourceId, incarnation: fileSource.incarnation },maxWindows: Math.min(windows.CORPUS_WINDOWS_PER_SWEEP, windowsLeft),extract: text => runFactsPipeline(text, pipelineCtx),- failures: { fingerprint, now },+ failures: { fingerprint, now }, attempted,});- windowsLeft -= run.windowsDone;report.corpus_files.push({ file: label, windows_done: run.windowsDone, windows_remaining: run.windowsRemaining });if (run.status !== 'complete') {abortLoop = run.status === 'aborted' || run.status === 'unavailable';@@ -884,6 +887,8 @@ async function runCorpusIngestPass(log(`[sweep] corpus ingest failed for ${name}${typeof code === 'string' ? ` (${code})` : ''}: ${e instanceof Error ? e.message : String(e)}`);}} finally {+ // #6785: every attempted window counts against the total, a thrown one included.+ windowsLeft -= attempted.count;// Success (its .ingested sidecar now stands in) and failure (retry next// sweep) both release the claim.await rm(claimPath, { force: true }).catch(() => {});@@ -1043,18 +1048,35 @@ export interface CorpusDrainOpts {log?: (msg: string) => void;}-/** True when the corpus dir holds a `.txt` with no final `.ingested` sidecar (#6786). Missing dir = false. */+/**+ * True when the corpus dir holds a `.txt` the sweep would extract: not+ * finished by the one classifier (#6786), and not stopped at the failure cap+ * (#6785; a backing-off file still counts). Missing dir = false.+ */async function corpusHasPendingFiles(engine: BrainEngine): Promise<boolean> {let dir = await engine.getConfig('dream.synthesize.session_corpus_dir');if (!dir) {const { configDir } = await import('./config.ts');dir = join(configDir(), 'transcripts', 'corpus');}- const { corpusSidecarState, corpusSpoolDir } = await import('./context/corpus-segments.ts');+ const { CORPUS_FAILURE_SUFFIX, corpusFileAwaitsExtraction, corpusSpoolDir, readCorpusFailure } = await import('./context/corpus-segments.ts');+ const { corpusFailureGate } = await import('./context/corpus-windows.ts');+ const { extractionConfigFingerprint } = await import('./facts/extraction-availability.ts');+ let fingerprint: Promise<string | null> | null = null;+ const stopped = async (full: string): Promise<boolean> => {+ const rec = readCorpusFailure(full);+ if (!rec) return false;+ fingerprint ??= extractionConfigFingerprint(engine).catch(() => null);+ return corpusFailureGate(rec, rec.key, rec.source_incarnation, await fingerprint, Date.now()) === 'dead_lettered';+ };for (const base of [corpusSpoolDir(dir), dir]) {const names = await readdir(base).catch(() => [] as string[]);const present = new Set(names);- if (names.some(n => n.endsWith('.txt') && (!present.has(n + CORPUS_INGESTED_SUFFIX) || corpusSidecarState(join(base, n)) !== 'final'))) return true;+ for (const n of names) {+ if (!n.endsWith('.txt') || !corpusFileAwaitsExtraction(join(base, n), n)) continue;+ if (present.has(n + CORPUS_FAILURE_SUFFIX) && await stopped(join(base, n))) continue;+ return true;+ }}return false;}diff --git a/test/e2e/context-engine-rung3-extraction.test.ts b/test/e2e/context-engine-rung3-extraction.test.tsindex bd8105e9c6..4eac9f0bfa 100644--- a/test/e2e/context-engine-rung3-extraction.test.ts+++ b/test/e2e/context-engine-rung3-extraction.test.ts@@ -12,7 +12,7 @@* Run: DATABASE_URL=... bun test test/e2e/context-engine-rung3-extraction.test.ts*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';@@ -22,6 +22,7 @@ import { detectCapabilities } from '../../src/core/capability.ts';import { createGBrainContextEngine, __resetSdkLoadStateForTests } from '../../src/core/context-engine.ts';import { disposeReflex } from '../../src/core/context/reflex.ts';import { withEnv } from '../helpers/with-env.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';const skip = !hasDatabase();const describeE2E = skip ? describe.skip : describe;@@ -88,4 +89,97 @@ describeE2E('context engine compact() rung 3 — DB-plane extraction model (#573);expect(rows[0]?.n).toBeGreaterThan(0);}, 60_000);+ /** A Postgres GBRAIN_HOME + workspace + one-turn OpenClaw session (the fixture above). */+ function rung3Fixture(session: string): { home: string; workspace: string; sessionFile: string } {+ const home = mkdtempSync(join(tmpdir(), 'gb-ce-rung3-'));+ const workspace = mkdtempSync(join(tmpdir(), 'gb-ce-rung3-ws-'));+ dirs.push(home, workspace);+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: process.env.DATABASE_URL }));+ mkdirSync(join(workspace, 'memory'), { recursive: true });+ writeFileSync(join(workspace, 'memory', 'heartbeat-state.json'), '{}');+ const sessionFile = join(home, `${session}.jsonl`);+ const line = (o: unknown) => JSON.stringify(o);+ writeFileSync(sessionFile, [+ line({ type: 'session', id: session, cwd: '/w', timestamp: '2026-08-01T10:00:00Z' }),+ line({ type: 'compaction', timestamp: '2026-08-01T10:00:01Z' }),+ line({ type: 'message', timestamp: '2026-08-01T10:00:02Z', message: { role: 'user', content: [{ type: 'text', text: 'We chose a local extraction model for the synthetic project.' }] } }),+ ].join('\n') + '\n');+ return { home, workspace, sessionFile };+ }++ function segmentFiles(root: string): string[] {+ const out: string[] = [];+ for (const e of readdirSync(root, { withFileTypes: true, recursive: true })) {+ if (e.isFile() && e.name.endsWith('.txt')) out.push(join(e.parentPath, e.name));+ }+ return out;+ }++ async function compactOnce(f: ReturnType<typeof rung3Fixture>, session: string): Promise<{ status: string; reason?: string } | undefined> {+ return withEnv({ ...noProviderKeys, GBRAIN_HOME: f.home }, async () => {+ __resetSdkLoadStateForTests();+ const ce = createGBrainContextEngine({ workspaceDir: f.workspace });+ const result = await ce.compact({ sessionId: session, sessionFile: f.sessionFile });+ return ((result.result ?? {}) as { gbrain_checkpoint?: { status: string; reason?: string } }).gbrain_checkpoint;+ });+ }++ test('#6785: a segment with a failing window is left to the sweep: no model call, no sidecar', async () => {+ const f = rung3Fixture('oc-rung3-failing');+ await getEngine().setConfig('facts.extraction_model', 'ollama:qwen2.5-coder:14b');+ let calls = 0;+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ calls++;+ throw Object.assign(new Error('provider down'), { code: 'provider_error' });+ });+ // The first compact freezes the session's source; the second spools the segment the later ones reuse.+ await compactOnce(f, 'oc-rung3-failing');+ await compactOnce(f, 'oc-rung3-failing');+ expect(calls).toBe(2);+ const segments = segmentFiles(f.home);+ expect(segments.length).toBeGreaterThan(0);+ for (const segment of segments) {+ expect(existsSync(segment + '.ingested')).toBe(false);+ writeFileSync(segment + '.failures.json', JSON.stringify({+ version: 1, key: 'k@0', source_incarnation: null, count: 2, first_at: Date.now(), last_at: Date.now(),+ last_code: 'provider_error', fingerprint: null, rearmed: false,+ }) + '\n');+ }++ const r2 = await compactOnce(f, 'oc-rung3-failing');+ expect(r2).toMatchObject({ status: 'banked', reason: 'corpus_window_backoff' });+ expect(calls).toBe(2);+ expect(segmentFiles(f.home)).toEqual(segments);+ expect(segments.some((p) => existsSync(p + '.ingested'))).toBe(false);+ }, 60_000);++ test('#6785: a claimed, not activated worktree is held before any model call', async () => {+ const f = rung3Fixture('oc-rung3-claimed');+ await getEngine().setConfig('facts.extraction_model', 'ollama:qwen2.5-coder:14b');+ let calls = 0;+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ calls++;+ return { text: '{"facts":[]}', blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'ollama:qwen2.5-coder:14b', providerId: 'ollama' };+ });+ const root = mkdtempSync(join(tmpdir(), 'gb-ce-rung3-brain-'));+ dirs.push(root);+ // setupDB does not truncate the persistence bindings: release the claim so no later file inherits it.+ const release = () => getEngine().executeRaw(`DELETE FROM persistence_source_bindings WHERE source_id = 'default';+ DELETE FROM persistence_host_bindings h WHERE NOT EXISTS (SELECT 1 FROM persistence_source_bindings s WHERE s.worktree_id = h.worktree_id);+ DELETE FROM persistence_worktrees w WHERE NOT EXISTS (SELECT 1 FROM persistence_source_bindings s WHERE s.worktree_id = w.id);+ UPDATE sources SET local_path = NULL WHERE id = 'default'`);+ await release();+ try {+ await getEngine().executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [root]);+ await claimWorktree(getEngine(), 'default', root);++ expect(await compactOnce(f, 'oc-rung3-claimed')).toMatchObject({ status: 'banked', reason: 'writer_coordinator_required' });+ expect(calls).toBe(0);+ expect(segmentFiles(f.home).some((p) => existsSync(p + '.ingested'))).toBe(false);+ } finally {+ await release();+ }+ }, 60_000);});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 63bd703e68..fa820f877b 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6158,7 +6158,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/sweep-corpus-failure-cap-6785.test.ts b/test/sweep-corpus-failure-cap-6785.test.tsindex fb20d06e12..5d7c83ca82 100644--- a/test/sweep-corpus-failure-cap-6785.test.ts+++ b/test/sweep-corpus-failure-cap-6785.test.ts@@ -15,7 +15,11 @@* grows; one extraction-config change re-arms it once; the operator retry* (`gbrain sweep --retry-failed --apply`, named as doctor's paid fix)* extracts it and its facts land; the HTTP drain logs skip reasons and- * thrown errors instead of discarding them.+ * thrown errors instead of discarding them. Stopped files never starve a+ * healthy one; a thrown window counts against the sweep total; a paid+ * window that cannot commit counts as a failure and a refused call does not;+ * the writeback harvest honours the cap; the drain and the doctor backlog+ * classify files like the sweep.** The preflight, drain and cost assertions import only modules that predate* #6785 and fail on the old tree. Hermetic in-memory PGLite + transport stubs.@@ -29,10 +33,12 @@ import { armCorpusDrain, CORPUS_INGESTED_SUFFIX, runMaintenanceSweep, type Sweepimport { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway, 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 { appendSegmentLedger, ensureCorpusSpoolDir, segmentFileName, sessionCorpusFileName, writeSegment } from '../src/core/context/corpus-segments.ts';+import { appendSegmentLedger, ensureCorpusSpoolDir, segmentFileName, sessionCorpusFileName, wbFileName, writeSegment } from '../src/core/context/corpus-segments.ts';import { __drainCheckpointHarvestForTests, __resetCheckpointHarvestForTests, HARVEST_RECEIPT_SUFFIX, scheduleCheckpointHarvest } from '../src/core/context/checkpoint-harvest.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withAIInvocationGuard } from '../src/core/ai/invocation-guard.ts';+import { parseCorpusTurns } from '../src/core/context/corpus-turns.ts';import { withEnv } from './helpers/with-env.ts';const KEYED: CapabilityReport = {@@ -220,12 +226,17 @@ describe('#6785: a window that keeps failing after its model call is capped', ()await engine.disconnect();});- const at = async (nowMs: number): Promise<{ paid: boolean; report: SweepReport }> => {+ const at = async (nowMs: number, extra: { batchLimit?: number; env?: Record<string, string> } = {}): Promise<{ paid: boolean; calls: number; report: SweepReport }> => {const before = chatCalls;- const report = await withEnv({ GBRAIN_HOME: home }, () =>- runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 120_000, now: () => nowMs, log: (m) => logs.push(m) }));- return { paid: chatCalls > before, report };+ const report = await withEnv({ GBRAIN_HOME: home, ...extra.env }, () =>+ runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 120_000, now: () => nowMs, log: (m) => logs.push(m),+ ...(extra.batchLimit ? { batchLimit: extra.batchLimit } : {}) }));+ return { paid: chatCalls > before, calls: chatCalls - before, report };};+ /** A failure record that stops the file's window (count at the cap, no fingerprint to re-arm on). */+ const stopped = (file: string, key = 'k@0', incarnation: string | null = null): void => writeFileSync(file + '.failures.json', JSON.stringify({+ version: 1, key, source_incarnation: incarnation, count: 5, first_at: 0, last_at: 0, last_code: 'provider_error', fingerprint: null, rearmed: false,+ }) + '\n');/** Five failed attempts on the schedule: now, the next sweep, +10, +20, +40 minutes. */async function capped(file: string, t0: number): Promise<void> {@@ -339,4 +350,115 @@ describe('#6785: a window that keeps failing after its model call is capped', ()expect(corpusFailureGate({ ...record, rearmed: true }, 'abc@0', 'inc-a', 'f2', 1e12)).toBe('dead_lettered');expect(corpusFailureGate({ ...record, fingerprint: null }, 'abc@0', 'inc-a', 'f2', 1e12)).toBe('dead_lettered');});+ test('stopped files never take every batch slot: a healthy file behind them is still extracted', async () => {+ failing = false;+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation::text AS incarnation FROM sources WHERE id = 'default'`);+ for (const n of ['a-stopped-1.txt', 'a-stopped-2.txt', 'a-stopped-3.txt']) {+ writeFileSync(join(dir, n), turnsText(2));+ stopped(join(dir, n), `${parseCorpusTurns(turnsText(2))[0].sha256}@0`, incarnation);+ }+ const healthy = join(dir, 'z-healthy.txt');+ writeFileSync(healthy, turnsText(2));+ const r = await at(Date.UTC(2026, 9, 15, 12), { batchLimit: 2 });+ expect(r.report.corpusIngested).toBe(1);+ expect(r.calls).toBe(1);+ expect(skipped(r.report, 'corpus_window_dead_lettered')).toBe(1);+ expect(existsSync(healthy + CORPUS_INGESTED_SUFFIX)).toBe(true);+ expect(existsSync(join(dir, 'a-stopped-1.txt') + CORPUS_INGESTED_SUFFIX)).toBe(false);+ });++ test('a thrown window counts against the sweep total: GBRAIN_CORPUS_WINDOWS_PER_SWEEP=1 pays once', async () => {+ for (const n of ['fail-1.txt', 'fail-2.txt']) writeFileSync(join(dir, n), turnsText(2));+ const spool = ensureCorpusSpoolDir(dir);+ await engine.setConfig('memory.auto_writeback', 'salient');+ try {+ for (const h of ['c', 'd']) writeFileSync(join(spool, wbFileName(`sess-${h}`, h.repeat(24), 'default')), '[user]\nWB I keep a written log of every decision I make.\n');+ const r = await at(Date.UTC(2026, 9, 15, 12), { env: { GBRAIN_CORPUS_WINDOWS_PER_SWEEP: '1' } });+ expect(r.calls).toBe(1);+ expect(skipped(r.report, 'corpus_window_cap')).toBeGreaterThan(0);+ } finally {+ await engine.unsetConfig('memory.auto_writeback');+ }+ });++ test('a paid window whose progress cannot commit counts as a failure', async () => {+ failing = false;+ const file = join(dir, 'lock-held.txt');+ writeFileSync(file, turnsText(1));+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ chatCalls++;+ writeFileSync(file + '.progress.lock', `${process.pid}\n`);+ return { text: fact(null), blocks: [], stopReason: 'end', usage, model: 'anthropic:test-stub', providerId: 'anthropic' };+ });+ const r = await at(Date.UTC(2026, 9, 15, 12));+ rmSync(file + '.progress.lock', { force: true });+ expect(r.paid).toBe(true);+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);+ const record = JSON.parse(readFileSync(file + '.failures.json', 'utf8'));+ expect([record.count, record.last_code]).toEqual([1, 'corpus_progress_contended']);+ });++ test('a call the spend guard refuses before the provider is not counted', async () => {+ const file = join(dir, 'refused.txt');+ writeFileSync(file, turnsText(2));+ const r = await withAIInvocationGuard(async () => { throw Object.assign(new Error('spend cap reached'), { code: 'budget_exceeded' }); },+ () => at(Date.UTC(2026, 9, 15, 12)));+ expect(r.calls).toBe(0);+ expect(existsSync(file + '.failures.json')).toBe(false);+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);+ });++ test('the writeback harvest honours the cap: a stopped turn file is not paid for', async () => {+ failing = false;+ const spool = ensureCorpusSpoolDir(dir);+ const name = wbFileName('sess-wb-stopped', 'e'.repeat(24), 'default');+ const wb = join(spool, name);+ writeFileSync(wb, '[user]\nWB I keep a written log of every decision I make.\n');+ stopped(wb, 'turn');+ await engine.setConfig('memory.auto_writeback', 'salient');+ const before = chatCalls;+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (let i = 0; i < 3; i++) {+ expect(scheduleCheckpointHarvest({ engine, sourceId: 'default', sessionId: 'sess-wb-stopped', corpusDir: spool, file: name, lane: 'writeback', capabilities: KEYED }).status).toBe('scheduled');+ await __drainCheckpointHarvestForTests();+ }+ });+ } finally {+ await engine.unsetConfig('memory.auto_writeback');+ }+ expect(chatCalls).toBe(before);+ expect(existsSync(wb + CORPUS_INGESTED_SUFFIX)).toBe(false);+ expect(JSON.parse(readFileSync(wb + '.failures.json', 'utf8')).count).toBe(5);+ });++ test('the drain and the doctor backlog use the completion classifier: a rewritten finished file is pending, a stopped one does not wake the drain', async () => {+ failing = false;+ const file = join(dir, 'rewritten.txt');+ writeFileSync(file, turnsText(2));+ expect((await at(Date.UTC(2026, 9, 15, 12))).report.corpusIngested).toBe(1);+ const { corpusBacklog } = await import('../src/core/context/corpus-segments.ts');+ expect(corpusBacklog(dir, 30 * 1440 * MIN).pending).toBe(0);+ let drained = 0;+ const drain = () => armCorpusDrain(engine, { env: {}, setIntervalFn: () => 0, clearIntervalFn: () => {},+ sweep: async () => { drained++; return { skipped: [] }; }, log: () => {} } as never)!;+ const d1 = drain();+ await withEnv({ GBRAIN_HOME: home }, () => d1.tick());+ d1.cancel();+ expect(drained).toBe(0);++ writeFileSync(file, turnsText(3));+ expect(corpusBacklog(dir, 30 * 1440 * MIN).pending).toBe(1);+ const d2 = drain();+ await withEnv({ GBRAIN_HOME: home }, () => d2.tick());+ d2.cancel();+ expect(drained).toBe(1);++ rmSync(file + CORPUS_INGESTED_SUFFIX);+ stopped(file);+ const d3 = drain();+ await withEnv({ GBRAIN_HOME: home }, () => d3.tick());+ d3.cancel();+ expect(drained).toBe(1);+ });});