Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytande9eb9dd86fb
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 315deb7a00..e541fd9287 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1823,7 +1823,7 @@ More: [docs/guides/write-refusals.md#git_protocol_required](../../docs/guides/wr| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published. | The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is. | Retry the write with a new request_id once the file has settled. | agent | `repeat the read that failed` | 1 | no |+| A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published. | The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is. | The write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it. Preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then apply --keep disk (the edit) or --keep prior with the preview's --expect hash. | agent | `repeat the read that failed` | 1 | no |### git_target_ignoreddiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 720a571589..0473d6f847 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1313,9 +1313,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.465.0', text: 'On a managed brain, `gbrain trust release h<id>` of a held fact whose entity page exists now writes the fact into that page\'s `## Facts` fence through the page-write door (a `trust_release` page write) and flips the hold in the same publication, so the released fact lives in the page\'s file and a re-import keeps it. Before, the release inserted a database-only row the file never held; a fence-guard hold that names an existing fence row created a database-only twin of it, and now indexes that row and leaves the file unchanged. The row is stamped `user_confirmed` with origin `trust_release` and the page keeps its trust tier. A hold decided after the release was accepted fails `preview_changed` and writes nothing; a remote request, or a deleted or private entity page, refuses and the fact stays held. A hold with no entity page, and unmanaged brains, release database-only as before.' },{ since: '0.60.467.0', id: 'cli_flag_equals', text: 'A CLI flag value written with `=` that a command used to ignore now exits 2 (`invalid_params`) and names the two-argument spelling the command reads: `gbrain auth create --scopes=read` minted a full-access token. A switch never takes a value (`--yes=n`, `--dry-run=true`, `--apply=false` and `-y=n` exit 2 instead of being ignored). The `=` spellings a command reads on every path keep working, and so do the spending cap and plan hash the consent check of a command reads; a few that only some paths read now exit 2 with the two-argument fix, among them the source id given that way to `gbrain extract` for stale extraction, the checkout path given that way to the database-free `gbrain sources pull`, and the values given that way to the managed `gbrain sources` lifecycle subcommands (add, remove, archive, restore, purge, set-path, reclone). A value written with `=` on a flag that the help of the command declares used to be ignored and now applies, so check scripts that pass these that way: an all-interfaces bind address given to `gbrain serve` bound loopback and now listens on every interface; a public URL given to `gbrain serve` now sets the OAuth issuer and resource, so clients authorized under the old localhost issuer must reconnect, and admin cookies become Secure on https; the serve port, token lifetime and stdio idle timeout, the sync interval, source and repository, the import worker count, the autopilot install repository and supervisor, and the target engine and URL the legacy `gbrain migrate` copier reads take effect the same way; a spend cap given to `gbrain onboard` (off included) now applies, and one given to a resumed `gbrain doctor` remediation overrides the cap its checkpoint recorded; and `gbrain apply-migrations` now honors an accepted reviewed inventory and a forced retry of a wedged migration. An upgrade restart of a `gbrain jobs supervisor` started with values written that way (which it ignored) starts it again without them. A script that passes a value with `=` to a command that does not read that form now stops with the fix instead of running without the value.' },// Bun floor 1.4.4 (#7644, #7596). `since` is stamped at the merge slot.+ { since: '0.60.468.0', id: 'bun_floor_1_4_4', text: 'GBrain now requires Bun 1.4.4 or newer (previously 1.4.0). On Bun 1.4.0 to 1.4.3 every command except `gbrain --version` exits 1 before it starts with `GBrain requires Bun 1.4.4 or newer (found Bun <version>)` and the fix (`bun upgrade`, then restart GBrain; `gbrain post-upgrade` finishes an interrupted upgrade); `--version` prints the same refusal and exits 0. On Bun 1.4.0 to 1.4.2 a postgres.js connection over TLS keeps every chunk it receives, so a full sync or conversion pass over a TLS Postgres or pooler grew by about the bytes it read until memory guards killed it (#7644, #7596); 1.4.4 also carries the Brotli fix for CVE-2026-111497. Standalone gbrain binaries already embed Bun 1.4.4; a source or `bun install` install runs `bun upgrade` first, and `gbrain upgrade` on an older host Bun stops (autopilot holds) with the same fix.' },// #7705 (strict door planned state). `since` is stamped at the merge slot.{ since: '0.60.469.0', id: 'door_planned_state', text: 'On a source with `canonical: git`, a page write now commits exactly the bytes it published, or nothing. A file edited on disk while the write was publishing refuses `git_target_changed`: nothing is committed, the edit stays on disk and the source\'s writes pause until `gbrain repair stuck-recovery` resolves it (before, Git committed the edit while the database recorded the write\'s content). A staged change of the page\'s file refuses `git_index_conflict`, with the index untouched; commit or unstage it, then retry (before, the write replaced the staged change in the index). When the index still holds the version from before an earlier gbrain commit whose index update failed, the next write restores it and says so with a `git_index_restored` notice.' },- { since: '0.60.468.0', id: 'bun_floor_1_4_4', text: 'GBrain now requires Bun 1.4.4 or newer (previously 1.4.0). On Bun 1.4.0 to 1.4.3 every command except `gbrain --version` exits 1 before it starts with `GBrain requires Bun 1.4.4 or newer (found Bun <version>)` and the fix (`bun upgrade`, then restart GBrain; `gbrain post-upgrade` finishes an interrupted upgrade); `--version` prints the same refusal and exits 0. On Bun 1.4.0 to 1.4.2 a postgres.js connection over TLS keeps every chunk it receives, so a full sync or conversion pass over a TLS Postgres or pooler grew by about the bytes it read until memory guards killed it (#7644, #7596); 1.4.4 also carries the Brotli fix for CVE-2026-111497. Standalone gbrain binaries already embed Bun 1.4.4; a source or `bun install` install runs `bun upgrade` first, and `gbrain upgrade` on an older host Bun stops (autopilot holds) with the same fix.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5bf6bdeae5..0f74d98824 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -329,7 +329,7 @@ export const CODES = {git_target_pending: { class: 'retryable', summary: "Git still lists a removed canonical file in the index; the removal was not committed yet." },git_operation_in_progress: { class: 'caller', summary: "A rebase, merge, cherry-pick or revert is in progress in the checkout, so gbrain will not commit or move it.", docs: 'docs/guides/shared-checkout-git.md#stuck-rebase' },git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },- git_target_changed: { class: 'caller', summary: "A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published.", why: "The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is.", suggestion: 'Retry the write with a new request_id once the file has settled.' },+ git_target_changed: { class: 'caller', summary: "A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published.", why: "The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is.", suggestion: "The write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it. Preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then apply --keep disk (the edit) or --keep prior with the preview's --expect hash." },git_target_ignored: { class: 'caller', summary: "A .gitignore rule excludes the canonical file, so its Git effect cannot commit it; the effect parks at once.", suggestion: 'Remove or narrow the rule and commit that change, then run gbrain sources writer retry-effects <source> --parked-code git_target_ignored; or keep the file out of Git and leave the effect parked.' },git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 8ba3141d88..dcd7a87e73 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -20,8 +20,9 @@* and after `hash-object -w` stores it (an edit landing during the write refuses `git_target_changed`), and each* target's index entry must equal HEAD's before the commit is built (a staged change of a target refuses* `git_index_conflict`, index untouched). After the branch moves, an entry someone staged meanwhile is left as it is- * and the write reports that its commit landed. An entry still holding HEAD's first parent's version at that path counts- * as clean: it is what an interrupted refresh after the door's own commit leaves, and its bytes are in history, so the+ * and the write reports that its commit landed. An entry still holding the version the path's last commit replaced counts+ * as clean, whatever commits of other paths landed since: it is what an interrupted refresh after the door's own commit+ * leaves, and its bytes are in history, so the* next write (or a replay whose blob HEAD already holds) refreshes it and reports the paths (`onIndexRestored`, the* `git_index_restored` notice); any other staged entry refuses `git_index_conflict`.*@@ -286,8 +287,8 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],const indexed = await readIndex(session, index, [...targets.values()]);const staged = [...targets.values()].filter(target => indexed.entries.get(target.rel) !== target.head);if (staged.length) {- const parent = await parentEntries(session, head, staged);- const foreign = staged.filter(target => indexed.entries.get(target.rel) !== parent.get(target.rel));+ const replaced = await replacedEntries(session, head, staged);+ const foreign = staged.filter(target => indexed.entries.get(target.rel) !== replaced.get(target.rel));if (foreign.length) throw indexConflict(root, foreign);}const restored = () => { if (staged.length) onIndexRestored?.(staged.map(target => target.rel)); };@@ -366,10 +367,10 @@ function refuseChanged(root: string, targets: Iterable<Target>): void {const moved = [...targets].filter(target => { try { return hashFile(join(root, target.rel)) !== target.planned; } catch { return true; } }).map(target => target.rel);if (!moved.length) return;throw opError('git_target_changed', `${moved.join(', ')} in ${root} no longer holds the bytes this write published, so nothing was committed and the write was not published.`,- 'Another process changed the file during the write; recovery leaves the changed file as it is. Retry the write with a new request_id once the file has settled.', { detail: moved.join(',') });+ 'Another process changed the file during the write; recovery leaves the changed file as it is and holds the write, so the source\'s later writes wait. Preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then apply --keep disk or --keep prior with the preview\'s --expect hash.', { detail: moved.join(',') });}-/** Targets whose index entry differs from HEAD's and from its first parent's (a staged change, or a merge conflict) refuse as `git_index_conflict`. */+/** Targets whose index entry differs from HEAD's and from the version their path's last commit replaced (a staged change, or a merge conflict) refuse as `git_index_conflict`. */function indexConflict(root: string, staged: Target[]): OperationError {const paths = staged.map(target => target.rel);return opError('git_index_conflict', `${paths.join(', ')} in ${root} has a staged change that is not committed, so this write committed nothing and the index was left as it was.`,@@ -402,16 +403,25 @@ async function readIndex(session: GitSession, index: string, targets: Target[]):return { signature, entries };}-/** The blob entries of the targets in `commit`'s first parent (none when it has no parent). */-async function parentEntries(session: GitSession, commit: string, targets: Target[]): Promise<Map<string, string>> {- const listed = await git(session, ['ls-tree', '-z', `${commit}^`, '--', ...targets.map(target => target.rel)]);+/**+ * Each target's blob entry as it was before the last commit reachable from `commit` that changed its path (none when that+ * commit added it, or the path was never committed): what the index still holds when that commit's refresh failed,+ * whatever commits touching other paths landed since.+ */+async function replacedEntries(session: GitSession, commit: string, targets: Target[]): Promise<Map<string, string>> {const entries = new Map<string, string>();- if (listed.code !== 0) return entries;- for (const record of listed.stdout.split('\0')) {- const tab = record.indexOf('\t');- if (tab < 0) continue;- const [mode, type, oid] = record.slice(0, tab).split(' ');- if (type === 'blob') entries.set(record.slice(tab + 1), `${mode} ${oid}`);+ for (const target of targets) {+ const last = await git(session, ['rev-list', '-1', commit, '--', target.rel]);+ const changed = last.stdout.trim();+ if (last.code !== 0 || !changed) continue;+ const listed = await git(session, ['ls-tree', '-z', `${changed}^`, '--', target.rel]);+ if (listed.code !== 0) continue;+ for (const record of listed.stdout.split('\0')) {+ const tab = record.indexOf('\t');+ if (tab < 0) continue;+ const [mode, type, oid] = record.slice(0, tab).split(' ');+ if (type === 'blob' && record.slice(tab + 1) === target.rel) entries.set(target.rel, `${mode} ${oid}`);+ }}return entries;}diff --git a/test/git-door-planned-state.test.ts b/test/git-door-planned-state.test.tsindex f2a0b3d93c..92df83539d 100644--- a/test/git-door-planned-state.test.ts+++ b/test/git-door-planned-state.test.ts@@ -43,6 +43,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { runRepairCommand } from '../src/commands/repair.ts';import { maintenancePreflight, publishMaintenancePages } from '../src/core/persistence/prepared-maintenance.ts';import { durableGitRepo } from './helpers/git-publication.ts';+import { withEnv } from './helpers/with-env.ts';import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -318,6 +319,47 @@ describe('door plumbing: the planned state', () => {expect(git(root, 'status', '--porcelain')).toBe('');});+ test('a file rewritten while hash-object stores it refuses git_target_changed, with nothing committed or staged', async () => {+ const root = repo({ 'notes/a.md': 'a\n' });+ const head = git(root, 'rev-parse', 'HEAD');+ const bin = mkdtempSync(join(tmpdir(), 'gbrain-git-shim-'));+ roots.push(bin);+ const real = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();+ writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase " $* " in *" hash-object -w "*) printf 'edited during hash\\n' > '${join(root, 'notes/a.md')}';; esac\nexec '${real}' "$@"\n`, { mode: 0o755 });+ put(root, 'notes/a.md', 'planned\n');+ await withEnv({ PATH: `${bin}:${process.env.PATH}` }, async () => {+ expect(await refusal(commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('planned\n') }]))).toMatchObject({ code: 'git_target_changed' });+ });+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toBe('edited during hash\n');+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(git(root, 'diff', '--cached', '--name-only')).toBe('');+ });++ test('a stale entry the door left still counts as its own after other commits land, and the next write to that path restores it', async () => {+ const root = repo({ 'notes/a.md': 'a\n', 'notes/q.md': 'q\n', 'other.md': 'o\n' });+ const lock = join(root, '.git', 'index.lock');+ doorSeams.beforeUpdateRef = () => { writeFileSync(lock, ''); };+ put(root, 'notes/a.md', 'first\n'); put(root, 'notes/new.md', 'first new\n');+ const landed = await refusal(commitThroughDoor(root, ['notes/a.md', 'notes/new.md'].map(path => ({ path: join(root, path), planned: sha256(readFileSync(join(root, path))) }))));+ rmSync(lock);+ delete doorSeams.beforeUpdateRef;+ expect(landed).toMatchObject({ code: 'git_unavailable', message: expect.stringContaining('landed, but the index') });+ const stale = git(root, 'rev-parse', 'HEAD^:notes/a.md');+ put(root, 'notes/q.md', 'q door\n');+ await commitThroughDoor(root, [{ path: join(root, 'notes/q.md'), planned: sha256('q door\n') }]);+ put(root, 'other.md', 'o human\n');+ git(root, '-c', 'commit.gpgsign=false', 'commit', '-qm', 'Human edit', '--', 'other.md');+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(stale);+ expect(git(root, 'ls-files', '--', 'notes/new.md')).toBe('');+ put(root, 'notes/a.md', 'second\n'); put(root, 'notes/new.md', 'second new\n');+ const restored: string[][] = [];+ const commit = await commitThroughDoor(root, ['notes/a.md', 'notes/new.md'].map(path => ({ path: join(root, path), planned: sha256(readFileSync(join(root, path))) })), undefined, paths => restored.push(paths));+ expect(restored).toEqual([['notes/a.md', 'notes/new.md']]);+ expect(commit).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(git(root, 'show', 'HEAD:notes/a.md')).toBe('second');+ expect(git(root, 'status', '--porcelain')).toBe('');+ });+test('a commit already at HEAD refreshes an entry holding the parent\'s version and refuses any other staged entry', async () => {const root = repo({ 'notes/a.md': 'a\n' });const commit = await publishAt(root, 'notes/a.md', 'door\n');diff --git a/test/git-door-write-cost.test.ts b/test/git-door-write-cost.test.tsindex 43fae3f0be..b3620bd491 100644--- a/test/git-door-write-cost.test.ts+++ b/test/git-door-write-cost.test.ts@@ -43,12 +43,17 @@ import { requirePostgresTestDatabase, testBackends } from './helpers/test-backenimport { waitFor } from './helpers/wait-for.ts';import { withEnv } from './helpers/with-env.ts';-const env = gitChildEnv();-const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env }).trim();+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: gitChildEnv() }).trim();const lines = (text: string) => text.split('\n').filter(Boolean);const OLD = new Date('2001-01-01T00:00:00Z');const roots: string[] = [];afterEach(() => { delete doorSeams.beforeUpdateRef; resetIgnoreCandidatesForTests(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });+/** Keeps the developer's global and system Git config and global ignore file out of the test: the filter reads what Git reads. */+const hermetic = (fn: () => unknown) => () => {+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-git-config-')));+ roots.push(home);+ return withEnv({ XDG_CONFIG_HOME: home, GIT_CONFIG_GLOBAL: join(home, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' }, async () => { await fn(); });+};/** A repository on branch main whose files and index are at rest (no racily clean entry). */function repo(files: Record<string, string>): string {@@ -80,7 +85,7 @@ async function traced(root: string, work: () => Promise<unknown>): Promise<strin}describe('door write cost', () => {- test('a new file no rule could match runs no check-ignore and one update-index; one a rule could match asks check-ignore', async () => {+ test('a new file no rule could match runs no check-ignore and one update-index; one a rule could match asks check-ignore', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n', '.gitignore': 'scratch/\nnotes/odd-*\n!notes/odd-kept.md\n' });put(root, 'notes/warm.md', 'warm\n');await door(root, 'notes/warm.md');@@ -95,9 +100,9 @@ describe('door write cost', () => {expect(asked.filter(cmd => cmd === 'check-ignore')).toHaveLength(1);expect(git(root, 'show', 'HEAD:notes/odd-kept.md')).toBe('odd');expect(git(root, 'status', '--porcelain')).toBe('');- });+ }));- test('an ignored new file still refuses through a nested .gitignore, info/exclude and core.excludesFile, naming the rule', async () => {+ test('an ignored new file still refuses through a nested .gitignore, info/exclude and core.excludesFile, naming the rule', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n', 'notes/.gitignore': 'private-*\n' });writeFileSync(join(root, '.git', 'info', 'exclude'), 'local/\n');const excludes = join(root, '.git', 'personal-excludes');@@ -110,9 +115,9 @@ describe('door write cost', () => {expect(git(root, 'rev-parse', 'HEAD')).toBe(head);expect(git(root, 'ls-files', '--', path)).toBe('');}- });+ }));- test('a .gitignore edited between writes, or carried by the same publication, is classified against its new rules', async () => {+ test('a .gitignore edited between writes, or carried by the same publication, is classified against its new rules', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n', '.gitignore': 'scratch/\n' });put(root, 'notes/later-1.md', 'one\n');await door(root, 'notes/later-1.md');@@ -127,9 +132,9 @@ describe('door write cost', () => {put(root, 'notes/sibling.md', 'sibling\n');expect(await refusal(door(root, '.gitignore', 'notes/sibling.md'))).toMatchObject({ code: 'git_target_ignored' });expect(git(root, 'rev-parse', 'HEAD')).toBe(head);- });+ }));- test('removals and renames commit exactly their paths while other files are dirty, staged or untracked; the bit survives', async () => {+ test('removals and renames commit exactly their paths while other files are dirty, staged or untracked; the bit survives', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n', 'notes/old.md': 'old\n', 'notes/gone.md': 'gone\n', 'bin/tool.md': 'tool\n', 'other/dirty.md': 'dirty\n', 'other/staged.md': 'staged\n' });chmodSync(join(root, 'bin/tool.md'), 0o755); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'executable');put(root, 'other/dirty.md', 'dirty, edited\n');@@ -148,9 +153,9 @@ describe('door write cost', () => {expect(git(root, 'status', '--porcelain')).toBe(before);expect(git(root, 'diff', '--cached', '--name-only')).toBe('other/staged.md');expect(git(root, 'show', 'HEAD:other/staged.md')).toBe('staged');- });+ }));- test('the staged index entry is the hashed oid, not a refresh: bytes changed after staging show as modified', async () => {+ test('the staged index entry is the hashed oid, not a refresh: bytes changed after staging show as modified', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n' });put(root, 'notes/a.md', 'hashed\n');put(root, 'notes/new.md', 'hashed new\n');@@ -161,9 +166,9 @@ describe('door write cost', () => {for (const path of ['notes/a.md', 'notes/new.md']) expect(git(root, 'ls-files', '-s', '--', path).split(' ')[1]).toBe(git(root, 'rev-parse', `${commit}:${path}`));expect(lines(git(root, 'status', '--porcelain')).map(line => line.trim()).sort()).toEqual(['M notes/a.md', 'M notes/new.md']);expect(git(root, 'diff', '--cached', '--name-only')).toBe('');- });+ }));- test('external git commits under the checkout writer lock never lose a door commit or its index entry', async () => {+ test('external git commits under the checkout writer lock never lose a door commit or its index entry', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n' });const lockPath = `${root}-writer.lock`;roots.push(lockPath);@@ -177,8 +182,8 @@ describe('door write cost', () => {for (let i = 0; i < 8; i++) {put(root, `outside/o${i}.md`, `outside ${i}\n`);await underLock(async () => {- await run('git', ['-C', root, 'add', '--', `outside/o${i}.md`], { env, timeout: 20_000 });- await run('git', ['-C', root, 'commit', '-q', '-m', `outside ${i}`, '--', `outside/o${i}.md`], { env, timeout: 20_000 });+ await run('git', ['-C', root, 'add', '--', `outside/o${i}.md`], { env: gitChildEnv(), timeout: 20_000 });+ await run('git', ['-C', root, 'commit', '-q', '-m', `outside ${i}`, '--', `outside/o${i}.md`], { env: gitChildEnv(), timeout: 20_000 });});}})();@@ -194,9 +199,9 @@ describe('door write cost', () => {expect(lines(git(root, 'ls-tree', '-r', '--name-only', 'HEAD')).filter(path => path !== 'notes/a.md').sort()).toEqual(paths);expect(lines(git(root, 'ls-files')).filter(path => path !== 'notes/a.md').sort()).toEqual(paths);expect(git(root, 'status', '--porcelain')).toBe('');- }, 60_000);+ }), 60_000);- test('raw git commits racing door commits without the writer lock never lose a commit or corrupt the index', async () => {+ test('raw git commits racing door commits without the writer lock never lose a commit or corrupt the index', hermetic(async () => {const root = repo({ 'notes/a.md': 'a\n' });const run = promisify(execFile);const landed: string[] = [], external: string[] = [], refused: { path: string; message: string }[] = [];@@ -204,8 +209,8 @@ describe('door write cost', () => {for (let i = 0; i < 8; i++) {put(root, `outside/o${i}.md`, `outside ${i}\n`);try {- await run('git', ['-C', root, 'add', '--', `outside/o${i}.md`], { env, timeout: 20_000 });- await run('git', ['-C', root, 'commit', '-q', '-m', `outside ${i}`, '--', `outside/o${i}.md`], { env, timeout: 20_000 });+ await run('git', ['-C', root, 'add', '--', `outside/o${i}.md`], { env: gitChildEnv(), timeout: 20_000 });+ await run('git', ['-C', root, 'commit', '-q', '-m', `outside ${i}`, '--', `outside/o${i}.md`], { env: gitChildEnv(), timeout: 20_000 });external.push(`outside/o${i}.md`);} catch { /* the door held index.lock or moved the branch; this commit is skipped */ }}@@ -229,7 +234,7 @@ describe('door write cost', () => {if (status === 'A') expect(path!.startsWith('outside/') && !external.includes(path!)).toBe(true);else expect({ status, doorCommitInHead: inHead.includes(path!) }).toEqual({ status: 'D', doorCommitInHead: true });}- }, 60_000);+ }), 60_000);});const putPage = operations.find(op => op.name === 'put_page')!;@@ -249,7 +254,7 @@ const plain = ({ root }: { root: string }) => {for (const backend of testBackends()) describe(`[${backend}] door write cost: ignore rules edited mid-session`, () => {const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;- test('strict: a page under a rule added mid-session is declared git_ignored; after the rule goes a new page commits', () => managedBrain(async ({ engine, ctx, root }) => {+ test('strict: a page under a rule added mid-session is declared git_ignored; after the rule goes a new page commits', hermetic(() => managedBrain(async ({ engine, ctx, root }) => {await strict(engine);expect(await write(ctx, 'notes/before')).toMatchObject({ state: 'committed' });expect(git(root, 'log', '--format=%H', '--', 'notes/before.md')).not.toBe('');@@ -263,9 +268,9 @@ for (const backend of testBackends()) describe(`[${backend}] door write cost: igexpect(await write(ctx, 'notes/later-two')).toMatchObject({ state: 'committed' });expect(git(root, 'show', 'HEAD:notes/later-two.md')).toContain('Body of notes/later-two.');expect(await reason(engine, 'notes/later-two')).toBeNull();- }, { databaseUrl, setup: durable }), 120_000);+ }, { databaseUrl, setup: durable })), 120_000);- test('mixed, not durable: a new page under a rule added mid-session is database-only', () => managedBrain(async ({ engine, ctx, root }) => {+ test('mixed, not durable: a new page under a rule added mid-session is database-only', hermetic(() => managedBrain(async ({ engine, ctx, root }) => {expect(await write(ctx, 'notes/before')).toMatchObject({ state: 'committed' });expect(existsSync(join(root, 'notes/before.md'))).toBe(true);ignoreLater(root, 'notes/later-*\n');@@ -273,9 +278,9 @@ for (const backend of testBackends()) describe(`[${backend}] door write cost: igexpect(existsSync(join(root, 'notes/later-one.md'))).toBe(false);const [row] = await engine.executeRaw<{ path: string | null }>("SELECT source_path AS path FROM pages WHERE source_id='default' AND slug='notes/later-one'");expect(row?.path ?? null).toBeNull();- }, { databaseUrl, setup: plain }), 120_000);+ }, { databaseUrl, setup: plain })), 120_000);- test('mixed, durable: a page under a rule added mid-session still parks its Git effect as git_target_ignored', () => managedBrain(async ({ engine, ctx, root }) => {+ test('mixed, durable: a page under a rule added mid-session still parks its Git effect as git_target_ignored', hermetic(() => managedBrain(async ({ engine, ctx, root }) => {expect(await write(ctx, 'notes/before')).toMatchObject({ state: 'committed' });ignoreLater(root, 'notes/later-*\n');expect(await write(ctx, 'notes/later-one')).toMatchObject({ state: 'committed' });@@ -286,5 +291,5 @@ for (const backend of testBackends()) describe(`[${backend}] door write cost: ig{ timeoutMs: 30_000, label: 'the Git effect parks' });expect(await parked()).toBe('git_target_ignored');expect(git(root, 'ls-files', '--', 'notes/later-one.md')).toBe('');- }, { databaseUrl, setup: durable }), 120_000);+ }, { databaseUrl, setup: durable })), 120_000);});diff --git a/test/ignore-rules.test.ts b/test/ignore-rules.test.tsindex f6eb384d72..e44d9c213d 100644--- a/test/ignore-rules.test.ts+++ b/test/ignore-rules.test.ts@@ -16,11 +16,17 @@ import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { gitChildEnv } from '../src/core/git-env.ts';import { ignoreCandidates, resetIgnoreCandidatesForTests, scanIndex } from '../src/core/persistence/ignore-rules.ts';+import { withEnv } from './helpers/with-env.ts';-const env = gitChildEnv();-const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], env }).trim();+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], env: gitChildEnv() }).trim();const roots: string[] = [];afterEach(() => { resetIgnoreCandidatesForTests(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });+/** Keeps the developer's global and system Git config and global ignore file out of the test: the filter reads what Git reads. */+const hermetic = (fn: () => unknown) => () => {+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-git-config-')));+ roots.push(home);+ return withEnv({ XDG_CONFIG_HOME: home, GIT_CONFIG_GLOBAL: join(home, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' }, async () => { await fn(); });+};function repo(): string {const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-ignore-rules-')));@@ -36,7 +42,7 @@ function put(root: string, path: string, body = 'x\n'): void {/** The paths Git ignores among `paths`, from the checkout's own check-ignore (index included). */function gitIgnored(root: string, paths: string[]): Set<string> {try {- const out = execFileSync('git', ['-C', root, 'check-ignore', '-z', '--stdin'], { input: paths.map(path => path + '\0').join(''), env, stdio: ['pipe', 'pipe', 'pipe'] });+ const out = execFileSync('git', ['-C', root, 'check-ignore', '-z', '--stdin'], { input: paths.map(path => path + '\0').join(''), env: gitChildEnv(), stdio: ['pipe', 'pipe', 'pipe'] });return new Set(out.toString('utf8').split('\0').filter(Boolean));} catch (error) {if ((error as { status?: number }).status === 1) return new Set();@@ -54,7 +60,7 @@ const RULES = ['notes', 'NOTES/', '*.log', '!keep.log', '*.tmp', '/dist', 'dist/'#notes', 'page.md ', '\\#lit', 'x\\.md', '*', '!*.md', 'node_modules/', '.DS_Store', 'foo bar', 'é.md', '/a/', 'ab*c.md', 'Build/', '**', '!sub/', 'b/', '/notes/drafts/', 'NOTES', 'y.log'];describe('ignore filter', () => {- test('every path check-ignore ignores is returned for Git, over generated rule sets; many others are cleared', async () => {+ test('every path check-ignore ignores is returned for Git, over generated rule sets; many others are cleared', hermetic(async () => {const next = random(7);const pick = <T>(list: T[]) => list[Math.floor(next() * list.length)]!;let cleared = 0, total = 0;@@ -84,9 +90,9 @@ describe('ignore filter', () => {cleared += listed.length - candidates.size;}expect(cleared).toBeGreaterThan(total / 10);- }, 120_000);+ }), 120_000);- test('an edit of a .gitignore, info/exclude or the excludes file, or a new core.excludesFile, is seen on the next call', async () => {+ test('an edit of a .gitignore, info/exclude or the excludes file, or a new core.excludesFile, is seen on the next call', hermetic(async () => {const root = repo();put(root, 'notes/a.md'); put(root, '.gitignore', 'scratch/\n');git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');@@ -105,9 +111,9 @@ describe('ignore filter', () => {expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual(['notes/new.md']);writeFileSync(excludes, '*.txt\n');expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual([]);- });+ }));- test('Git decides on a sparse checkout, a skip-worktree entry, a gitlink or symlinked directory on the path, and a version 4 gitlink', async () => {+ test('Git decides on a sparse checkout, a skip-worktree entry, a gitlink or symlinked directory on the path, and a version 4 gitlink', hermetic(async () => {const root = repo();put(root, 'notes/a.md'); put(root, 'notes/b.md'); put(root, 'real/c.md');git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');@@ -127,9 +133,9 @@ describe('ignore filter', () => {expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual(['notes/new.md']);git(root, 'update-index', '--force-remove', 'vendor/lib');expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual([]);- });+ }));- test('the index scan reads versions 2, 3 and 4 and names version 2 and 3 gitlinks', () => {+ test('the index scan reads versions 2, 3 and 4 and names version 2 and 3 gitlinks', hermetic(() => {const root = repo();for (let i = 0; i < 50; i++) put(root, `dir-${i % 7}/${'long-name-'.repeat(i % 5)}page-${i}.md`);git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');@@ -145,13 +151,13 @@ describe('ignore filter', () => {git(root, 'update-index', '--force-remove', 'dir-3/module');expect(scanIndex(readFileSync(index), 20)).toEqual({ decidable: true, gitlinks: new Set() });expect(scanIndex(Buffer.from('not an index'), 20).decidable).toBe(false);- });+ }));// Generated by /ship Step 7 coverage audit (gstack), test-only.// Value: protects=a core.excludesFile set in an included config file (a relative include.path) is read, and an edit of that file is seen;// fails_when=the probe stops resolving include paths or watching included files, so a stale probe clears a path Git now ignores;// why_new=excludes edits are tested only through .git/config; seam=none; no_claim=includeIf conditions (onbranch, gitdir) are not exercised- test('a core.excludesFile set through an included config file, and an edit of that file, is seen on the next call', async () => {+ test('a core.excludesFile set through an included config file, and an edit of that file, is seen on the next call', hermetic(async () => {const root = repo();put(root, 'notes/a.md');git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');@@ -167,13 +173,13 @@ describe('ignore filter', () => {expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual(['notes/new.md']);writeFileSync(included, `[core]\n\texcludesFile = ${text}\n`);expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual([]);- });+ }));// Generated by /ship Step 7 coverage audit (gstack), test-only.// Value: protects=a split index (entries and skip-worktree bits in the shared index file) is left to Git; fails_when=scanIndex accepts the// required 'link' extension, so the filter decides without seeing the shared entries; why_new=sparse, skip-worktree and v4 are tested, a split// index is not; seam=none; no_claim=a sparse index (sdir extension) is not exercised- test('a split index is left to Git', async () => {+ test('a split index is left to Git', hermetic(async () => {const root = repo();put(root, 'notes/a.md');git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');@@ -183,5 +189,5 @@ describe('ignore filter', () => {expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual(['notes/new.md']);git(root, 'update-index', '--no-split-index');expect(await ignoreCandidates(root, ['notes/new.md'])).toEqual([]);- });+ }));});