Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* #5808 [R9]: the AGENTS durability block `gbrain sources harden` renders tells
* agents to run `scripts/brain-commit-push.sh` after every write and to
* `scripts/brain-commit-push.sh --pull` before writing (#6530; formerly `git pull --rebase`). On a managed canonical
* worktree both route agents around the persistence owner, and `sources harden`
* itself refuses there, so a block rendered before activation stayed stale.
*
* Fix: `gbrain sources writer git-durability <source> --enable` (and
* `--pat-file`) rewrites the block to its managed variant, idempotently,
* without touching the text outside the markers, without committing (the
* block is a non-page file the operator commits) and without any claim,
* transfer or topology change.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { hardenBrainRepo, patchManagedDurabilityBlock } from '../src/core/brain-repo-durability.ts';
import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { gitAsync } from './helpers/git-publication.ts';
import { withEnv } from './helpers/with-env.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
const BEGIN = '<!-- BEGIN gbrain-brain-durability (managed; do not edit between markers) -->';
const END = '<!-- END gbrain-brain-durability -->';
const CLASSIC = ['scripts/brain-commit-push.sh', 'scripts/brain-commit-push.sh --pull', 'regenerated by `gbrain sources harden`'];
const block = (text: string) => text.slice(text.indexOf(BEGIN), text.indexOf(END) + END.length);
const outside = (text: string) => text.slice(0, text.indexOf(BEGIN)) + text.slice(text.indexOf(END) + END.length);
let engine: PGLiteEngine;
const homes: string[] = [];
beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); for (const home of homes) rmSync(home, { recursive: true, force: true }); });
async function isolated<T>(run: (home: string) => Promise<T>): Promise<T> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-5808-')); homes.push(home);
try {
return await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, async () => { await registerLocalWriter(engine, 'cli'); return run(home); });
} finally { await disposePersistenceConsumer(engine); }
}
/** A checkout with a bare remote, hardened the classic way before anyone claimed it: the reported install. */
async function hardenedRoot(home: string): Promise<{ root: string; agents: string; before: string }> {
const root = join(home, `root-${randomUUID().slice(0, 8)}`); mkdirSync(root);
await gitAsync(root, 'init', '-q', '-b', 'main');
await gitAsync(root, 'config', 'user.name', 'Example Writer');
await gitAsync(root, 'config', 'user.email', '[email protected]');
const agents = join(root, 'AGENTS.md');
writeFileSync(agents, '# Example brain\n\nHouse rules the operator wrote. Keep these.\n');
writeFileSync(join(root, 'initial.md'), 'Initial\n');
await gitAsync(root, 'add', '-A'); await gitAsync(root, 'commit', '-q', '-m', 'Initial');
const remote = join(home, `remote-${randomUUID().slice(0, 8)}.git`); mkdirSync(remote);
await gitAsync(remote, 'init', '-q', '--bare');
await gitAsync(root, 'remote', 'add', 'origin', remote); await gitAsync(root, 'push', '-q', '-u', 'origin', 'main');
const report = await hardenBrainRepo({ repoPath: root, sourceId: 'example', installCron: false, verify: false });
expect(report.steps.find(step => step.step === 'agents')).toMatchObject({ status: 'fixed' });
const before = readFileSync(agents, 'utf8');
for (const marker of CLASSIC) expect(block(before)).toContain(marker);
await gitAsync(root, 'add', '-A'); await gitAsync(root, 'commit', '-q', '-m', 'Harden');
return { root, agents, before };
}
describe('the managed durability block (#5808)', () => {
test('the managed variant never tells agents to pull --rebase or run the push helper, and is idempotent in place', () => isolated(async home => {
const { root, agents, before } = await hardenedRoot(home);
expect(patchManagedDurabilityBlock(root, 'vault-example', true)).toMatchObject({ status: 'fixed', detail: expect.stringContaining('dry-run') });
expect(readFileSync(agents, 'utf8')).toBe(before);
expect(patchManagedDurabilityBlock(root, 'vault-example', false)).toMatchObject({ status: 'fixed' });
const after = readFileSync(agents, 'utf8');
const managed = block(after);
for (const marker of CLASSIC) expect(managed).not.toContain(marker);
expect(managed).not.toContain('pull --rebase');
expect(managed).toContain('regenerated by `gbrain sources writer git-durability vault-example --enable`');
expect(managed).toContain('Page writes go through gbrain, never through git.');
expect(managed).toContain('Never pull, rebase or reset this checkout.');
expect(managed).toContain('gbrain sources writer status vault-example --json');
expect(managed).toContain('gbrain sources refresh vault-example');
expect(managed).toContain('Files that are not pages');
expect(managed).toContain('Deterministic filing');
expect(outside(after)).toBe(outside(before));
expect(after).toContain('House rules the operator wrote. Keep these.');
expect(patchManagedDurabilityBlock(root, 'vault-example', false)).toMatchObject({ status: 'ok', detail: expect.stringContaining('already current') });
expect(readFileSync(agents, 'utf8')).toBe(after);
}), 60_000);
test('git-durability --enable on an already-hardened managed install rewrites the stale block, commits nothing and changes no ownership', () => isolated(async home => {
const { root, agents, before } = await hardenedRoot(home);
const sourceId = `vault-${randomUUID().slice(0, 8)}`;
await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
await claimWorktree(engine, sourceId, root, localHostId());
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
try {
const binding = (await getWorktreeBinding(engine, sourceId, localHostId()))!;
const identity = (b: typeof binding) => [b.worktree_id, b.owner_host_id, String(b.owner_epoch), String(b.topology_generation), b.state, b.local_path];
const preview = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });
expect(preview).toMatchObject({ dry_run: true, push_probe: { ok: true }, agents: { status: 'fixed', detail: expect.stringContaining('dry-run') } });
expect(readFileSync(agents, 'utf8')).toBe(before);
const applied = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });
expect(applied).toMatchObject({ applied: true, git_durability: { before: null, after: 'enabled' },
agents: { status: 'fixed', detail: expect.stringContaining('durability rules written'), commit: expect.stringContaining(`gbrain git commit-push --path ${root} -m "<msg>" -- AGENTS.md`) } });
const after = readFileSync(agents, 'utf8');
for (const marker of CLASSIC) expect(block(after)).not.toContain(marker);
expect(block(after)).toContain(`gbrain sources writer git-durability ${sourceId} --enable`);
expect(outside(after)).toBe(outside(before));
// The verb commits nothing: the rewritten file is the operator's to commit, and no ownership record moved.
expect((await gitAsync(root, 'status', '--porcelain')).trim()).toBe('M AGENTS.md');
expect(identity((await getWorktreeBinding(engine, sourceId, localHostId()))!)).toEqual(identity(binding));
expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBe('enabled');
// A second --enable is a no-op for the block and for the file.
const again = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });
expect(again).toMatchObject({ agents: { status: 'ok', detail: expect.stringContaining('already current') }, why: expect.stringContaining('already as requested') });
expect(readFileSync(agents, 'utf8')).toBe(after);
// --disable leaves the block alone: the checkout stays managed either way.
const disabled = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, disable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });
expect(disabled).toMatchObject({ applied: true, git_durability: { before: 'enabled', after: 'disabled' } });
expect(disabled.agents).toBeUndefined();
expect(readFileSync(agents, 'utf8')).toBe(after);
} finally {
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
}
}), 120_000);
});