Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sweep): count paid-then-refused and rung-3 failures; never count unpaid replays (#6785)
garrytan2d2859a6c10a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 522cbfa1f4..6a0ba5deed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,13 +31,13 @@ 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, 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/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; an extraction refused by the spend guard before any chat call was admitted, or replayed without a model call, does not count. 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/context-engine.ts`: the OpenClaw `compact()` inline harvest on Postgres (rung 3) runs the same preflight, records a failed paid attempt where the sweep's cap reads it and then leaves that segment 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), `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.+- 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, a chat call followed by a refused one, an unpaid replay, the writeback harvest cap, and the drain and backlog classifier with a stale record) 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/context-engine.ts b/src/core/context-engine.tsindex 5de57d7ea6..19e91e9d5c 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -928,6 +928,19 @@ async function rung3SegmentHold(fullPath: string, name: string): Promise<stringreturn failing.count >= segs.CORPUS_WINDOW_FAILURE_CAP ? 'corpus_window_dead_lettered' : 'corpus_window_backoff';}+/**+ * Rung 3, #6785: a failure after a paid call is recorded at the segment's+ * frontier window, the record the sweep's cap reads, so every later compact+ * leaves the segment to the sweep (rung3SegmentHold).+ */+async function rung3Counted<T>(engine: BrainEngine, fullPath: string, name: string, incarnation: string | null, signal: AbortSignal, run: () => Promise<T>): Promise<T> {+ const windows = await import('./context/corpus-windows.ts');+ const { extractionConfigFingerprint } = await import('./facts/extraction-availability.ts');+ const key = (await windows.corpusFrontierKey(fullPath, name)) ?? 'unreadable@0';+ const fingerprint = await extractionConfigFingerprint(engine).catch(() => null);+ return (await windows.extractUnderFailureCount({ full: fullPath, record: null, key, incarnation, fingerprint, nowMs: Date.now, signal }, run)).value;+}+/** 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 {@@ -1245,7 +1258,7 @@ export function createGBrainContextEngine(ctx: {const deadlinePoll = setInterval(() => { if (deadlineHit()) abort.abort(); }, 250);let r: Awaited<ReturnType<typeof runFactsPipeline>>;try {- r = await runFactsPipeline(rendered.text, {+ r = await rung3Counted(pg, fullPath, segName(w.hash), fileSource.incarnation, abort.signal, () => runFactsPipeline(rendered.text, {engine: pg,sourceId,sessionId,@@ -1253,7 +1266,7 @@ export function createGBrainContextEngine(ctx: {mode: 'inline',remote: false,abortSignal: abort.signal,- });+ }));} finally {clearTimeout(timer);clearInterval(deadlinePoll);diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.tsindex 3fc980ec39..f01c95e1c4 100644--- a/src/core/context/corpus-windows.ts+++ b/src/core/context/corpus-windows.ts@@ -32,11 +32,11 @@ 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, withAIInvocationGuard } from '../ai/invocation-guard.ts';+import { 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,- corpusFileCompletion, corpusFileFinished, parseCorpusProgress, readCorpusFailure, type CorpusFailureRecord,+ corpusFileCompletion, corpusFileFinished, parseCorpusProgress, parseWbFileName, readCorpusFailure, type CorpusFailureRecord,} from './corpus-segments.ts';export { parseCorpusTurns, type CorpusTurn };@@ -444,35 +444,46 @@ export function corpusFileParked(full: string, fingerprint: string | null, nowMsreturn !!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;+/**+ * The key of the window the next run of `full` starts at (the frontier a+ * failure record names), or null when the file or its progress is+ * unreadable. A writeback turn file's key is always CORPUS_TURN_FAILURE_KEY.+ */+export async function corpusFrontierKey(full: string, name: string): Promise<string | null> {+ if (parseWbFileName(name)) return CORPUS_TURN_FAILURE_KEY;+ try {+ const turns = parseCorpusTurns(await readFile(full, 'utf-8'));+ return windowKey(turns, resumePoint(turns, await readCorpusProgress(full)));+ } catch {+ return null;}- 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.+ * rethrow, whatever ended it (a later call the spend guard refused+ * included). A throw before any admitted chat call (a refused first call+ * included), an abort, or capture switched off mid-call (the next sweep+ * retires the file) costs nothing to retry and is not counted. `paid` says+ * whether a chat call was admitted, for a caller that must count a failure+ * after the extraction returned.*/export async function extractUnderFailureCount<T>(failure: { full: string; record: CorpusFailureRecord | null; key: string; incarnation: string | null; fingerprint: string | null; nowMs: () => number; signal?: AbortSignal },extract: () => Promise<T>,-): Promise<T> {- let chatCalled = false;+): Promise<{ value: T; paid: boolean }> {+ let paid = false;try {// Inherit: an outer guard admits first, so this one only sees admitted calls.- return await withAIInvocationGuard(async (call) => {- if (call.kind === 'chat') chatCalled = true;+ const value = await withAIInvocationGuard(async (call) => {+ if (call.kind === 'chat') paid = true;return { settle: async () => {} };}, extract, { inherit: true });+ return { value, paid };} catch (e) {- const counts = chatCalled && !failure.signal?.aborted && !(e instanceof Error && e.name === 'AbortError')- && !isPolicyRefusal(e) && (e as { code?: unknown } | null)?.code !== 'ambient_capture_off';+ const counts = paid && !failure.signal?.aborted && !(e instanceof Error && e.name === 'AbortError')+ && (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(() => {});}@@ -546,7 +557,7 @@ export async function runCorpusTurn(opts: {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(+ const { value: result } = await extractUnderFailureCount({ full: opts.full, record, key: CORPUS_TURN_FAILURE_KEY, incarnation: opts.incarnation, fingerprint, nowMs: clock, signal: opts.signal },opts.extract,);@@ -629,6 +640,7 @@ export async function runCorpusWindows(opts: {const win = windows[w];const key = windowKey(turns, cursor);let r: PipelineResult | null = null;+ let paid = false;if (win.text) {if (done >= opts.maxWindows) { status = 'partial'; break; }if (opts.overBudget() || signal.aborted) { status = 'aborted'; break; }@@ -636,7 +648,9 @@ export async function runCorpusWindows(opts: {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));+ const attempt = await extractUnderFailureCount({ full, record: failure, key, incarnation, fingerprint, nowMs: clock, signal }, () => opts.extract(text));+ r = attempt.value;+ paid = attempt.paid;if (r.skipped_reason && CORPUS_NON_TERMINAL_SKIPS.includes(r.skipped_reason)) { status = 'unavailable'; break; }}if (signal.aborted) { status = 'aborted'; break; }@@ -663,7 +677,7 @@ export async function runCorpusWindows(opts: {};});// #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+ const countUncommitted = (e: unknown) => paid? recordCorpusFailure(full, failure, key, incarnation, fingerprint, clock(), e).catch(() => failure): Promise.resolve(failure);let next: CorpusProgress | null;@@ -679,7 +693,8 @@ export async function runCorpusWindows(opts: {break;}state = next;- if (failure?.key === key) {+ // Any record left is this window's or stale (the frontier moved past it).+ if (failure) {await clearCorpusFailure(full).catch(() => {});failure = null;}diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex dcc5c9059c..0c84c2733d 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -1051,7 +1051,8 @@ export interface CorpusDrainOpts {/*** 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.+ * at the window it starts at now (#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');@@ -1060,12 +1061,13 @@ async function corpusHasPendingFiles(engine: BrainEngine): Promise<boolean> {dir = join(configDir(), 'transcripts', 'corpus');}const { CORPUS_FAILURE_SUFFIX, corpusFileAwaitsExtraction, corpusSpoolDir, readCorpusFailure } = await import('./context/corpus-segments.ts');- const { corpusFailureGate } = await import('./context/corpus-windows.ts');+ const { corpusFailureGate, corpusFrontierKey } = 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 stopped = async (full: string, name: string): Promise<boolean> => {const rec = readCorpusFailure(full);- if (!rec) return false;+ // A record for a window the file no longer starts at (rewritten) is stale.+ if (!rec || (await corpusFrontierKey(full, name)) !== rec.key) return false;fingerprint ??= extractionConfigFingerprint(engine).catch(() => null);return corpusFailureGate(rec, rec.key, rec.source_incarnation, await fingerprint, Date.now()) === 'dead_lettered';};@@ -1074,7 +1076,7 @@ async function corpusHasPendingFiles(engine: BrainEngine): Promise<boolean> {const present = new Set(names);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;+ if (present.has(n + CORPUS_FAILURE_SUFFIX) && await stopped(join(base, n), n)) continue;return true;}}diff --git a/test/e2e/context-engine-rung3-extraction.test.ts b/test/e2e/context-engine-rung3-extraction.test.tsindex 4eac9f0bfa..9dca81d99b 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 { existsSync, mkdtempSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';@@ -125,7 +125,7 @@ describeE2E('context engine compact() rung 3 — DB-plane extraction model (#573});}- test('#6785: a segment with a failing window is left to the sweep: no model call, no sidecar', async () => {+ test('#6785: a failed inline harvest is recorded once, and later compacts leave the segment to the sweep', async () => {const f = rung3Fixture('oc-rung3-failing');await getEngine().setConfig('facts.extraction_model', 'ollama:qwen2.5-coder:14b');let calls = 0;@@ -133,25 +133,17 @@ describeE2E('context engine compact() rung 3 — DB-plane extraction model (#573calls++;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 results = [];+ for (let i = 0; i < 6; i++) results.push(await compactOnce(f, 'oc-rung3-failing'));const segments = segmentFiles(f.home);expect(segments.length).toBeGreaterThan(0);+ // One paid attempt per segment file, each recorded; every later compact holds.+ expect(calls).toBe(segments.length);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');+ expect(JSON.parse(readFileSync(segment + '.failures.json', 'utf8')).count).toBe(1);}-- 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);+ expect(results.at(-1)).toMatchObject({ status: 'banked', reason: 'corpus_window_backoff' });}, 60_000);test('#6785: a claimed, not activated worktree is held before any model call', async () => {diff --git a/test/sweep-corpus-failure-cap-6785.test.ts b/test/sweep-corpus-failure-cap-6785.test.tsindex 5d7c83ca82..ebfe6b3f9c 100644--- a/test/sweep-corpus-failure-cap-6785.test.ts+++ b/test/sweep-corpus-failure-cap-6785.test.ts@@ -19,7 +19,8 @@* 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.+ * classify files like the sweep and ignore a stale record; a chat call+ * followed by a refused one still counts, an unpaid replay never does.** The preflight, drain and cost assertions import only modules that predate* #6785 and fail on the old tree. Hermetic in-memory PGLite + transport stubs.@@ -455,10 +456,61 @@ describe('#6785: a window that keeps failing after its model call is capped', ()expect(drained).toBe(1);rmSync(file + CORPUS_INGESTED_SUFFIX);- stopped(file);+ const { corpusFrontierKey } = await import('../src/core/context/corpus-windows.ts');+ stopped(file, (await corpusFrontierKey(file, 'rewritten.txt'))!);const d3 = drain();await withEnv({ GBRAIN_HOME: home }, () => d3.tick());d3.cancel();expect(drained).toBe(1);++ // The session is rewritten past the stopped window: that record no longer applies.+ writeFileSync(file, turnsText(2, 10));+ const d4 = drain();+ await withEnv({ GBRAIN_HOME: home }, () => d4.tick());+ d4.cancel();+ expect(drained).toBe(2);+ });++ test('a failure after an admitted chat call counts even when a later call is refused; a result with no chat call does not', async () => {+ const { extractUnderFailureCount } = await import('../src/core/context/corpus-windows.ts');+ const { invokeAI } = await import('../src/core/ai/invocation-guard.ts');+ const full = join(dir, 'chat-then-refused.txt');+ const failure = { full, record: null, key: 'k@0', incarnation: null, fingerprint: null, nowMs: () => 1 };+ const refuseEmbeddings = async (call: { kind: string }) => {+ if (call.kind === 'embedding') throw Object.assign(new Error('embedding budget refused'), { code: 'budget_exceeded' });+ return { settle: async () => {} };+ };+ const chatThenEmbed = async () => {+ await invokeAI({ operation: 'extract', model: 'anthropic:test', kind: 'chat' }, async () => 'facts', () => null);+ try {+ await invokeAI({ operation: 'embed', model: 'openai:test', kind: 'embedding' }, async () => [0], () => null);+ } catch (e) {+ throw Object.assign(new Error('[facts-extract] wrapped'), { cause: e });+ }+ };+ await expect(withAIInvocationGuard(refuseEmbeddings, () => extractUnderFailureCount(failure, chatThenEmbed))).rejects.toThrow('wrapped');+ expect(JSON.parse(readFileSync(full + '.failures.json', 'utf8')).count).toBe(1);++ const replay = join(dir, 'replayed.txt');+ const unpaid = await extractUnderFailureCount({ ...failure, full: replay }, async () => 'cached receipt');+ expect(unpaid).toEqual({ value: 'cached receipt', paid: false });+ });++ test('a replayed window (no model call) whose progress cannot commit is not counted', async () => {+ const { corpusFileStat, runCorpusWindows } = await import('../src/core/context/corpus-windows.ts');+ const { statSync } = await import('node:fs');+ const file = join(dir, 'replay-contended.txt');+ writeFileSync(file, turnsText(1));+ const run = await runCorpusWindows({+ full: file, raw: readFileSync(file, 'utf8'), fileStat: corpusFileStat(statSync(file)), maxWindows: 8,+ overBudget: () => false, signal: new AbortController().signal,+ extract: async () => {+ writeFileSync(file + '.progress.lock', `${process.pid}\n`);+ return { inserted: 0, duplicate: 1, superseded: 0, fact_ids: [], entity_slugs: [] };+ },+ });+ rmSync(file + '.progress.lock', { force: true });+ expect(run.status).toBe('contended');+ expect(existsSync(file + '.failures.json')).toBe(false);});});