Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: a fresh process starts from the clean dirtiness probes the last one vouched (sync.level_reuse; verify oracle covers reused probes)
garrytane68600bb0750
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 1ac7b8e268..0756c21468 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -148,7 +148,9 @@ than 10 minutes, a change over a quarter of the tree or source (and over2,000), counts that do not add up (a deletion leaves no other trace), a widetransaction-id span, pathspec characters in scope, or any error. Holds,markers, open work and the Git level are read every round.-`gbrain config set sync.level_reuse false` turns both off.+Clean dirtiness probes are kept on this machine (`~/.gbrain/persistence/clean-probes`),+so a new process rereads only files whose stat or tree entry moved.+`gbrain config set sync.level_reuse false` turns all three off.`GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1` also reads whole and fails the pass on anydifference (tests and the nightly freshness cell).diff --git a/llms-full.txt b/llms-full.txtindex 4aba3bf29c..fbcdfe135d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6998,7 +6998,9 @@ than 10 minutes, a change over a quarter of the tree or source (and over2,000), counts that do not add up (a deletion leaves no other trace), a widetransaction-id span, pathspec characters in scope, or any error. Holds,markers, open work and the Git level are read every round.-`gbrain config set sync.level_reuse false` turns both off.+Clean dirtiness probes are kept on this machine (`~/.gbrain/persistence/clean-probes`),+so a new process rereads only files whose stat or tree entry moved.+`gbrain config set sync.level_reuse false` turns all three off.`GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1` also reads whole and fails the pass on anydifference (tests and the nightly freshness cell).diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.tsindex 72d0a61033..3c0341e98d 100644--- a/src/core/persistence/sync-git-stream.ts+++ b/src/core/persistence/sync-git-stream.ts@@ -8,8 +8,9 @@* 600k-path tree costs its map and one chunk.*/import { randomUUID } from 'node:crypto';-import { lstatSync, readFileSync, realpathSync, rmSync, writeFileSync, type BigIntStats } from 'node:fs';+import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync, type BigIntStats } from 'node:fs';import { join, relative, resolve, sep } from 'node:path';+import { configDir } from '../config.ts';import { hardenedGitStream, hardenedStreamComplete, NulRecordSplitter, type HardenedGitStreamResult } from '../hardened-git.ts';import { gitBlobOid, sha256 } from './digest.ts';import { readSyncFile } from './sync-discovery.ts';@@ -346,9 +347,15 @@ interface ReadFile { path: string; sha256: string; localOid: string; foldedOid:* `ctime` are older than 2 s before the call began, by the earlier of the* process's and the filesystem's clocks (`racyFloor`, the working stat cache's* racy window), so an edit made during or after the read always rehashes.+ *+ * With `persist` (`sync.level_reuse`, GBRA-133 wave 4) the vouched probes also outlive the process: a process with none+ * for this root and Git root starts from the ones the last process saved (`cleanProbeFile`), each still checked against+ * the path's lstat key and tree entry, and saves its own when they changed (at most once a minute per root). A file that+ * is missing, unreadable, for another root or with any malformed entry is ignored whole. With `verify` every reused probe+ * is read and hashed anyway, and `verify` gets the reused count and the first path whose fresh probe differs.*/export async function probeDirtiness(root: string, gitRoot: string, paths: string[], tree: Map<string, GitTreeEntry>,- index: Map<string, GitIndexEntry>, opts: { batch?: number; working?: boolean; step?: LoopYield } = {}): Promise<Map<string, DirtinessProbe>> {+ index: Map<string, GitIndexEntry>, opts: { batch?: number; working?: boolean; step?: LoopYield; persist?: boolean; verify?: (reused: number, differs: string | null) => void } = {}): Promise<Map<string, DirtinessProbe>> {const batch = Math.max(1, opts.batch ?? 2000);const results = new Map<string, DirtinessProbe>();const firstOid = tree.values().next().value?.oid ?? index.values().next().value?.oid ?? '';@@ -358,7 +365,9 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strintry { realRoot = realpathSync.native(root); realGitRoot = realpathSync.native(gitRoot); } catch {}const step = opts.step ?? loopYield();const cleanKey = !opts.working && realRoot !== null && realGitRoot !== null ? `${realRoot}\0${realGitRoot}` : null;- const vouched = cleanKey === null ? null : new Map(cleanProbes.get(cleanKey));+ const vouched = cleanKey === null ? null : new Map(cleanProbes.get(cleanKey) ?? (opts.persist ? loadCleanProbes(cleanKey) : undefined));+ const checked = new Map<string, DirtinessProbe>();+ let touched = false;const racyFrom = vouched ? racyFloor(realGitRoot!) : 0n;for (let start = 0; start < paths.length; start += batch) {const decided = new Map<string, Dp | null>();@@ -376,8 +385,12 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strinconst statKey = vouched && dp === null && !unreadable ? statAt(realGitRoot!, path) : null;const prior = statKey && statKey !== ABSENT ? vouched!.get(path) : undefined;const signature = `${statKey}|${committed?.oid}|${committed?.mode}|`;- if (prior?.startsWith(signature)) { results.set(path, { dp: 'clean', rawOid: committed!.oid, rawSha256: prior.slice(signature.length) }); continue; }- vouched?.delete(path);+ if (prior?.startsWith(signature)) {+ const kept: DirtinessProbe = { dp: 'clean', rawOid: committed!.oid, rawSha256: prior.slice(signature.length) };+ if (!opts.verify) { results.set(path, kept); continue; }+ checked.set(path, kept);+ }+ if (vouched?.delete(path)) touched = true;if (!unreadable) { try { bytes = readSyncFile(root, sourcePath); } catch { unreadable = true; } }if ((dp === null || opts.working) && !unreadable && bytes === null) dp = 'deleted';const hashable = bytes !== null && !path.includes('\n') && !path.startsWith('"');@@ -407,7 +420,7 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strinif (rawOid === committed.oid) {settle(executableMatches ? 'clean' : 'unknown');if (executableMatches && file.statKey && vouched!.size < WORKING_STAT_CACHE_MAX_ENTRIES && statAt(realGitRoot!, file.path) === file.statKey- && file.statKey.split(':').slice(5).every(ns => BigInt(ns) < racyFrom)) vouched!.set(file.path, `${file.statKey}|${committed.oid}|${committed.mode}|${file.sha256}`);+ && file.statKey.split(':').slice(5).every(ns => BigInt(ns) < racyFrom)) { vouched!.set(file.path, `${file.statKey}|${committed.oid}|${committed.mode}|${file.sha256}`); touched = true; }continue;}if (attributeSet(attr['working-tree-encoding']) || (attributeSet(attr.filter) && attr.filter !== 'lfs')) { settle('unknown'); continue; }@@ -431,12 +444,48 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strincleanProbes.delete(cleanKey);cleanProbes.set(cleanKey, vouched!);while (cleanProbes.size > WORKING_STAT_CACHES_REMEMBERED) cleanProbes.delete(cleanProbes.keys().next().value!);+ if (opts.persist && touched && Date.now() - (cleanProbesSavedAt.get(cleanKey) ?? -Infinity) >= CLEAN_PROBE_SAVE_EVERY_MS) saveCleanProbes(cleanKey, vouched!);+ }+ if (opts.verify) {+ const differs = [...checked].find(([path, kept]) => JSON.stringify(results.get(path)) !== JSON.stringify(kept));+ opts.verify(checked.size, differs ? `${differs[0]}: kept ${JSON.stringify(differs[1])}, read ${JSON.stringify(results.get(differs[0]))}` : null);}return results;}/** Committed-mode `clean` probes this process vouched, by root and Git root: path -> `<stat key>|<tree oid>|<tree mode>|<sha256>`. */const cleanProbes = new Map<string, Map<string, string>>();+const cleanProbesSavedAt = new Map<string, number>();+const CLEAN_PROBE_SAVE_EVERY_MS = 60_000;+const CLEAN_PROBE = /^\d+:\d+:\d+:\d+:\d+:\d+:\d+\|[0-9a-f]{40}(?:[0-9a-f]{24})?\|\d{6}\|[0-9a-f]{64}$/;++/** Where `persist` keeps the vouched probes of one root and Git root (`key`): this machine's gbrain home, never the brain. */+export function cleanProbeFile(key: string): string {+ return join(configDir(), 'persistence', 'clean-probes', `${sha256(key).slice(0, 32)}.json`);+}++function loadCleanProbes(key: string): Map<string, string> | undefined {+ try {+ const doc = JSON.parse(readFileSync(cleanProbeFile(key), 'utf8')) as { v?: unknown; key?: unknown; entries?: unknown };+ if (doc.v !== 1 || doc.key !== key || !doc.entries || typeof doc.entries !== 'object' || Array.isArray(doc.entries)) return undefined;+ const list = Object.entries(doc.entries as Record<string, unknown>);+ if (list.length > WORKING_STAT_CACHE_MAX_ENTRIES || !list.every(([, entry]) => typeof entry === 'string' && CLEAN_PROBE.test(entry))) return undefined;+ return new Map(list as Array<[string, string]>);+ } catch { return undefined; }+}++function saveCleanProbes(key: string, probes: Map<string, string>): void {+ const file = cleanProbeFile(key), staged = `${file}.${randomUUID()}.tmp`;+ try {+ mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });+ writeFileSync(staged, JSON.stringify({ v: 1, key, entries: Object.fromEntries(probes) }), { mode: 0o600 });+ renameSync(staged, file);+ cleanProbesSavedAt.set(key, Date.now());+ } catch { rmSync(staged, { force: true }); }+}++/** Tests: forget this process's vouched probes and save times, as a new process starts. */+export function __resetCleanProbesForTests(): void { cleanProbes.clear(); cleanProbesSavedAt.clear(); }/** Raw blob ids (no filters) of present files, in order, or null when Git did not answer every path. */async function hashRaw(gitRoot: string, paths: string[]): Promise<string[] | null> {diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 5671375d82..521880dc5d 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -852,7 +852,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stt = timer();const candidateIndex = new Map<string, GitIndexEntry>();for (const path of candidates) { if (step.due()) await step.pause(); const entry = indexed(path); if (entry) candidateIndex.set(path, entry); }- const probed = await probeDirtiness(root, gitRoot, candidates, tree, candidateIndex, { step });+ const probed = await probeDirtiness(root, gitRoot, candidates, tree, candidateIndex, { step, persist: input.pass?.levelReuse === true,+ ...(levelReuseVerify() ? { verify: (reused: number, differs: string | null) => { if (reused) reportLevelReuseCheck('dirtiness probes', `${reused} reused`, differs); } } : {}) });timings.Dp = (timings.Dp ?? 0) + t();t = timer();for (const [k, path] of candidates.entries()) {diff --git a/test/sync-probe-persist-gbra133.test.ts b/test/sync-probe-persist-gbra133.test.tsnew file mode 100644index 0000000000..643d1e5822--- /dev/null+++ b/test/sync-probe-persist-gbra133.test.ts@@ -0,0 +1,117 @@+/**+ * GBRA-133 wave 4: a fresh process (a CLI \x60gbrain sync\x60, a sync job) had no vouched clean probes (#7338 keeps them in the+ * process), so its pass read and hashed every candidate file again: about 250 ms per pass at 10k pages, linear in the brain.+ * With \x60persist\x60 (\x60sync.level_reuse\x60) a new process starts from the probes the last one saved under this machine's gbrain+ * home, each still checked against the path's lstat key and tree entry; anything doubtful in the file is ignored whole, and+ * \x60verify\x60 (the level-reuse oracle) still reads every reused path and reports the first that differs.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, writeSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { __resetCleanProbesForTests, cleanProbeFile, probeDirtiness, readIndexLevel, readTreeLevel } from '../src/core/persistence/sync-git-stream.ts';+import { withEnv } from './helpers/with-env.ts';++const dirs: string[] = [];+afterAll(() => { __resetCleanProbesForTests(); for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });++const GIT_ENV = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', env: GIT_ENV, stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const blobOid = (content: string) => createHash('sha1').update(`blob ${Buffer.byteLength(content)}\0`).update(content).digest('hex');+const sha256 = (content: string) => createHash('sha256').update(content).digest('hex');+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));+const RACY_WAIT_MS = 2_100;++function temp(prefix: string): string { const dir = mkdtempSync(join(tmpdir(), prefix)); dirs.push(dir); return dir; }++function repo(files: Record<string, string>): string {+ const root = temp('gbrain-probe-persist-');+ git(root, 'init', '-q');+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);+ git(root, 'add', '-A');+ git(root, '-c', '[email protected]', '-c', 'user.name=Writer Example', 'commit', '-qm', 'init');+ return root;+}++/** Runs \x60fn\x60 with the Git directory moved away, so a path probed again (attributes, raw OIDs) reads \x60unknown\x60. */+async function withoutGit<T>(root: string, fn: () => Promise<T>): Promise<T> {+ renameSync(join(root, '.git'), join(root, '.git-away'));+ try { return await fn(); } finally { renameSync(join(root, '.git-away'), join(root, '.git')); }+}++/** A repository past the racy window, its levels, and a probe run as a new process would (no probes in memory). */+async function vouchedRepo(files: Record<string, string>) {+ const root = repo(files);+ const tree = await readTreeLevel(root, 'HEAD', ''), index = await readIndexLevel(root);+ await sleep(RACY_WAIT_MS);+ const paths = Object.keys(files);+ const fresh = (opts: Parameters<typeof probeDirtiness>[5] = {}) => { __resetCleanProbesForTests(); return probeDirtiness(root, root, paths, tree, index, opts); };+ const real = realpathSync.native(root);+ return { root, tree, index, paths, fresh, file: cleanProbeFile(`${real}\0${real}`) };+}++describe('GBRA-133 wave 4: vouched clean probes outlive the process with persist', () => {+ test('a new process reuses the probes the last one saved, without reading or hashing the files', () => withEnv({ GBRAIN_HOME: temp('gbrain-home-') }, async () => {+ const r = await vouchedRepo({ 'a.md': 'alpha\n', 'b.md': 'bravo\n' });+ expect((await r.fresh({ persist: true })).get('a.md')).toEqual({ dp: 'clean', rawOid: blobOid('alpha\n'), rawSha256: sha256('alpha\n') });+ expect(existsSync(r.file)).toBe(true);+ expect((statSync(r.file).mode & 0o777)).toBe(0o600);+ const again = await withoutGit(r.root, () => r.fresh({ persist: true }));+ expect(again.get('a.md')).toEqual({ dp: 'clean', rawOid: blobOid('alpha\n'), rawSha256: sha256('alpha\n') });+ expect(again.get('b.md')).toEqual({ dp: 'clean', rawOid: blobOid('bravo\n'), rawSha256: sha256('bravo\n') });+ }), 30_000);++ test('without persist a new process neither reads nor writes the file', () => withEnv({ GBRAIN_HOME: temp('gbrain-home-') }, async () => {+ const r = await vouchedRepo({ 'a.md': 'alpha\n' });+ expect((await r.fresh()).get('a.md')?.dp).toBe('clean');+ expect(existsSync(r.file)).toBe(false);+ expect((await r.fresh({ persist: true })).get('a.md')?.dp).toBe('clean');+ expect((await withoutGit(r.root, () => r.fresh())).get('a.md')?.dp).toBe('unknown');+ }), 30_000);++ test('a file with one malformed entry, or saved for another root, is ignored whole', () => withEnv({ GBRAIN_HOME: temp('gbrain-home-') }, async () => {+ const r = await vouchedRepo({ 'a.md': 'alpha\n', 'b.md': 'bravo\n' });+ await r.fresh({ persist: true });+ const saved = JSON.parse(readFileSync(r.file, 'utf8')) as { v: number; key: string; entries: Record<string, string> };+ writeFileSync(r.file, JSON.stringify({ ...saved, entries: { ...saved.entries, 'b.md': 'not a probe' } }));+ expect((await withoutGit(r.root, () => r.fresh({ persist: true }))).get('a.md')?.dp).toBe('unknown');+ writeFileSync(r.file, JSON.stringify({ ...saved, key: 'another root' }));+ expect((await withoutGit(r.root, () => r.fresh({ persist: true }))).get('a.md')?.dp).toBe('unknown');+ writeFileSync(r.file, '{"v":1,');+ expect((await withoutGit(r.root, () => r.fresh({ persist: true }))).get('a.md')?.dp).toBe('unknown');+ }), 30_000);++ test('a same-inode, same-size edit with a restored mtime after the save is a change', () => withEnv({ GBRAIN_HOME: temp('gbrain-home-') }, async () => {+ const root = repo({ 'a.md': 'alpha one\n' });+ const past = Math.floor(Date.now() / 1000) - 3600;+ utimesSync(join(root, 'a.md'), past, past);+ const tree = await readTreeLevel(root, 'HEAD', ''), index = await readIndexLevel(root);+ await sleep(RACY_WAIT_MS);+ __resetCleanProbesForTests();+ expect((await probeDirtiness(root, root, ['a.md'], tree, index, { persist: true })).get('a.md')?.dp).toBe('clean');+ const fd = openSync(join(root, 'a.md'), 'r+');+ try { writeSync(fd, 'alpha two\n', 0); } finally { closeSync(fd); }+ utimesSync(join(root, 'a.md'), past, past);+ __resetCleanProbesForTests();+ expect((await probeDirtiness(root, root, ['a.md'], tree, index, { persist: true })).get('a.md')).toEqual({ dp: 'modified', rawOid: blobOid('alpha two\n'), rawSha256: sha256('alpha two\n') });+ }), 30_000);++ test('verify reads every reused probe and names the first that differs (a saved hash that is not the file)', () => withEnv({ GBRAIN_HOME: temp('gbrain-home-') }, async () => {+ const r = await vouchedRepo({ 'a.md': 'alpha\n', 'b.md': 'bravo\n' });+ await r.fresh({ persist: true });+ const checks: Array<[number, string | null]> = [];+ const verify = (reused: number, differs: string | null) => { checks.push([reused, differs]); };+ expect((await r.fresh({ persist: true, verify })).get('a.md')?.dp).toBe('clean');+ expect(checks).toEqual([[2, null]]);+ const saved = JSON.parse(readFileSync(r.file, 'utf8')) as { v: number; key: string; entries: Record<string, string> };+ const forged = saved.entries['a.md']!.replace(/[0-9a-f]{64}$/, sha256('not alpha\n'));+ writeFileSync(r.file, JSON.stringify({ ...saved, entries: { ...saved.entries, 'a.md': forged } }));+ checks.length = 0;+ expect((await r.fresh({ persist: true, verify })).get('a.md')).toEqual({ dp: 'clean', rawOid: blobOid('alpha\n'), rawSha256: sha256('alpha\n') });+ expect(checks.length).toBe(1);+ expect(checks[0]![0]).toBe(2);+ expect(checks[0]![1]).toContain('a.md');+ }), 30_000);+});