Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* brain-repo-durability core (v0.42.44): hardenBrainRepo / unhardenBrainRepo /
* acceptPat. Real git against a local bare remote. HOME + GBRAIN_HOME are
* redirected to a tmp dir; installCron:false so the suite never touches launchd.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, statSync, chmodSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { execFileSync } from 'child_process';
import {
hardenBrainRepo, unhardenBrainRepo, acceptPat, maintainPushLog,
} from '../src/core/brain-repo-durability.ts';
const PAT = 'ghp_TESTSECRETTOKEN0123456789abcdef';
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args], {
stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8',
}).trim();
}
function commitCount(work: string): number {
return parseInt(git(work, 'rev-list', '--count', 'HEAD'), 10);
}
/** git config read that returns '' instead of throwing when the key is unset. */
function cfg(work: string, key: string): string {
try { return git(work, 'config', '--local', '--get', key); } catch { return ''; }
}
let root: string;
let work: string;
let bare: string;
let oldHome: string | undefined;
let oldGbrainHome: string | undefined;
function makePair(): void {
bare = mkdtempSync(join(root, 'origin-')) + '.git';
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], { stdio: 'ignore' });
work = mkdtempSync(join(root, 'work-'));
execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, work], { stdio: 'ignore' });
git(work, 'config', 'user.email', '[email protected]');
git(work, 'config', 'user.name', 'tester');
writeFileSync(join(work, 'README.md'), 'init\n');
git(work, 'add', 'README.md'); git(work, 'commit', '-qm', 'init'); git(work, 'push', '-q', 'origin', 'main');
try { git(work, 'remote', 'set-head', 'origin', 'main'); } catch { /* */ }
}
async function harden(extra: Record<string, unknown> = {}) {
return hardenBrainRepo({ repoPath: work, sourceId: 'wiki', pat: PAT, installCron: false, ...extra });
}
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'brd-'));
oldHome = process.env.HOME; oldGbrainHome = process.env.GBRAIN_HOME;
process.env.HOME = mkdtempSync(join(root, 'home-'));
// CX2-8: GBRAIN_HOME is a PARENT dir (config.ts semantics — `.gbrain` is
// appended by the resolver), so the effective home is $HOME/.gbrain.
process.env.GBRAIN_HOME = process.env.HOME;
process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
makePair();
});
afterEach(() => {
if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome;
if (oldGbrainHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = oldGbrainHome;
delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT;
rmSync(root, { recursive: true, force: true });
});
describe('hardenBrainRepo', () => {
test('installs hook (local, untracked, +x), helper, and AGENTS rules', async () => {
const r = await harden();
// hook
const hookPath = join(work, '.git', 'hooks', 'post-commit');
expect(existsSync(hookPath)).toBe(true);
expect(readFileSync(hookPath, 'utf-8')).toContain('post-commit hook');
expect(statSync(hookPath).mode & 0o111).toBeTruthy(); // executable
// helper (committed, +x)
const helperPath = join(work, 'scripts', 'brain-commit-push.sh');
expect(existsSync(helperPath)).toBe(true);
expect(statSync(helperPath).mode & 0o111).toBeTruthy();
// AGENTS.md with managed block + taxonomy
const agents = readFileSync(join(work, 'AGENTS.md'), 'utf-8');
expect(agents).toContain('BEGIN gbrain-brain-durability');
expect(agents).toContain('people/');
expect(agents).toContain('brain-commit-push.sh');
// verify pushed scaffolding → clean against origin
expect(r.clean_against_origin).toBe(true);
expect(r.needs_attention).toEqual([]);
});
test('is idempotent — second run adds NO new commit', async () => {
await harden();
const after1 = commitCount(work);
const r2 = await harden();
expect(commitCount(work)).toBe(after1); // no churn
// every step is ok/skipped on the second pass (nothing left to fix)
expect(r2.steps.every(s => s.status === 'ok' || s.status === 'skipped')).toBe(true);
});
test('the post-commit hook is UNTRACKED (never committed)', async () => {
await harden();
const tracked = git(work, 'ls-files');
expect(tracked.includes('post-commit')).toBe(false);
expect(tracked).toContain('scripts/brain-commit-push.sh'); // helper IS tracked
});
test('D3 — patches RESOLVER.md when it exists, not AGENTS.md', async () => {
writeFileSync(join(work, 'RESOLVER.md'), '# my resolver\n\nuser content\n');
git(work, 'add', 'RESOLVER.md'); git(work, 'commit', '-qm', 'resolver');
await harden();
expect(readFileSync(join(work, 'RESOLVER.md'), 'utf-8')).toContain('BEGIN gbrain-brain-durability');
expect(existsSync(join(work, 'AGENTS.md'))).toBe(false);
});
test('AGENTS block patch preserves user content above and below', async () => {
writeFileSync(join(work, 'AGENTS.md'), '# Top\n\nkeep above\n\n## footer\nkeep below\n');
git(work, 'add', 'AGENTS.md'); git(work, 'commit', '-qm', 'agents');
await harden();
const body = readFileSync(join(work, 'AGENTS.md'), 'utf-8');
expect(body).toContain('keep above');
expect(body).toContain('keep below');
expect(body).toContain('BEGIN gbrain-brain-durability');
// patch-in-place: exactly one managed block
expect(body.split('BEGIN gbrain-brain-durability').length - 1).toBe(1);
});
test('D11 — writes a repo-scoped credential (0600 store, local config, ownership key)', async () => {
await harden();
const store = join(process.env.HOME!, '.gbrain', 'git-credentials');
expect(existsSync(store)).toBe(true);
expect(statSync(store).mode & 0o077).toBe(0); // not group/other readable
expect(git(work, 'config', '--local', '--get', 'credential.helper')).toContain('store --file');
expect(cfg(work, 'gbrain.durability.managedcredential')).toBe('true');
});
test('D11 — reuses an existing credential.helper (no plaintext store written)', async () => {
git(work, 'config', 'credential.helper', 'osxkeychain');
await harden();
const store = join(process.env.HOME!, '.gbrain', 'git-credentials');
expect(existsSync(store)).toBe(false);
expect(git(work, 'config', '--local', '--get', 'credential.helper')).toBe('osxkeychain');
});
test('PAT never appears in the serialized report', async () => {
const r = await harden();
expect(JSON.stringify(r).includes(PAT)).toBe(false);
});
test('detached HEAD → pull step needs_attention (refuses to push to a wrong ref)', async () => {
const sha = git(work, 'rev-parse', 'HEAD');
git(work, 'checkout', '-q', sha); // detached
const r = await harden({ verify: false });
const pull = r.steps.find(s => s.step === 'pull');
expect(pull?.status).toBe('needs_attention');
});
test('D10 — verify reports needs_attention when push-probe fails (read-only/unreachable)', async () => {
git(work, 'remote', 'set-url', 'origin', join(root, 'unreachable.git'));
const r = await harden();
const verify = r.steps.find(s => s.step === 'verify');
expect(verify?.status).toBe('needs_attention');
expect(r.clean_against_origin).toBe(false);
expect(r.needs_attention.length).toBeGreaterThan(0);
// No scaffolding commit when we can't confirm a push.
expect(r.steps.find(s => s.step === 'commit')).toBeUndefined();
});
test('dry-run makes no commit and writes no files', async () => {
const before = commitCount(work);
await harden({ dryRun: true });
expect(commitCount(work)).toBe(before);
expect(existsSync(join(work, 'scripts', 'brain-commit-push.sh'))).toBe(false);
});
test('dry-run does not fetch or pull from origin', async () => {
const secondClone = mkdtempSync(join(root, 'pusher-'));
execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, secondClone], { stdio: 'ignore' });
execFileSync('git', ['-C', secondClone, 'config', 'user.email', '[email protected]'], { stdio: 'ignore' });
execFileSync('git', ['-C', secondClone, 'config', 'user.name', 'tester'], { stdio: 'ignore' });
writeFileSync(join(secondClone, 'upstream.md'), 'new upstream content\n');
execFileSync('git', ['-C', secondClone, 'add', 'upstream.md'], { stdio: 'ignore' });
execFileSync('git', ['-C', secondClone, 'commit', '-qm', 'advance origin'], { stdio: 'ignore' });
execFileSync('git', ['-c', 'protocol.file.allow=always', '-C', secondClone, 'push', '-q', 'origin', 'main'], { stdio: 'ignore' });
const headBefore = git(work, 'rev-parse', 'HEAD');
const trackingBefore = git(work, 'rev-parse', 'refs/remotes/origin/main');
const report = await harden({ dryRun: true });
expect(git(work, 'rev-parse', 'HEAD')).toBe(headBefore);
expect(existsSync(join(work, 'upstream.md'))).toBe(false);
expect(git(work, 'rev-parse', 'refs/remotes/origin/main')).toBe(trackingBefore);
expect(existsSync(join(work, '.git', 'FETCH_HEAD'))).toBe(false);
expect(report.steps.find(step => step.step === 'pull')?.status).toBe('skipped');
});
test('dry-run does not chmod an already-current helper (#3736)', async () => {
await harden(); // real run installs scripts/brain-commit-push.sh at 0o755
const helperPath = join(work, 'scripts', 'brain-commit-push.sh');
chmodSync(helperPath, 0o644); // simulate perms drifting away from +x, content unchanged
await harden({ dryRun: true });
expect(statSync(helperPath).mode & 0o777).toBe(0o644); // untouched — preview must not mutate
});
test('non-dry-run restores the exec bit on an already-current helper', async () => {
await harden();
const helperPath = join(work, 'scripts', 'brain-commit-push.sh');
chmodSync(helperPath, 0o644);
await harden();
expect(statSync(helperPath).mode & 0o111).toBeTruthy(); // exec bit restored
});
test('CX2-3 — parent-repo-aware: a subdirectory target hardens the repo ROOT', async () => {
// Workspace layout: the source dir is `repo/brain` while the enclosing
// repo owns `.git`. Pre-fix the `.git` assertion failed on the subdir.
const sub = join(work, 'brain');
mkdirSync(sub, { recursive: true });
writeFileSync(join(sub, 'note.md'), '# note\n');
git(work, 'add', 'brain/note.md'); git(work, 'commit', '-qm', 'brain dir');
const r = await hardenBrainRepo({ repoPath: sub, sourceId: 'wiki', pat: PAT, installCron: false });
expect(r.repo_path).toBe(git(work, 'rev-parse', '--show-toplevel'));
// scaffolding landed at the ROOT, not inside brain/
expect(existsSync(join(work, 'scripts', 'brain-commit-push.sh'))).toBe(true);
expect(existsSync(join(sub, 'scripts'))).toBe(false);
expect(r.needs_attention).toEqual([]);
});
test('S3#10 — maintainPushLog chmods 0600 and rotates at 1MB', async () => {
const home = join(process.env.HOME!, '.gbrain');
mkdirSync(home, { recursive: true });
const log = join(home, 'brain-push.log');
writeFileSync(log, 'x'.repeat(1024 * 1024 + 1), { mode: 0o644 });
maintainPushLog();
// rotated: predecessor kept as .1, fresh log is empty + 0600
expect(existsSync(`${log}.1`)).toBe(true);
expect(readFileSync(log, 'utf-8')).toBe('');
expect(statSync(log).mode & 0o077).toBe(0);
// small log: chmod only, no rotation
rmSync(`${log}.1`);
writeFileSync(log, 'small\n', { mode: 0o644 });
maintainPushLog();
expect(existsSync(`${log}.1`)).toBe(false);
expect(readFileSync(log, 'utf-8')).toBe('small\n');
expect(statSync(log).mode & 0o077).toBe(0);
});
test('#5436 — core.hooksPath=.githooks: hook is excluded via info/exclude and stays untracked', async () => {
git(work, 'config', 'core.hooksPath', '.githooks');
await harden({ verify: false });
const hookPath = join(work, '.githooks', 'post-commit');
expect(existsSync(hookPath)).toBe(true);
const exclude = readFileSync(join(work, '.git', 'info', 'exclude'), 'utf-8');
expect(exclude).toContain('.githooks/post-commit');
// Ignored → the hook never shows up as untracked in git status.
const st = git(work, 'status', '--porcelain', '--untracked-files=all', '--', '.githooks/post-commit');
expect(st).toBe('');
});
test('#5436 — re-harden repairs the exclusion for a hook installed before the fix', async () => {
git(work, 'config', 'core.hooksPath', '.githooks');
await harden({ verify: false });
const exclude = join(work, '.git', 'info', 'exclude');
writeFileSync(exclude, readFileSync(exclude, 'utf-8').replace('.githooks/post-commit\n', ''));
expect(git(work, 'status', '--porcelain', '--untracked-files=all', '--', '.githooks/post-commit')).toBe('?? .githooks/post-commit');
await harden({ verify: false });
expect(readFileSync(exclude, 'utf-8').split('\n').filter(line => line === '.githooks/post-commit')).toHaveLength(1);
expect(git(work, 'status', '--porcelain', '--untracked-files=all', '--', '.githooks/post-commit')).toBe('');
});
test('#5436 — a hooks dir outside the working tree gets no exclude entry', async () => {
const outside = join(root, 'shared-hooks');
git(work, 'config', 'core.hooksPath', outside);
await harden({ verify: false });
expect(existsSync(join(outside, 'post-commit'))).toBe(true);
expect(readFileSync(join(work, '.git', 'info', 'exclude'), 'utf-8')).not.toContain('post-commit');
});
test('#5436 — a hooksPath whose repo path contains ".git" (site.github.io) is still excluded', async () => {
const weird = join(root, 'site.github.io', 'repo');
execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, weird], { stdio: 'ignore' });
git(weird, 'config', 'user.email', '[email protected]');
git(weird, 'config', 'user.name', 'tester');
git(weird, 'config', 'core.hooksPath', 'myhooks');
await hardenBrainRepo({ repoPath: weird, sourceId: 'wiki', pat: PAT, installCron: false, verify: false });
const exclude = readFileSync(join(weird, '.git', 'info', 'exclude'), 'utf-8');
expect(exclude).toContain('myhooks/post-commit');
const st = git(weird, 'status', '--porcelain', '--untracked-files=all', '--', 'myhooks/post-commit');
expect(st).toBe('');
});
});
describe('unhardenBrainRepo', () => {
test('removes hook + credential wiring; leaves committed content', async () => {
await harden();
const steps = await unhardenBrainRepo({ repoPath: work, sourceId: 'wiki' });
expect(existsSync(join(work, '.git', 'hooks', 'post-commit'))).toBe(false);
expect(cfg(work, 'gbrain.durability.managedcredential')).toBe('');
// committed helper stays
expect(existsSync(join(work, 'scripts', 'brain-commit-push.sh'))).toBe(true);
expect(steps.find(s => s.step === 'hook')?.status).toBe('fixed');
});
test('idempotent when not hardened (all skipped)', async () => {
const steps = await unhardenBrainRepo({ repoPath: work, sourceId: 'wiki' });
expect(steps.every(s => s.status === 'skipped')).toBe(true);
});
});
describe('acceptPat (D8)', () => {
test('reads + trims a pat-file', () => {
const p = join(root, 'pat.txt');
writeFileSync(p, `${PAT}\n`, { mode: 0o600 });
const r = acceptPat({ patFile: p });
expect(r?.token).toBe(PAT);
expect(r?.warnings).toEqual([]);
});
test('throws on a missing pat-file', () => {
expect(() => acceptPat({ patFile: join(root, 'nope.txt') })).toThrow();
});
test('throws on an empty pat-file', () => {
const p = join(root, 'empty.txt'); writeFileSync(p, ' \n', { mode: 0o600 });
expect(() => acceptPat({ patFile: p })).toThrow();
});
test('warns (but continues) on loose perms', () => {
const p = join(root, 'loose.txt'); writeFileSync(p, PAT); chmodSync(p, 0o644);
const r = acceptPat({ patFile: p });
expect(r?.token).toBe(PAT);
expect(r?.warnings.length).toBeGreaterThan(0);
});
test('falls back to GBRAIN_GITHUB_PAT env', () => {
const old = process.env.GBRAIN_GITHUB_PAT;
process.env.GBRAIN_GITHUB_PAT = PAT;
try { expect(acceptPat({})?.source).toBe('env:GBRAIN_GITHUB_PAT'); }
finally { if (old === undefined) delete process.env.GBRAIN_GITHUB_PAT; else process.env.GBRAIN_GITHUB_PAT = old; }
});
test('returns null when no PAT is available', () => {
const old = process.env.GBRAIN_GITHUB_PAT; delete process.env.GBRAIN_GITHUB_PAT;
try { expect(acceptPat({})).toBeNull(); }
finally { if (old !== undefined) process.env.GBRAIN_GITHUB_PAT = old; }
});
});