Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: working level reads the physical bytes; Git-contract stat cache (#6712 PR 4b lane W, probes 41, 42)

garrytand1aab10dbff4
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.ts
index 63f8ecee49..c936a62f7d 100644
--- a/src/core/persistence/sync-git-stream.ts
+++ b/src/core/persistence/sync-git-stream.ts
@@ -7,7 +7,7 @@
* is parsed as it streams; nothing but the result maps is held, so a
* 600k-path tree costs its map and one chunk.
*/
-import { lstatSync, realpathSync } from 'node:fs';
+import { lstatSync, realpathSync, type BigIntStats } from 'node:fs';
import { join, relative, sep } from 'node:path';
import { hardenedGitStream, hardenedStreamComplete, NulRecordSplitter, type HardenedGitStreamResult } from '../hardened-git.ts';
import { gitBlobOid, sha256 } from './digest.ts';
@@ -206,10 +206,18 @@ interface ReadFile { path: string; sha256: string; localOid: string; foldedOid:
* `hash-object --no-filters --stdin-paths` per batch and must agree with the
* bytes read here; attributes from one `check-attr -z --stdin`. A present,
* readable file also reports its raw OID and sha256 under `staged` and
- * `untracked`, for working mode.
+ * `untracked`.
+ *
+ * `working` (design v3.2 §2.1, the working level is the physical bytes):
+ * the index is not read. A path is `deleted` when no file backs it, whatever
+ * the index says; a present file outside the tree is `untracked` with its raw
+ * OID; every other present file is judged from its bytes against the tree,
+ * through the same `clean_eol`/`clean_lfs` domains. So a staged edit, a staged
+ * new file, `git rm --cached`, a staged deletion and a staged file removed from
+ * disk probe exactly as the same disk does with a pristine index.
*/
export async function probeDirtiness(root: string, gitRoot: string, paths: string[], tree: Map<string, GitTreeEntry>,
- index: Map<string, GitIndexEntry>, opts: { batch?: number } = {}): Promise<Map<string, DirtinessProbe>> {
+ index: Map<string, GitIndexEntry>, opts: { batch?: number; working?: boolean } = {}): 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 ?? '';
@@ -223,13 +231,13 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
for (const path of paths.slice(start, start + batch)) {
const committed = tree.get(path);
const indexed = index.get(path);
- let dp: Dp | null = !committed && !indexed ? 'untracked'
+ let dp: Dp | null = opts.working ? (committed ? null : 'untracked') : !committed && !indexed ? 'untracked'
: !committed || !indexed || indexed.oid !== committed.oid || indexed.mode !== committed.mode || indexed.stage !== 0 ? 'staged' : null;
let bytes: Buffer | null = null;
let unreadable = realRoot === null || realGitRoot === null;
const sourcePath = unreadable ? '' : relative(realRoot!, join(realGitRoot!, path)).split(sep).join('/');
if (!unreadable) { try { bytes = readSyncFile(root, sourcePath); } catch { unreadable = true; } }
- if (dp === null && !unreadable && bytes === null) dp = 'deleted';
+ if ((dp === null || opts.working) && !unreadable && bytes === null) dp = 'deleted';
const hashable = bytes !== null && !path.includes('\n') && !path.startsWith('"');
if (dp === null && (committed!.mode === '120000' || committed!.mode === '160000' || unreadable || !hashable)) dp = 'unknown';
decided.set(path, dp);
@@ -305,3 +313,125 @@ async function readAttributes(gitRoot: string, paths: string[]): Promise<Map<str
}
return paths.every(path => ATTRIBUTES.every(name => attrs.get(path)?.[name] !== undefined)) ? attrs : null;
}
+
+/**
+ * The working stat cache (design v3.2 §2.1, Git's freshness contract). Each
+ * Git-root-relative path maps to the `lstat` key `dev:ino:mode:uid:size:mtime_ns:ctime_ns`
+ * it had when its bytes were hashed, or `absent`. A user can restore `mtime` but
+ * not `ctime`, so a same-size, same-inode edit still changes the key. Plain JSON;
+ * entries are self-contained, so two caches of one root merge by spreading
+ * their entries.
+ */
+export interface WorkingStatCache { v: 1; root: string; entries: Record<string, string> }
+
+const WORKING_RACY_WINDOW_NS = 2_000_000_000n;
+const WORKING_HASH_ATTEMPTS = 3;
+const WORKING_STAT_CACHES_REMEMBERED = 64;
+const ABSENT = 'absent';
+const STAT_KEY = /^\d+:\d+:\d+:\d+:\d+:\d+:\d+$/;
+/** Entries a cache keeps (by path order); a path beyond the bound reads as changed [estimated]. */
+export const WORKING_STAT_CACHE_MAX_ENTRIES = 100_000;
+
+/** The cache key of one bigint `lstat`, or null when it cannot vouch for the file (no stat, or no `ctime`). */
+export function workingStatKey(stats: Pick<BigIntStats, 'dev' | 'ino' | 'mode' | 'uid' | 'size' | 'mtimeNs' | 'ctimeNs'> | null): string | null {
+ if (!stats || !stats.ctimeNs) return null;
+ return [stats.dev, stats.ino, stats.mode, stats.uid, stats.size, stats.mtimeNs, stats.ctimeNs].join(':');
+}
+
+/** `absent` for a path nothing backs, its key, or null for any other stat failure (uncertain). */
+function statAt(root: string, path: string): string | null {
+ try { return workingStatKey(lstatSync(join(root, path), { bigint: true })); }
+ catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT' ? ABSENT : null; }
+}
+
+function rootStill(root: string): boolean {
+ try { return realpathSync.native(root) === root; } catch { return false; }
+}
+
+/**
+ * The idle tick's working-mode check: every path in `paths` or in the cache whose
+ * stat no longer matches its entry is changed, as is a path the cache does not
+ * hold (new, racy when hashed, past the bound), a stat that fails or has no
+ * `ctime`, and every path when there is no cache or its root moved. Uncertainty is
+ * never "no change". Returns the changed paths, sorted, and the cache without
+ * them.
+ */
+export function workingChanged(cache: WorkingStatCache | null, paths: Iterable<string>): { changed: string[]; cache: WorkingStatCache | null } {
+ const all = new Set(paths);
+ if (!cache || !rootStill(cache.root)) return { changed: [...all].sort(), cache: null };
+ for (const path of Object.keys(cache.entries)) all.add(path);
+ const changed: string[] = [];
+ const entries: Record<string, string> = {};
+ for (const path of [...all].sort()) {
+ const entry = cache.entries[path];
+ if (entry !== undefined && statAt(cache.root, path) === entry) entries[path] = entry;
+ else changed.push(path);
+ }
+ return { changed, cache: { v: 1, root: cache.root, entries } };
+}
+
+/**
+ * The working level of `paths` (`probeDirtiness` with `working`, every path hashed:
+ * full rounds rehash unconditionally) and the stat cache it leaves. Each path is
+ * stat'd before and after its bytes are hashed; a path whose stat moved is
+ * discarded and rehashed, up to three attempts, and one still moving keeps its
+ * last probe but no entry. An entry is written only for a stable stat whose
+ * `mtime` and `ctime` are older than 2 s before that attempt began (a racy entry is
+ * left out, so the next pass rehashes it), and only for a probe with a level
+ * (raw bytes read, or `deleted` with nothing at the path). `afterHash` runs between
+ * the hash and the re-stat (tests inject an edit there).
+ */
+export async function hashWorkingLevel(root: string, gitRoot: string, paths: string[], tree: Map<string, GitTreeEntry>,
+ opts: { batch?: number; maxEntries?: number; afterHash?: (paths: string[]) => void | Promise<void> } = {}): Promise<{ probes: Map<string, DirtinessProbe>; cache: WorkingStatCache | null }> {
+ let realGitRoot: string | null = null;
+ try { realGitRoot = realpathSync.native(gitRoot); } catch {}
+ const statOf = (path: string) => (realGitRoot === null ? null : statAt(realGitRoot, path));
+ const probes = new Map<string, DirtinessProbe>();
+ const entries = new Map<string, string>();
+ let pending = [...new Set(paths)];
+ for (let attempt = 0; attempt < WORKING_HASH_ATTEMPTS && pending.length > 0; attempt++) {
+ const racyFrom = BigInt(Date.now()) * 1_000_000n - WORKING_RACY_WINDOW_NS;
+ const before = new Map(pending.map(path => [path, statOf(path)]));
+ const probed = await probeDirtiness(root, gitRoot, pending, tree, new Map(), { batch: opts.batch, working: true });
+ await opts.afterHash?.(pending);
+ const moved: string[] = [];
+ for (const path of pending) {
+ const probe = probed.get(path)!;
+ probes.set(path, probe);
+ const key = before.get(path)!;
+ if (statOf(path) !== key) { moved.push(path); continue; }
+ if (key === null) continue;
+ const [mtimeNs = '0', ctimeNs = '0'] = key === ABSENT ? [] : key.split(':').slice(5);
+ const vouched = key === ABSENT ? probe.dp === 'deleted' : probe.rawOid !== null && BigInt(mtimeNs) < racyFrom && BigInt(ctimeNs) < racyFrom;
+ if (vouched) entries.set(path, key);
+ }
+ pending = moved;
+ }
+ if (realGitRoot === null) return { probes, cache: null };
+ const kept = [...entries.keys()].sort().slice(0, Math.max(0, opts.maxEntries ?? WORKING_STAT_CACHE_MAX_ENTRIES));
+ return { probes, cache: { v: 1, root: realGitRoot, entries: Object.fromEntries(kept.map(path => [path, entries.get(path)!])) } };
+}
+
+/** A serialized cache (a pass row's copy), or null for anything that is not one; null reads as "everything changed". */
+export function parseWorkingStatCache(value: unknown): WorkingStatCache | null {
+ if (!value || typeof value !== 'object') return null;
+ const { v, root, entries } = value as Record<string, unknown>;
+ if (v !== 1 || typeof root !== 'string' || !entries || typeof entries !== 'object' || Array.isArray(entries)) return null;
+ const list = Object.entries(entries as Record<string, unknown>);
+ if (list.length > WORKING_STAT_CACHE_MAX_ENTRIES || !list.every(([, key]) => typeof key === 'string' && (key === ABSENT || STAT_KEY.test(key)))) return null;
+ return { v: 1, root, entries: Object.fromEntries(list) as Record<string, string> };
+}
+
+const rememberedCaches = new Map<string, WorkingStatCache>();
+
+/** Keeps a cache in this process under `key` (the pass uses `<source>:<incarnation>`); the least recently stored past 64 are dropped. */
+export function rememberWorkingStatCache(key: string, cache: WorkingStatCache): void {
+ rememberedCaches.delete(key);
+ rememberedCaches.set(key, cache);
+ while (rememberedCaches.size > WORKING_STAT_CACHES_REMEMBERED) rememberedCaches.delete(rememberedCaches.keys().next().value!);
+}
+
+/** The cache this process remembered under `key`, or null. */
+export function recallWorkingStatCache(key: string): WorkingStatCache | null {
+ return rememberedCaches.get(key) ?? null;
+}
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 3246ca7f62..27939ce08e 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -33,7 +33,7 @@ import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHo
type GitHoldRecord, type SyncImportProvenance } from './sync-holds.ts';
import { movedDriftHolds, sameParser } from './sync-prescreen.ts';
import { syncOriginPath } from './sync-origin.ts';
-import { probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, type GitTreeEntry } from './sync-git-stream.ts';
+import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, type GitTreeEntry } from './sync-git-stream.ts';
import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';
import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';
import { readManagedMode } from './ownership.ts';
@@ -292,7 +292,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
// Working mode rehashes every path (the full round's unconditional rehash); committed mode probes candidates only.
t = timer();
- const probes = mode === 'working' ? await probeDirtiness(root, gitRoot, [...domain], tree, index) : new Map();
+ const probes = mode === 'working' ? (await hashWorkingLevel(root, gitRoot, [...domain], tree)).probes : new Map();
timings.Dp = t();
const levelOf = (path: string, probe: { dp: string; rawOid: string | null } | undefined): string | null => {
diff --git a/test/hardened-git-stream-6712.test.ts b/test/hardened-git-stream-6712.test.ts
index 8c5e7f4fd1..74f87d2837 100644
--- a/test/hardened-git-stream-6712.test.ts
+++ b/test/hardened-git-stream-6712.test.ts
@@ -12,7 +12,7 @@ import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { assertHardenedGitArgs, hardenedGitStream, hardenedStreamComplete, NulRecordSplitter, type HardenedGitStreamResult } from '../src/core/hardened-git.ts';
-import { __setSyncGitStreamForTests, probeDirtiness, readBlobs, readIndexLevel, readRenameHints, readTreeLevel, SyncTreeReadIncomplete } from '../src/core/persistence/sync-git-stream.ts';
+import { __setSyncGitStreamForTests, hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readRenameHints, readTreeLevel, SyncTreeReadIncomplete } from '../src/core/persistence/sync-git-stream.ts';
const dirs: string[] = [];
afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });
@@ -281,7 +281,7 @@ describe('probeDirtiness verdicts', () => {
});
describe('forced probe: repository filters and textconv never run (design probe 28)', () => {
- test('1,000 passes of every read leave no marker, while porcelain on the same checkout leaves one', async () => {
+ test('1,000 passes of every read (working-mode hashing included) leave no marker, while porcelain on the same checkout leaves one', async () => {
const root = repo({ 'a.md': 'alpha\n', 'b.md': 'bravo\n', 'c.md': 'charlie\r\n' });
const from = git(root, 'rev-parse', 'HEAD').trim();
git(root, 'mv', 'a.md', 'renamed.md');
@@ -307,14 +307,17 @@ describe('forced probe: repository filters and textconv never run (design probe
const pass = async () => {
const tree = await readTreeLevel(root, 'HEAD', '');
const index = await readIndexLevel(root);
- const [hints, read, verdicts] = await Promise.all([readRenameHints(root, from, 'HEAD'), readBlobs(root, blobs, 1024), probeDirtiness(root, root, paths, tree, index)]);
- return { hints, read, verdicts };
+ const [hints, read, verdicts, working] = await Promise.all([readRenameHints(root, from, 'HEAD'), readBlobs(root, blobs, 1024), probeDirtiness(root, root, paths, tree, index),
+ hashWorkingLevel(root, root, paths, tree)]);
+ return { hints, read, verdicts, working: working.probes };
};
const first = await pass();
expect(first.hints).toEqual([{ from: 'a.md', to: 'renamed.md', oid: blobOid('alpha\n') }]);
expect(first.read.size).toBe(2);
expect(Object.fromEntries([...first.verdicts].map(([path, probe]) => [path, probe.dp])))
.toEqual({ 'renamed.md': 'clean', 'b.md': 'unknown', 'c.md': 'unknown', '.gitattributes': 'untracked', 'missing.md': 'untracked' });
+ expect(Object.fromEntries([...first.working].map(([path, probe]) => [path, probe.dp])))
+ .toEqual({ 'renamed.md': 'clean', 'b.md': 'unknown', 'c.md': 'unknown', '.gitattributes': 'untracked', 'missing.md': 'deleted' });
for (let done = 1; done < 1000; done += 8) await Promise.all(Array.from({ length: Math.min(8, 1000 - done) }, pass));
expect(ran()).toEqual([]);
diff --git a/test/sync-working-level-6712.test.ts b/test/sync-working-level-6712.test.ts
new file mode 100644
index 0000000000..8983460a29
--- /dev/null
+++ b/test/sync-working-level-6712.test.ts
@@ -0,0 +1,101 @@
+/**
+ * #6712 PR 4b (design v3.2 §2.1), probe 41: in working mode the level of a path is the bytes on disk (or absent), whatever the index says. A staged
+ * edit, a staged new file, `git rm --cached`, a staged deletion and a staged file removed from disk all read the disk,
+ * in the `clean_eol`/`clean_lfs` domains. The index only feeds committed mode's `Dp` categories.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { shadowConvergence } from '../src/core/persistence/sync-pass.ts';
+import { probeDirtiness, readIndexLevel, readTreeLevel } from '../src/core/persistence/sync-git-stream.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const dirs: string[] = [];
+afterAll(() => { 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 | Buffer) => createHash('sha1').update(`blob ${Buffer.byteLength(content)}\0`).update(content).digest('hex');
+const sha256 = (content: string | Buffer) => createHash('sha256').update(content).digest('hex');
+
+function repo(files: Record<string, string | Buffer>, attributes?: string): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-working-level-'));
+ dirs.push(root);
+ git(root, 'init', '-q');
+ git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'user.name', 'Writer Example');
+ if (attributes) writeFileSync(join(root, '.gitattributes'), attributes);
+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);
+ git(root, 'add', '-A');
+ git(root, 'commit', '-qm', 'init');
+ return root;
+}
+
+async function workingProbe(root: string, paths: string[]) {
+ return probeDirtiness(root, root, paths, await readTreeLevel(root, 'HEAD', ''), await readIndexLevel(root), { working: true });
+}
+
+describe('probe 41: the working level is the disk bytes, whatever the index says', () => {
+ test('every staged shape probes exactly as the same disk does with a pristine index', async () => {
+ const content = Buffer.from('large binary payload\n'.repeat(40));
+ const pointer = `version https://git-lfs.github.com/spec/v1\noid sha256:${sha256(content)}\nsize ${content.length}\n`;
+ const root = repo({ 'edit.md': 'old\n', 'cached.md': 'c\n', 'removed.md': 'r\n', 'eol.md': 'a\nb\n', 'big.bin': pointer, 'back.md': 'back\n' },
+ 'eol.md text\n*.bin filter=lfs -text\n');
+ writeFileSync(join(root, 'edit.md'), 'staged edit\n');
+ writeFileSync(join(root, 'added.md'), 'added\n');
+ writeFileSync(join(root, 'vanished.md'), 'vanished\n');
+ git(root, 'add', 'edit.md', 'added.md', 'vanished.md');
+ unlinkSync(join(root, 'vanished.md'));
+ git(root, 'rm', '-q', '--cached', 'cached.md');
+ git(root, 'rm', '-q', 'removed.md');
+ writeFileSync(join(root, 'eol.md'), 'a\r\nb\r\n');
+ writeFileSync(join(root, 'big.bin'), content);
+ git(root, 'update-index', '--chmod=+x', 'eol.md', 'big.bin');
+ writeFileSync(join(root, 'back.md'), 'staged then reverted\n');
+ git(root, 'add', 'back.md');
+ writeFileSync(join(root, 'back.md'), 'back\n');
+ const paths = ['edit.md', 'added.md', 'vanished.md', 'cached.md', 'removed.md', 'eol.md', 'big.bin', 'back.md', 'never.md'];
+
+ const staged = await workingProbe(root, paths);
+ git(root, 'reset', '-q');
+ const pristine = await workingProbe(root, paths);
+ for (const path of paths) expect([path, staged.get(path)]).toEqual([path, pristine.get(path)]);
+ expect(Object.fromEntries([...staged].map(([path, probe]) => [path, probe.dp]))).toEqual({
+ 'edit.md': 'modified', 'added.md': 'untracked', 'vanished.md': 'deleted', 'cached.md': 'clean', 'removed.md': 'deleted',
+ 'eol.md': 'clean_eol', 'big.bin': 'clean_lfs', 'back.md': 'clean', 'never.md': 'deleted' });
+ expect(staged.get('edit.md')).toEqual({ dp: 'modified', rawOid: blobOid('staged edit\n'), rawSha256: sha256('staged edit\n') });
+ expect(staged.get('added.md')).toEqual({ dp: 'untracked', rawOid: blobOid('added\n'), rawSha256: sha256('added\n') });
+ expect(staged.get('vanished.md')).toEqual({ dp: 'deleted', rawOid: null, rawSha256: null });
+ });
+
+ const note = (title: string, body: string) => `---\ntitle: ${title}\n---\n\n${body}\n`;
+ const setup = ({ root }: { root: string }) => {
+ git(root, 'init', '-q');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, '.gitattributes'), 'notes/eol.md text\n');
+ for (const name of ['alpha', 'beta', 'gamma', 'eol']) writeFileSync(join(root, 'notes', name + '.md'), note(name, 'Synthetic ' + name + ' one.'));
+ git(root, 'add', '.');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ };
+
+ test('a managed pass classifies a staged deletion as a delete, a staged file gone from disk as gone, and a CRLF file as matched', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes', 'alpha.md'), note('alpha', 'A staged edit.'));
+ git(root, 'add', 'notes/alpha.md');
+ git(root, 'rm', '-q', 'notes/beta.md');
+ writeFileSync(join(root, 'notes', 'zeta.md'), note('zeta', 'Staged, then removed from disk.'));
+ git(root, 'add', 'notes/zeta.md');
+ unlinkSync(join(root, 'notes', 'zeta.md'));
+ writeFileSync(join(root, 'notes', 'eol.md'), note('eol', 'Synthetic eol one.').replaceAll('\n', '\r\n'));
+ git(root, 'update-index', '--chmod=+x', 'notes/eol.md');
+ const receipt = (await shadowConvergence(engine, { sourceId: 'default', workingTree: true }))!;
+ expect(receipt.mode).toBe('working');
+ expect(receipt.counts).toEqual({ matched: 2, import: 1, delete: 1, gone: 1 });
+ expect(receipt.samples.import!.map(sample => sample.path)).toEqual(['notes/alpha.md']);
+ expect(receipt.samples.delete!.map(sample => sample.path)).toEqual(['notes/beta.md']);
+ }, { setup }), 120_000);
+});
diff --git a/test/sync-working-stat-cache-6712.test.ts b/test/sync-working-stat-cache-6712.test.ts
new file mode 100644
index 0000000000..a83265697d
--- /dev/null
+++ b/test/sync-working-stat-cache-6712.test.ts
@@ -0,0 +1,134 @@
+/**
+ * #6712 PR 4b (design v3.2 §2.1): the working stat cache follows Git's freshness contract (key dev, ino, mode, uid,
+ * size, mtime_ns, ctime_ns; racy entries rehashed; hash-then-restat; uncertainty is a change). Probe 42: a same-inode, same-size edit with a restored `mtime` on a warm
+ * cache, and an edit while the file is hashed, are both seen by the next working pass.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { closeSync, mkdtempSync, openSync, rmSync, statSync, symlinkSync, unlinkSync, utimesSync, writeFileSync, writeSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { hashWorkingLevel, parseWorkingStatCache, readTreeLevel, recallWorkingStatCache, rememberWorkingStatCache,
+ workingChanged, workingStatKey, type WorkingStatCache } from '../src/core/persistence/sync-git-stream.ts';
+
+const dirs: string[] = [];
+afterAll(() => { 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 | Buffer) => createHash('sha1').update(`blob ${Buffer.byteLength(content)}\0`).update(content).digest('hex');
+const sha256 = (content: string | Buffer) => createHash('sha256').update(content).digest('hex');
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+/** Past Git's 2 s racy window, so entries written now are trusted on the next pass. */
+const RACY_WAIT_MS = 2_100;
+
+function repo(files: Record<string, string | Buffer>, attributes?: string): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-working-level-'));
+ dirs.push(root);
+ git(root, 'init', '-q');
+ git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'user.name', 'Writer Example');
+ if (attributes) writeFileSync(join(root, '.gitattributes'), attributes);
+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);
+ git(root, 'add', '-A');
+ git(root, 'commit', '-qm', 'init');
+ return root;
+}
+
+/** Overwrites `path` in place (same inode, same size) and restores its atime and mtime to whole seconds `at`. */
+function sameSizeEdit(path: string, content: string, at: number): void {
+ const fd = openSync(path, 'r+');
+ try { writeSync(fd, content, 0); } finally { closeSync(fd); }
+ utimesSync(path, at, at);
+}
+
+describe('probe 42: the working stat cache follows Git\'s freshness contract', () => {
+ const past = Math.floor(Date.now() / 1000) - 3600;
+
+ test('a same-inode, same-size edit with a restored mtime on a warm cache is a change', async () => {
+ const root = repo({ 'a.md': 'alpha one\n', 'b.md': 'bravo\n' });
+ utimesSync(join(root, 'a.md'), past, past);
+ await sleep(RACY_WAIT_MS);
+ const tree = await readTreeLevel(root, 'HEAD', '');
+ const { cache } = await hashWorkingLevel(root, root, ['a.md', 'b.md', 'gone.md'], tree);
+ expect(Object.keys(cache!.entries).sort()).toEqual(['a.md', 'b.md', 'gone.md']);
+ expect(workingChanged(cache, ['a.md', 'b.md', 'gone.md']).changed).toEqual([]);
+
+ const before = statSync(join(root, 'a.md'), { bigint: true });
+ sameSizeEdit(join(root, 'a.md'), 'alpha two\n', past);
+ const after = statSync(join(root, 'a.md'), { bigint: true });
+ expect([after.ino, after.size, after.mtimeNs]).toEqual([before.ino, before.size, before.mtimeNs]);
+ expect(after.ctimeNs).not.toBe(before.ctimeNs);
+ const next = workingChanged(cache, ['a.md', 'b.md', 'gone.md']);
+ expect(next.changed).toEqual(['a.md']);
+ expect(Object.keys(next.cache!.entries).sort()).toEqual(['b.md', 'gone.md']);
+ const rehashed = await hashWorkingLevel(root, root, next.changed, tree);
+ expect(rehashed.probes.get('a.md')).toEqual({ dp: 'modified', rawOid: blobOid('alpha two\n'), rawSha256: sha256('alpha two\n') });
+ }, 30_000);
+
+ test('an edit while the file is hashed is rehashed in the pass and never cached as the old bytes', async () => {
+ const root = repo({ 'a.md': 'alpha one\n' });
+ utimesSync(join(root, 'a.md'), past, past);
+ await sleep(RACY_WAIT_MS);
+ const tree = await readTreeLevel(root, 'HEAD', '');
+ let edits = 0;
+ const once = await hashWorkingLevel(root, root, ['a.md'], tree, { afterHash: () => { if (edits++ === 0) sameSizeEdit(join(root, 'a.md'), 'alpha two\n', past); } });
+ expect(edits).toBe(2);
+ expect(once.probes.get('a.md')).toEqual({ dp: 'modified', rawOid: blobOid('alpha two\n'), rawSha256: sha256('alpha two\n') });
+ expect(workingChanged(once.cache, ['a.md']).changed).toEqual(['a.md']);
+
+ let n = 0;
+ const always = await hashWorkingLevel(root, root, ['a.md'], tree, { afterHash: () => { sameSizeEdit(join(root, 'a.md'), n++ % 2 ? 'alpha one\n' : 'alpha six\n', past); } });
+ expect(n).toBe(3);
+ expect(always.cache!.entries['a.md']).toBeUndefined();
+ expect(workingChanged(always.cache, ['a.md']).changed).toEqual(['a.md']);
+ }, 30_000);
+
+ test('a racy entry is rehashed on the next pass; once it ages past the window the cache trusts it', async () => {
+ const root = repo({ 'a.md': 'alpha\n' });
+ writeFileSync(join(root, 'a.md'), 'alpha now\n');
+ const tree = await readTreeLevel(root, 'HEAD', '');
+ const fresh = await hashWorkingLevel(root, root, ['a.md'], tree);
+ expect(fresh.cache!.entries['a.md']).toBeUndefined();
+ expect(workingChanged(fresh.cache, ['a.md']).changed).toEqual(['a.md']);
+ await sleep(RACY_WAIT_MS);
+ const aged = await hashWorkingLevel(root, root, ['a.md'], tree);
+ expect(aged.cache!.entries['a.md']).toBeDefined();
+ expect(workingChanged(aged.cache, ['a.md']).changed).toEqual([]);
+ }, 30_000);
+
+ test('new, vanished, replaced and unstat-able paths are changes; uncertainty is never "no change"', async () => {
+ const root = repo({ 'a.md': 'alpha\n', 'b.md': 'bravo\n', 'c.md': 'charlie\n' });
+ for (const name of ['a.md', 'b.md', 'c.md']) utimesSync(join(root, name), past, past);
+ await sleep(RACY_WAIT_MS);
+ const { cache } = await hashWorkingLevel(root, root, ['a.md', 'b.md', 'c.md', 'gone.md'], await readTreeLevel(root, 'HEAD', ''));
+ unlinkSync(join(root, 'b.md'));
+ writeFileSync(join(root, 'gone.md'), 'back\n');
+ unlinkSync(join(root, 'c.md'));
+ symlinkSync('a.md', join(root, 'c.md'));
+ expect(workingChanged(cache, ['a.md', 'new.md', 'a.md/inside']).changed).toEqual(['a.md/inside', 'b.md', 'c.md', 'gone.md', 'new.md']);
+ expect(workingChanged(null, ['a.md']).changed).toEqual(['a.md']);
+ expect(parseWorkingStatCache({ v: 1, root, entries: { 'a.md': 7 } })).toBeNull();
+ expect(parseWorkingStatCache('junk')).toBeNull();
+ expect(parseWorkingStatCache(JSON.parse(JSON.stringify(cache)))).toEqual(cache);
+ expect(workingChanged({ ...cache!, root: join(root, 'elsewhere') }, ['a.md']).changed).toEqual(['a.md']);
+ const stats = statSync(join(root, 'a.md'), { bigint: true });
+ expect(workingStatKey(stats)).toMatch(/^\d+:\d+:\d+:\d+:\d+:\d+:\d+$/);
+ expect(workingStatKey({ ...stats, ctimeNs: 0n })).toBeNull();
+ expect(workingStatKey(null)).toBeNull();
+ }, 30_000);
+
+ test('the cache is bounded, JSON-able, and remembered per process', async () => {
+ const files = Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`n${i}.md`, `note ${i}\n`]));
+ const root = repo(files);
+ for (const name of Object.keys(files)) utimesSync(join(root, name), past, past);
+ await sleep(RACY_WAIT_MS);
+ const { cache } = await hashWorkingLevel(root, root, Object.keys(files), await readTreeLevel(root, 'HEAD', ''), { maxEntries: 4 });
+ expect(Object.keys(cache!.entries)).toEqual(['n0.md', 'n1.md', 'n2.md', 'n3.md']);
+ expect(workingChanged(cache, Object.keys(files)).changed).toEqual(['n4.md', 'n5.md']);
+ rememberWorkingStatCache('default:1', cache!);
+ expect(recallWorkingStatCache('default:1')).toEqual(cache as WorkingStatCache);
+ expect(recallWorkingStatCache('default:2')).toBeNull();
+ }, 30_000);
+});