Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(hook): keep un-extracted corpus turns up to 3x retention; doctor names the backlog (E-N1)
time-attackbb73d4f1d0ae
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.tsindex a53f4e2a51..97db88251d 100644--- a/src/commands/doctor/checks/memory-writeback.ts+++ b/src/commands/doctor/checks/memory-writeback.ts@@ -21,6 +21,7 @@*/import { existsSync, readFileSync } from 'node:fs';+import { isAbsolute, join } from 'node:path';import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import type { Effect } from '../../../core/agent-output.ts';@@ -37,6 +38,7 @@ import { classifyBrainAudience } from '../../../core/facts/writeback-audience.tsimport { readVerbUsage } from '../../../core/verbs/usage-log.ts';import { readClientOpUsage } from '../../../core/mcp-usage.ts';import { readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';+import { CORPUS_UNINGESTED_RETENTION_FACTOR, corpusBacklog } from '../../../core/context/corpus-segments.ts';import { readHarnessReceiptState } from '../../../core/bootstrap/format.ts';import { mutedFirstRunDecisionsNotice } from '../../../core/onboard/mcp-onboarding.ts';import {@@ -101,6 +103,29 @@ async function remoteFactReaders(engine: BrainEngine): Promise<string[]> {return readers;}+const DAY_MS = 24 * 60 * 60 * 1000;++/**+ * E-N1: corpus turn files nothing has extracted yet. Retention keeps them up+ * to CORPUS_UNINGESTED_RETENTION_FACTOR x `corpus_retention_days`; once one is+ * past plain retention it is on its way to deletion, so the check says so.+ * Records `details.corpus_backlog`; returns the warning text or null.+ */+async function corpusBacklogProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {+ const synth = fileCfg?.dream?.synthesize as Record<string, unknown> | undefined;+ const configured = (await engine.getConfig('dream.synthesize.session_corpus_dir').catch(() => null)) ?? synth?.session_corpus_dir;+ const dir = typeof configured === 'string' && isAbsolute(configured) ? configured : join(resolveGbrainHome(), 'transcripts', 'corpus');+ const days = typeof synth?.corpus_retention_days === 'number' && synth.corpus_retention_days > 0 ? synth.corpus_retention_days : 30;+ const now = Date.now();+ const backlog = corpusBacklog(dir, days * DAY_MS, now);+ const oldestDays = backlog.oldestPendingMtimeMs === null ? null : Math.floor((now - backlog.oldestPendingMtimeMs) / DAY_MS);+ const purgeDays = days * CORPUS_UNINGESTED_RETENTION_FACTOR;+ details.corpus_backlog = { pending: backlog.pending, oldest_pending_days: oldestDays, past_retention: backlog.pastRetention, retention_days: days, deleted_after_days: purgeDays };+ if (backlog.pastRetention === 0) return null;+ return `${backlog.pastRetention} of ${backlog.pending} captured session file(s) are older than the ${days}-day corpus retention and were never extracted `+ + `(oldest ${oldestDays}d); they are deleted at ${purgeDays}d. Extract them now: gbrain sweep --once --budget-ms 600000`;+}+export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Promise<Check> {try {const fileCfg = loadConfig();@@ -151,6 +176,8 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Prodetails.near_duplicates_shadow_7d = dedup.reduce((n, e) => n + (e.near_duplicate ?? 0), 0);} catch { /* heartbeat unreadable — counters stay absent */ }+ const corpusProblem = await corpusBacklogProblem(engine, fileCfg, details).catch(() => null);+// Plane comparison (the dual-write design's promised surfacing): the DB// row is authoritative at runtime; a disagreeing file mirror means a// failed dual-write, a foreign writer, or another machine's `config set`@@ -210,6 +237,7 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro}const problems: string[] = [];+ if (corpusProblem) problems.push(corpusProblem);if (!wb.ttl_valid) {problems.push(`memory.auto_writeback_transient_ttl is invalid — using '${wb.transient_ttl}'`);}diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 6d4e11c7b7..aebf339fd7 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -69,6 +69,7 @@ import {bankWritebackTurn,decideCorpusMode,gcCorpusArtifacts,+ gcCorpusTurnFiles,CORPUS_PROGRESS_SUFFIX,CORPUS_PROGRESS_LOCK_SUFFIX,HARVEST_RECEIPT_SUFFIX,@@ -1817,7 +1818,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {}}const retentionMs = corpusRetentionDays(cfg) * 24 * 60 * 60 * 1000;- gcOldFiles(dir, retentionMs); // [G15]+ gcCorpusTurnFiles(dir, retentionMs); // [G15]; un-ingested turns kept longer (E-N1)gcCorpusArtifacts(dir, retentionMs, [CORPUS_INGESTED_SUFFIX,CORPUS_CLAIM_SUFFIX,diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.tsindex c09a029bfd..be503a9db5 100644--- a/src/core/context/corpus-segments.ts+++ b/src/core/context/corpus-segments.ts@@ -486,6 +486,75 @@ export async function decideCorpusMode(return { mode: 'full_fallback', turns, startTurnIndex: 0 };}+/**+ * E-N1: a corpus `.txt` with no `.ingested` sidecar holds turns nothing has+ * extracted yet (an HTTP serve with no sweep, a refused harvest). Retention+ * removes it only at this multiple of the configured retention, and doctor+ * `memory_writeback` warns while it waits.+ */+export const CORPUS_UNINGESTED_RETENTION_FACTOR = 3;+/** Completion sidecar suffix (sweep.ts CORPUS_INGESTED_SUFFIX; duplicated to stay engine-free). */+const INGESTED_SUFFIX = '.ingested';++export interface CorpusBacklog {+ /** `.txt` files with no `.ingested` sidecar. */+ pending: number;+ /** mtime of the oldest pending file, or null with none pending. */+ oldestPendingMtimeMs: number | null;+ /** Pending files older than retention: kept only by the un-ingested rule, deleted at the ceiling. */+ pastRetention: number;+}++/** Count corpus turn files still waiting for extraction. Missing dir = empty backlog; never throws. */+export function corpusBacklog(dir: string, retentionMs: number, now = Date.now()): CorpusBacklog {+ const backlog: CorpusBacklog = { pending: 0, oldestPendingMtimeMs: null, pastRetention: 0 };+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch {+ return backlog;+ }+ const present = new Set(names);+ for (const name of names) {+ if (!name.endsWith('.txt') || present.has(name + INGESTED_SUFFIX)) continue;+ let mtimeMs: number;+ try {+ mtimeMs = statSync(join(dir, name)).mtimeMs;+ } catch {+ continue;+ }+ backlog.pending++;+ if (backlog.oldestPendingMtimeMs === null || mtimeMs < backlog.oldestPendingMtimeMs) backlog.oldestPendingMtimeMs = mtimeMs;+ if (mtimeMs < now - retentionMs) backlog.pastRetention++;+ }+ return backlog;+}++/**+ * Retention GC for corpus turn files: an extracted file (`.ingested`+ * sidecar present) goes at `retentionMs`; one nothing has extracted stays+ * until `CORPUS_UNINGESTED_RETENTION_FACTOR` x `retentionMs` (E-N1).+ * Best-effort per file; never throws.+ */+export function gcCorpusTurnFiles(dir: string, retentionMs: number, now = Date.now()): void {+ try {+ const names = readdirSync(dir);+ const present = new Set(names);+ for (const name of names) {+ if (!name.endsWith('.txt')) continue;+ const ageLimit = present.has(name + INGESTED_SUFFIX) ? retentionMs : retentionMs * CORPUS_UNINGESTED_RETENTION_FACTOR;+ const p = join(dir, name);+ try {+ if (statSync(p).mtimeMs < now - ageLimit) rmSync(p, { force: true });+ } catch {+ /* per-file best effort */+ }+ }+ } catch {+ /* GC never breaks the caller */+ }+}+/*** GC companion for the corpus dir (extends the hook's `.txt`-only GC): remove* ledgers past the retention window, ORPHANED sidecars whose base `.txt` isdiff --git a/test/corpus-retention-uningested.serial.test.ts b/test/corpus-retention-uningested.serial.test.tsnew file mode 100644index 0000000000..14de74f3d1--- /dev/null+++ b/test/corpus-retention-uningested.serial.test.ts@@ -0,0 +1,112 @@+/**+ * E-N1 (D16): corpus retention never silently deletes turns nothing has+ * extracted. Before the fix the session-end GC removed every corpus `.txt`+ * older than `corpus_retention_days` (default 30) with or without an+ * `.ingested` sidecar, so an HTTP-served brain with no corpus drain lost its+ * banked turns after 30 days. Now an un-ingested file stays until 3x+ * retention and doctor `memory_writeback` warns while it waits.+ *+ * Imports only modules that exist on the pre-fix tree, so it fails there.+ * SERIAL: mutates GBRAIN_HOME.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runHook } from '../src/commands/hook.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { buildMemoryWritebackCheck } from '../src/commands/doctor/checks/memory-writeback.ts';++const DAY = 24 * 60 * 60 * 1000;+let tmp: string;+let savedHome: string | undefined;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-corpus-ret-'));+ savedHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = tmp;+ mkdirSync(join(tmp, 'ws'), { recursive: true });+});+afterEach(() => {+ if (savedHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = savedHome;+ rmSync(tmp, { recursive: true, force: true });+});++const corpus = () => join(tmp, '.gbrain', 'transcripts', 'corpus');++function aged(name: string, ageDays: number, ingested: boolean): string {+ mkdirSync(corpus(), { recursive: true });+ const p = join(corpus(), name);+ writeFileSync(p, '[user]\nan old turn\n');+ if (ingested) writeFileSync(p + '.ingested', '{}\n');+ const t = new Date(Date.now() - ageDays * DAY);+ utimesSync(p, t, t);+ return p;+}++async function sessionEnd(): Promise<void> {+ const projects = join(tmp, 'claude', 'projects', 'p1');+ mkdirSync(projects, { recursive: true });+ const transcript = join(projects, 's.jsonl');+ writeFileSync(transcript, [+ JSON.stringify({ type: 'user', isSidechain: false, message: { role: 'user', content: 'a new question' } }),+ JSON.stringify({ type: 'assistant', isSidechain: false, message: { role: 'assistant', content: [{ type: 'text', text: 'an answer' }] } }),+ ].join('\n') + '\n');+ expect(await runHook(['session-end'], {+ stdin: JSON.stringify({ session_id: 'sess-new', transcript_path: transcript, cwd: join(tmp, 'ws') }),+ transcriptRoot: join(tmp, 'claude', 'projects'),+ })).toBe(0);+}++describe('E-N1: session-end GC keeps un-ingested corpus files up to 3x retention', () => {+ test('an old extracted file is removed; an old un-extracted file survives; one past 3x retention is removed', async () => {+ const extracted = aged('old-done.txt', 40, true);+ const waiting = aged('old-waiting.txt', 40, false);+ const ceiling = aged('ancient-waiting.txt', 95, false);+ const fresh = aged('fresh-waiting.txt', 2, false);+ await sessionEnd();+ expect(existsSync(join(corpus(), 'sess-new.txt'))).toBe(true);+ expect(existsSync(extracted)).toBe(false);+ expect(existsSync(waiting)).toBe(true);+ expect(existsSync(fresh)).toBe(true);+ expect(existsSync(ceiling)).toBe(false);+ });+});++describe('E-N1: doctor memory_writeback names the un-extracted backlog before it is deleted', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => {+ await engine.disconnect();+ });++ test('files past retention without a sidecar warn with counts, age, the deletion day and the extract command', async () => {+ await engine.setConfig('memory.auto_writeback', 'salient');+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', memory: { auto_writeback: 'salient' } }) + '\n');+ aged('old-waiting.txt', 40, false);+ aged('fresh-waiting.txt', 2, false);+ aged('old-done.txt', 40, true);+ const check = await buildMemoryWritebackCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('1 of 2 captured session file(s) are older than the 30-day corpus retention');+ expect(check.message).toContain('deleted at 90d');+ expect(check.message).toContain('gbrain sweep --once');+ expect(check.details?.corpus_backlog).toMatchObject({ pending: 2, past_retention: 1, oldest_pending_days: 40, deleted_after_days: 90 });+ });++ test('a backlog inside retention is reported in details and stays ok', async () => {+ await engine.setConfig('memory.auto_writeback', 'salient');+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', memory: { auto_writeback: 'salient' } }) + '\n');+ aged('fresh-waiting.txt', 2, false);+ const check = await buildMemoryWritebackCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.details?.corpus_backlog).toMatchObject({ pending: 1, past_retention: 0 });+ });+});