Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(writeback): each brain keeps its own writeback-off capture record (W4.2)

time-attack681fe95e62e3
diff --git a/docs/architecture/key-files/ambient-capture.md b/docs/architecture/key-files/ambient-capture.md
index 8ae0b8b08c..eacf21e0aa 100644
--- a/docs/architecture/key-files/ambient-capture.md
+++ b/docs/architecture/key-files/ambient-capture.md
@@ -8,4 +8,4 @@ each lane's claim, and a re-check at fact admission. User guide:
[ambient writeback](../../guides/ambient-writeback.md#capture-lanes-and-the-off-switch).
Key files:
-- `src/core/context/capture-consent.ts` + `src/core/facts/capture-sources.ts` (+ `captureGateDecision` in `src/core/facts/writeback-config.ts`) — `captureGateDecision(cfg, lane)` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write `<file>.capture-off.json` — brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts` — BEFORE the file lands; GC reaps an orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's record via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`. Retired turn hashes also land in `.progress` `retired_turns` (`retireCorpusFile`, `retireCorpusTurns`); `planCorpusWindows` skips them wherever a rewrite places them, and `withoutOffPeriodTurns` (capture-consent.ts) strips them from what `discoverTranscripts` hands dream synthesis.
+- `src/core/context/capture-consent.ts` + `src/core/facts/capture-sources.ts` (+ `captureGateDecision` in `src/core/facts/writeback-config.ts`) — `captureGateDecision(cfg, lane)` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write this brain's own `<file>.capture-off.<brain>.json` (`captureOffRecordPath`; brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts`) BEFORE the file lands, unioning a pre-wave-12 single `<file>.capture-off.json` that names this brain, so two brains sharing a corpus directory never overwrite each other's off turns; GC (`corpus-segments.ts`, `CAPTURE_OFF_INFIX`) reaps any brain's orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's turns, own record plus a matching legacy record, via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored; an unreadable or invalid record holds `capture_record_unreadable` and makes `recordCaptureIfOff` throw, never reads as "no record"), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`. Retired turn hashes also land in `.progress` `retired_turns` (`retireCorpusFile`, `retireCorpusTurns`); `planCorpusWindows` skips them wherever a rewrite places them, and `withoutOffPeriodTurns` (capture-consent.ts) strips them from what `discoverTranscripts` hands dream synthesis.
diff --git a/src/core/context/capture-consent.ts b/src/core/context/capture-consent.ts
index be0febe789..af69a31d64 100644
--- a/src/core/context/capture-consent.ts
+++ b/src/core/context/capture-consent.ts
@@ -37,9 +37,9 @@ import type { GBrainConfig } from '../config.ts';
import { configDir, loadConfig } from '../config.ts';
import { captureGateDecision, fileCaptureIsOff, resolveWritebackConfig, type CaptureGateDecision, type CaptureGateLane, type WritebackMode } from '../facts/writeback-config.ts';
import { parseCorpusTurns } from './corpus-turns.ts';
-import { CAPTURE_OFF_SUFFIX, CORPUS_PROGRESS_SUFFIX, parseSegmentFileName, parseWbFileName, writebackOffSidecarJson } from './corpus-segments.ts';
+import { CAPTURE_OFF_INFIX, CAPTURE_OFF_SUFFIX, CORPUS_PROGRESS_SUFFIX, parseSegmentFileName, parseWbFileName, writebackOffSidecarJson } from './corpus-segments.ts';
-export { CAPTURE_OFF_SUFFIX };
+export { CAPTURE_OFF_INFIX, CAPTURE_OFF_SUFFIX };
interface CaptureOffRecord {
version: 1;
@@ -64,15 +64,38 @@ export function captureLaneForFile(name: string): CaptureGateLane {
return 'session_end';
}
-function readRecord(path: string): CaptureOffRecord | null {
+/** A record file: absent, unreadable/invalid (never "no record": it holds), or this shape. */
+function readRecord(path: string): CaptureOffRecord | null | 'unreadable' {
+ let raw: string;
+ try { raw = readFileSync(path, 'utf8'); } catch (e) {
+ return (e as NodeJS.ErrnoException).code === 'ENOENT' ? null : 'unreadable';
+ }
try {
- const r = JSON.parse(readFileSync(path, 'utf8')) as CaptureOffRecord;
- return r && r.version === 1 && typeof r.brain === 'string' && Array.isArray(r.turns) ? r : null;
+ const r = JSON.parse(raw) as CaptureOffRecord;
+ return r && r.version === 1 && typeof r.brain === 'string' && Array.isArray(r.turns) && r.turns.every((t) => typeof t === 'string') ? r : 'unreadable';
} catch {
- return null;
+ return 'unreadable';
}
}
+/** W4.2: this brain's own record file for corpus file `file` (two brains sharing a corpus directory never write the same file). */
+export function captureOffRecordPath(file: string, brain: string = brainIdentity()): string {
+ return `${file}${CAPTURE_OFF_INFIX}${brain}.json`;
+}
+
+/**
+ * The turns this brain captured under off for `file`: its own record plus a
+ * pre-wave-12 single-file record (`<file>.capture-off.json`) when that one
+ * names this brain. `unreadable` when either file exists but cannot be read
+ * or parsed, so callers hold instead of treating it as "no record".
+ */
+function offTurns(file: string, brain: string): string[] | 'unreadable' {
+ const own = readRecord(captureOffRecordPath(file, brain));
+ const legacy = readRecord(file + CAPTURE_OFF_SUFFIX);
+ if (own === 'unreadable' || legacy === 'unreadable') return 'unreadable';
+ return [...(own?.turns ?? []), ...(legacy && legacy.brain === brain ? legacy.turns : [])];
+}
+
/**
* Capture side: when `cfg` (the brain's own file plane) says an explicit off,
* record every turn of `text` as captured under off for `file`. Call it before
@@ -81,10 +104,12 @@ function readRecord(path: string): CaptureOffRecord | null {
*/
export function recordCaptureIfOff(cfg: GBrainConfig | null | undefined, file: string, text: string, source?: string | null): boolean {
if (!fileCaptureIsOff(cfg)) return false;
- const path = file + CAPTURE_OFF_SUFFIX;
const brain = brainIdentity();
- const prior = readRecord(path);
- const turns = new Set(prior && prior.brain === brain ? prior.turns : []);
+ const path = captureOffRecordPath(file, brain);
+ // W4.2: the first namespaced write unions a legacy record of this brain; an unreadable record throws (bank nothing).
+ const prior = offTurns(file, brain);
+ if (prior === 'unreadable') throw new Error(`capture-off record for ${basename(file)} is unreadable; nothing was banked`);
+ const turns = new Set(prior);
for (const t of parseCorpusTurns(text)) turns.add(t.sha256);
const record: CaptureOffRecord = { version: 1, brain, source: source ?? null, at: new Date().toISOString(), turns: [...turns] };
const tmp = `${path}.tmp-${process.pid}`;
@@ -129,14 +154,15 @@ export async function applyCaptureGate(full: string, decision: CaptureGateDecisi
}
return await retireCorpusFile(full) ? decision : { action: 'hold', reason: 'retire_deferred' };
}
- const record = readRecord(full + CAPTURE_OFF_SUFFIX);
- if (!record || record.brain !== brainIdentity()) return decision;
- const retired = new Set(record.turns);
+ const off = offTurns(full, brainIdentity());
+ if (off === 'unreadable') return { action: 'hold', reason: 'capture_record_unreadable' };
+ if (off.length === 0) return decision;
+ const retired = new Set(off);
const current = parseCorpusTurns(await readFile(full, 'utf8'));
if (current.every((t) => retired.has(t.sha256))) {
return await retireCorpusFile(full) ? { action: 'retire', reason: 'captured_under_off' } : { action: 'hold', reason: 'retire_deferred' };
}
- return await retireCorpusTurns(full, record.turns) ? decision : { action: 'hold', reason: 'retire_deferred' };
+ return await retireCorpusTurns(full, [...retired]) ? decision : { action: 'hold', reason: 'retire_deferred' };
}
/** `resolveCaptureGate` + `applyCaptureGate` for one file of one lane. */
@@ -151,10 +177,11 @@ export async function gateCorpusFile(engine: BrainEngine, full: string, lane: Ca
* is left. Content with no off-period turns comes back unchanged.
*/
export function withoutOffPeriodTurns(full: string, content: string): string | null {
- const record = readRecord(full + CAPTURE_OFF_SUFFIX);
+ const recorded = offTurns(full, brainIdentity());
+ if (recorded === 'unreadable') return null;
let retired: string[] = [];
try { retired = (JSON.parse(readFileSync(full + CORPUS_PROGRESS_SUFFIX, 'utf8')) as { retired_turns?: string[] }).retired_turns ?? []; } catch { /* no progress */ }
- const off = new Set([...(record && record.brain === brainIdentity() ? record.turns : []), ...retired]);
+ const off = new Set([...recorded, ...retired]);
if (off.size === 0) return content;
const turns = parseCorpusTurns(content);
const kept = turns.filter((t) => !off.has(t.sha256));
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.ts
index eb032ce267..29639ee1fa 100644
--- a/src/core/context/corpus-segments.ts
+++ b/src/core/context/corpus-segments.ts
@@ -94,8 +94,10 @@ const SEAT_ORPHAN_GRACE_MS = 10 * 60 * 1000;
* publish). Lives HERE so the engine-free hook lane can GC orphaned receipts
* without importing the engine-typed harvest module. */
export const HARVEST_RECEIPT_SUFFIX = '.receipt.json';
-/** #6091: capture-time consent record (capture-consent.ts); reaped with its corpus file after a grace period. */
+/** #6091: capture-time consent record (capture-consent.ts); reaped with its corpus file after a grace period.
+ * `<file>.capture-off.json` is the pre-wave-12 single record; W4.2 records are `<file>.capture-off.<brain>.json`. */
export const CAPTURE_OFF_SUFFIX = '.capture-off.json';
+export const CAPTURE_OFF_INFIX = '.capture-off.';
/** #5887 window-progress sidecar (context/corpus-windows.ts) and its CAS
* lock. Engine-free home so the hook's GC reaps both with the `.txt`; the
* hook's resume rewrite never deletes them. */
@@ -587,9 +589,10 @@ export function gcCorpusArtifacts(
}
continue;
}
- if (name.endsWith(CAPTURE_OFF_SUFFIX)) {
- // Written BEFORE its corpus file lands: only an orphan past the grace period is reaped.
- if (!existsSync(p.slice(0, -CAPTURE_OFF_SUFFIX.length)) && statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) rmSync(p, { force: true });
+ const offAt = name.endsWith('.json') ? name.lastIndexOf(CAPTURE_OFF_INFIX) : -1;
+ if (offAt > 0) {
+ // Written BEFORE its corpus file lands: only an orphan past the grace period is reaped (every brain's record alike).
+ if (!existsSync(join(dir, name.slice(0, offAt))) && statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) rmSync(p, { force: true });
continue;
}
if (name.endsWith('.ledger.json')) {
diff --git a/test/capture-consent-gate.serial.test.ts b/test/capture-consent-gate.serial.test.ts
index 9495f0b2d8..a13bea4c45 100644
--- a/test/capture-consent-gate.serial.test.ts
+++ b/test/capture-consent-gate.serial.test.ts
@@ -10,7 +10,7 @@
* Serial: real PGLite engines, module-global harvest queue, GBRAIN_HOME env.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -19,7 +19,9 @@ import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
import type { CapabilityReport } from '../src/core/capability.ts';
import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';
import { __drainCheckpointHarvestForTests, __resetCheckpointHarvestForTests, scheduleCheckpointHarvest } from '../src/core/context/checkpoint-harvest.ts';
-import { appendSegmentLedger, segmentFileName, writeSegment } from '../src/core/context/corpus-segments.ts';
+import { appendSegmentLedger, gcCorpusArtifacts, segmentFileName, writeSegment } from '../src/core/context/corpus-segments.ts';
+import { brainIdentity, recordCaptureIfOff } from '../src/core/context/capture-consent.ts';
+import { parseCorpusTurns } from '../src/core/context/corpus-turns.ts';
import { runHook } from '../src/commands/hook.ts';
import { discoverTranscripts } from '../src/core/cycle/transcript-discovery.ts';
@@ -340,6 +342,69 @@ describe('two brains on one machine', () => {
expect(prompts[0]).toContain('beta said to brain B');
});
+ // W4.2: two brains whose hooks bank the same session file in one shared corpus directory.
+ const OFF = { engine: 'pglite', memory: { auto_writeback: 'off' } } as never;
+ const shared = (sessionId: string, turns: string[]) => {
+ const file = join(corpusDir, `${sessionId}.txt`);
+ return { file, text: corpusText(turns) };
+ };
+
+ test('W4.2: brain B capturing under off never erases brain A\'s off record for the same file', async () => {
+ await setMode('off');
+ const { file, text } = shared('sess-w42a', ['delta said to brain A under off', 'ack']);
+ recordCaptureIfOff(OFF, file, text);
+ await asBrainB(async () => { recordCaptureIfOff(OFF, file, text + '\n[user]\nepsilon said to brain B\n'); });
+ writeFileSync(file, text);
+ await setMode('salient');
+ await sweep();
+ expect(prompts.length).toBe(0);
+ });
+
+ test('W4.2: a pre-upgrade record of this brain is unioned on the first per-brain write and survives an older writer replacing it', async () => {
+ await setMode('off');
+ const { file, text } = shared('sess-w42b', ['zeta said to brain A before the upgrade', 'ack']);
+ const legacy = file + '.capture-off.json';
+ writeFileSync(legacy, JSON.stringify({ version: 1, brain: brainIdentity(), source: null, at: new Date().toISOString(),
+ turns: parseCorpusTurns(text).map((t) => t.sha256) }) + '\n');
+ const later = text + '\n[user]\neta said to brain A after the upgrade\n';
+ recordCaptureIfOff(OFF, file, later);
+ // An older gbrain on brain B still writes the single legacy file and drops A's turns from it.
+ await asBrainB(async () => {
+ writeFileSync(legacy, JSON.stringify({ version: 1, brain: brainIdentity(), source: null, at: new Date().toISOString(), turns: [] }) + '\n');
+ });
+ writeFileSync(file, later);
+ await setMode('salient');
+ await sweep();
+ expect(prompts.length).toBe(0);
+ });
+
+ test('W4.2: an unreadable capture-off record holds the file instead of reading as "no record"', async () => {
+ const { file, text } = shared('sess-w42c', ['theta said under off, record later corrupted', 'ack']);
+ writeFileSync(file + '.capture-off.json', '{"version":1,"brain":');
+ writeFileSync(file, text);
+ await setMode('salient');
+ await sweep();
+ expect(prompts.length).toBe(0);
+ expect(() => recordCaptureIfOff(OFF, file, text)).toThrow(/unreadable/);
+ });
+
+ test('W4.2: GC reaps any brain\'s orphaned record only past the grace period and keeps a live file\'s records', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gb-consent-gc-'));
+ tmpDirs.push(dir);
+ const old = new Date(Date.now() - 60 * 60 * 1000);
+ const orphanB = join(dir, 'gone.txt.capture-off.bbbbbbbbbbbbbbbbbbbbbbbb.json');
+ const freshB = join(dir, 'pending.txt.capture-off.bbbbbbbbbbbbbbbbbbbbbbbb.json');
+ const liveA = join(dir, 'live.txt.capture-off.aaaaaaaaaaaaaaaaaaaaaaaa.json');
+ for (const p of [orphanB, freshB, liveA]) writeFileSync(p, '{}\n');
+ writeFileSync(join(dir, 'live.txt'), '[user]\nhi\n');
+ utimesSync(orphanB, old, old);
+ utimesSync(liveA, old, old);
+ gcCorpusArtifacts(dir, 24 * 60 * 60 * 1000, []);
+ expect(existsSync(orphanB)).toBe(false);
+ expect(existsSync(freshB)).toBe(true);
+ expect(existsSync(liveA)).toBe(true);
+ });
+
test('pin: a capture record written by another brain in a shared corpus directory is ignored', async () => {
await setMode('off');
await sessionEnd('sess-m3', ['gamma in the shared directory', 'ack']);