Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: give harness installer tests their own GBRAIN_HOME

garrytan47f4a193ef2e
diff --git a/test/harness-install-ownership.test.ts b/test/harness-install-ownership.test.ts
index 6dc9b15a07..b8837b0c2d 100644
--- a/test/harness-install-ownership.test.ts
+++ b/test/harness-install-ownership.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { CODEX_TOML_BLOCK_END } from '../src/core/bootstrap/host-specs.ts';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
@@ -9,10 +9,17 @@ import { readCredentials, validateCredentials, type HarnessCredentials } from '.
import { sha256 } from '../src/core/agent-install/state.ts';
import { parseMcpGrant } from '../src/commands/mcp.ts';
import { validateHarnessArguments } from '../src/core/harness/arguments.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { guardInheritedInstructionLedger } from './helpers/inherited-ledger-guard.ts';
+
+guardInheritedInstructionLedger();
const roots: string[] = [];
const temp = () => { const root = mkdtempSync(join(tmpdir(), 'gbrain-owned-client-')); roots.push(root); return root; };
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+let ledgerHome = '';
+beforeEach(() => { ledgerHome = temp(); });
+const install: typeof installHarnessConnection = (c, opts) => withEnv({ GBRAIN_HOME: ledgerHome }, () => installHarnessConnection(c, opts));
const credentials: HarnessCredentials = { version: 1, mcp_url: 'https://brain.example.com/mcp', issuer_url: 'https://brain.example.com', client_id: 'gbrain_cl_owned_fixture', client_secret: 'fixture-secret-not-real', access_token: 'fixture-token-not-real', profile: 'memory-writer' };
test('provisioning refuses misspelled restrictions and duplicate aliases before creating authority', () => {
@@ -26,17 +33,17 @@ test('provisioning refuses misspelled restrictions and duplicate aliases before
test('thin install preserves edited files before any rewrite, then removes only owned artifacts idempotently', async () => {
const root = temp();
- await installHarnessConnection(credentials, { harness: 'muse', root });
+ await install(credentials, { harness: 'muse', root });
const path = join(root, 'GBRAIN-INSTRUCTIONS.md'); const generated = readFileSync(path, 'utf8');
const configPath = join(root, '.gbrain', 'config.json'); const before = readFileSync(configPath, 'utf8');
writeFileSync(path, 'my personal instructions');
- await expect(installHarnessConnection({ ...credentials, client_secret: 'new-fixture-secret' }, { harness: 'muse', root })).rejects.toThrow('edited');
- await expect(installHarnessConnection(credentials, { harness: 'muse', root, remove: true })).rejects.toThrow('edited');
+ await expect(install({ ...credentials, client_secret: 'new-fixture-secret' }, { harness: 'muse', root })).rejects.toThrow('edited');
+ await expect(install(credentials, { harness: 'muse', root, remove: true })).rejects.toThrow('edited');
expect(readFileSync(configPath, 'utf8')).toBe(before);
expect(readFileSync(path, 'utf8')).toBe('my personal instructions');
writeFileSync(path, generated);
writeFileSync(join(root, 'personal-note.md'), 'keep this');
- for (let i = 0; i < 2; i++) expect((await installHarnessConnection(credentials, { harness: 'muse', root, remove: true })).status).toBe('removed');
+ for (let i = 0; i < 2; i++) expect((await install(credentials, { harness: 'muse', root, remove: true })).status).toBe('removed');
expect(existsSync(configPath)).toBe(false);
expect(existsSync(join(root, 'bin', 'gbrain'))).toBe(false);
expect(readFileSync(join(root, 'personal-note.md'), 'utf8')).toBe('keep this');
@@ -45,7 +52,7 @@ test('thin install preserves edited files before any rewrite, then removes only
test('thin setup resumes a recorded interrupted file write without claiming arbitrary edits', async () => {
const root = temp();
- await installHarnessConnection(credentials, { harness: 'grok-bot', root });
+ await install(credentials, { harness: 'grok-bot', root });
const path = 'GBRAIN-INSTRUCTIONS.md'; const target = join(root, path);
const generated = readFileSync(target, 'utf8');
const receiptPath = join(root, '.gbrain', 'harness-connection.json');
@@ -53,21 +60,21 @@ test('thin setup resumes a recorded interrupted file write without claiming arbi
const staged = generated + '\ninterrupted generated revision\n';
receipt.pending_files = { [path]: { before: sha256(generated), after: sha256(staged) } };
writeFileSync(receiptPath, JSON.stringify(receipt)); writeFileSync(target, staged);
- await installHarnessConnection(credentials, { harness: 'grok-bot', root });
+ await install(credentials, { harness: 'grok-bot', root });
expect(readFileSync(target, 'utf8')).toBe(generated);
expect(JSON.parse(readFileSync(receiptPath, 'utf8')).pending_files).toEqual({});
});
for (const harness of ['codex', 'opencode']) test(`${harness} refuses edited and same-URL unowned entries`, async () => {
const root = temp(); const configPath = join(root, harness === 'codex' ? 'config.toml' : 'config.jsonc');
- await installHarnessConnection(credentials, { harness, configPath });
+ await install(credentials, { harness, configPath });
const original = readFileSync(configPath, 'utf8');
writeFileSync(configPath, original.replace('fixture-token-not-real', 'edited-token'));
- await expect(installHarnessConnection(credentials, { harness, configPath })).rejects.toThrow('edited');
- await expect(installHarnessConnection(credentials, { harness, configPath, remove: true })).rejects.toThrow('edited');
+ await expect(install(credentials, { harness, configPath })).rejects.toThrow('edited');
+ await expect(install(credentials, { harness, configPath, remove: true })).rejects.toThrow('edited');
writeFileSync(configPath, original);
rmSync(join(root, `.gbrain-connection-${harness}-gbrain.json`));
- await expect(installHarnessConnection(credentials, { harness, configPath })).rejects.toThrow('unowned');
+ await expect(install(credentials, { harness, configPath })).rejects.toThrow('unowned');
expect(readFileSync(configPath, 'utf8')).toBe(original);
});
@@ -80,36 +87,36 @@ describe('#6799 Codex tool approvals ("always allow")', () => {
test('an install keyed by the legacy whole-entry hash renews with approvals inside the block and keeps them', async () => {
const root = temp(); const configPath = join(root, 'config.toml');
- await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ await install(credentials, { harness: 'codex', configPath });
expect(JSON.parse(readFileSync(receiptPath(root), 'utf8')).entry_hash).toBe(wholeHash(entryOf(configPath)));
writeFileSync(configPath, readFileSync(configPath, 'utf8').replace(CODEX_TOML_BLOCK_END, `${approval('search')}${CODEX_TOML_BLOCK_END}`));
- expect((await installHarnessConnection(renewed, { harness: 'codex', configPath })).status).toBe('installed');
+ expect((await install(renewed, { harness: 'codex', configPath })).status).toBe('installed');
const entry = entryOf(configPath);
expect(entry.http_headers.Authorization).toBe('Bearer renewed-token-not-real');
expect(entry.tools).toEqual({ search: { approval_mode: 'approve' } });
- expect((await installHarnessConnection(credentials, { harness: 'codex', configPath })).status).toBe('installed');
+ expect((await install(credentials, { harness: 'codex', configPath })).status).toBe('installed');
expect(entryOf(configPath).tools).toEqual({ search: { approval_mode: 'approve' } });
});
test('approvals after the block renew in place; removal refuses rather than orphan them', async () => {
const root = temp(); const configPath = join(root, 'config.toml');
- await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ await install(credentials, { harness: 'codex', configPath });
writeFileSync(configPath, `${readFileSync(configPath, 'utf8')}\n${approval('get_page')}`);
- expect((await installHarnessConnection(renewed, { harness: 'codex', configPath })).status).toBe('installed');
+ expect((await install(renewed, { harness: 'codex', configPath })).status).toBe('installed');
expect(entryOf(configPath).tools).toEqual({ get_page: { approval_mode: 'approve' } });
expect(entryOf(configPath).http_headers.Authorization).toBe('Bearer renewed-token-not-real');
const before = readFileSync(configPath, 'utf8');
- await expect(installHarnessConnection(renewed, { harness: 'codex', configPath, remove: true })).rejects.toThrow('outside the gbrain-managed block');
+ await expect(install(renewed, { harness: 'codex', configPath, remove: true })).rejects.toThrow('outside the gbrain-managed block');
expect(readFileSync(configPath, 'utf8')).toBe(before);
});
test('a receipt that recorded the whole entry with its approvals still owns it', async () => {
const root = temp(); const configPath = join(root, 'config.toml');
- await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ await install(credentials, { harness: 'codex', configPath });
writeFileSync(configPath, readFileSync(configPath, 'utf8').replace(CODEX_TOML_BLOCK_END, `${approval('search')}${CODEX_TOML_BLOCK_END}`));
const receipt = JSON.parse(readFileSync(receiptPath(root), 'utf8'));
writeFileSync(receiptPath(root), JSON.stringify({ ...receipt, entry_hash: wholeHash(entryOf(configPath)) }));
- expect((await installHarnessConnection(renewed, { harness: 'codex', configPath })).status).toBe('installed');
+ expect((await install(renewed, { harness: 'codex', configPath })).status).toBe('installed');
});
test('approvals never bless other edits: a changed URL, header or execution key still refuses', async () => {
@@ -120,10 +127,10 @@ describe('#6799 Codex tool approvals ("always allow")', () => {
(t: string) => t.replace(CODEX_TOML_BLOCK_END, `[mcp_servers.gbrain.tools.search]\napproval_mode = { nested = "x" }\n${CODEX_TOML_BLOCK_END}`),
]) {
const root = temp(); const configPath = join(root, 'config.toml');
- await installHarnessConnection(credentials, { harness: 'codex', configPath });
+ await install(credentials, { harness: 'codex', configPath });
const edited = edit(readFileSync(configPath, 'utf8'));
writeFileSync(configPath, edited);
- await expect(installHarnessConnection(renewed, { harness: 'codex', configPath })).rejects.toThrow('edited');
+ await expect(install(renewed, { harness: 'codex', configPath })).rejects.toThrow('edited');
expect(readFileSync(configPath, 'utf8')).toBe(edited);
}
});
@@ -134,7 +141,7 @@ test('credentials and roots reject intermediate symlinks and credential-bearing
symlinkSync(real, join(root, 'alias'));
writeFileSync(join(real, 'credentials.json'), JSON.stringify(credentials), { mode: 0o600 });
expect(() => readCredentials(join(root, 'alias', 'credentials.json'))).toThrow('symlink');
- await expect(installHarnessConnection(credentials, { harness: 'muse', root: join(root, 'alias', 'new') })).rejects.toThrow('symlink');
+ await expect(install(credentials, { harness: 'muse', root: join(root, 'alias', 'new') })).rejects.toThrow('symlink');
expect(existsSync(join(real, 'new'))).toBe(false);
expect(() => validateCredentials({ ...credentials, issuer_url: 'https://[email protected]' })).toThrow('credentials');
expect(() => validateCredentials({ ...credentials, issuer_url: 'https://brain.example.com?token=private' })).toThrow('query');
diff --git a/test/helpers/inherited-ledger-guard.ts b/test/helpers/inherited-ledger-guard.ts
new file mode 100644
index 0000000000..a9dfb8e05e
--- /dev/null
+++ b/test/helpers/inherited-ledger-guard.ts
@@ -0,0 +1,18 @@
+import { afterAll, expect } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+const read = (path: string): string | null => { try { return readFileSync(path, 'utf8'); } catch { return null; } };
+
+/**
+ * Fails the file when one of its tests wrote the brain-first ledger of the GBRAIN_HOME the run inherited
+ * (a developer shell's real brain, or the preload's per-process scratch home): installer tests must give
+ * each install its own GBRAIN_HOME with withEnv (#8434).
+ */
+export function guardInheritedInstructionLedger(): void {
+ const home = process.env.GBRAIN_HOME;
+ if (!home) return;
+ const ledger = join(home, '.gbrain', 'agent-instructions.json');
+ const before = read(ledger);
+ afterAll(() => expect(read(ledger), `${ledger} changed during this file`).toBe(before));
+}
diff --git a/test/shared-skills-adapter.test.ts b/test/shared-skills-adapter.test.ts
index 0f2dca80cb..ca40b34cc5 100644
--- a/test/shared-skills-adapter.test.ts
+++ b/test/shared-skills-adapter.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, expect, test } from 'bun:test';
+import { afterEach, beforeEach, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -10,10 +10,17 @@ import { sha256 } from '../src/core/agent-install/state.ts';
import { installHarnessConnection } from '../src/core/harness/install.ts';
import type { HarnessCredentials } from '../src/core/harness/credentials.ts';
import { operations } from '../src/core/operations.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { guardInheritedInstructionLedger } from './helpers/inherited-ledger-guard.ts';
+
+guardInheritedInstructionLedger();
const roots: string[] = [];
const temp = () => { const root = mkdtempSync(join(tmpdir(), 'gbrain-shared-adapter-')); roots.push(root); return root; };
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+let ledgerHome = '';
+beforeEach(() => { ledgerHome = temp(); });
+const install: typeof installHarnessConnection = (c, opts) => withEnv({ GBRAIN_HOME: ledgerHome }, () => installHarnessConnection(c, opts));
function fixture() {
const brain = randomUUID(), incarnation = randomUUID(), installation = randomUUID();
@@ -216,7 +223,7 @@ test('connect install performs approved enrollment while preserving unrelated ha
const configPath = join(root, 'config.json');
writeFileSync(configPath, JSON.stringify({ identity: 'keep', mcpServers: { unrelated: { command: 'local-fixture' } } }));
const c: HarnessCredentials = { version: 1, mcp_url: 'https://brain.example.com/mcp', issuer_url: 'https://brain.example.com', client_id: 'fixture', access_token: 'synthetic-fixture-token', shared_skills: { follow: true } };
- const result = await installHarnessConnection(c, { harness: 'claude-code', configPath, toolCaller: f.call, nativeSkillsDir: join(root, 'native-skills') });
+ const result = await install(c, { harness: 'claude-code', configPath, toolCaller: f.call, nativeSkillsDir: join(root, 'native-skills') });
expect(result.shared_skills?.status).toBe('restart_required');
expect(f.calls).toContain('join_brain'); expect(f.calls).toContain('get_skill_asset');
const config = JSON.parse(readFileSync(configPath, 'utf8'));
@@ -226,7 +233,7 @@ test('connect install performs approved enrollment while preserving unrelated ha
test('memory-only install neither enrolls nor expands authority', async () => {
const root = temp(); const f = fixture();
const c: HarnessCredentials = { version: 1, mcp_url: 'https://brain.example.com/mcp', issuer_url: 'https://brain.example.com', client_id: 'fixture', access_token: 'synthetic-fixture-token', shared_skills: { follow: false } };
- const result = await installHarnessConnection(c, { harness: 'claude-code', configPath: join(root, 'config.json'), toolCaller: f.call });
+ const result = await install(c, { harness: 'claude-code', configPath: join(root, 'config.json'), toolCaller: f.call });
expect(result.shared_skills?.status).toBe('pending'); expect(f.calls).toEqual([]);
});
diff --git a/test/shared-skills-native-router.test.ts b/test/shared-skills-native-router.test.ts
index 6e642f3c8b..4576adf6c2 100644
--- a/test/shared-skills-native-router.test.ts
+++ b/test/shared-skills-native-router.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, expect, test } from 'bun:test';
+import { afterEach, beforeEach, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, symlinkSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -11,10 +11,16 @@ import type { HarnessCredentials } from '../src/core/harness/credentials.ts';
import type { SharedSkillsToolCaller } from '../src/core/shared-skills/adapter.ts';
import { readHarnessConnectionStatus } from '../src/core/harness/status.ts';
import { runCli } from './helpers/cli-spawn.ts';
+import { guardInheritedInstructionLedger } from './helpers/inherited-ledger-guard.ts';
+
+guardInheritedInstructionLedger();
const roots: string[] = [];
const temp = () => { const root = mkdtempSync(join(tmpdir(), 'gbrain-native-router-')); roots.push(root); return root; };
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+let ledgerHome = '';
+beforeEach(() => { ledgerHome = temp(); });
+const install: typeof installHarnessConnection = (c, opts) => withEnv({ GBRAIN_HOME: ledgerHome }, () => installHarnessConnection(c, opts));
const body = '---\nname: gbrain-shared-router\ndescription: Discover relevant authorized shared-brain skills.\n---\nUse only the named connection. Native use remains unverified.\n';
function fixture() {
@@ -47,7 +53,7 @@ for (const harness of ['claude-code', 'codex', 'opencode']) test(`${harness} con
expect(names.length).toBe(1);
expect(existsSync(join(expected, names[0], 'SKILL.md'))).toBe(true);
});
- const installed = await installHarnessConnection(f.credentials, { harness, toolCaller: f.call });
+ const installed = await install(f.credentials, { harness, toolCaller: f.call });
const shared = installed.shared_skills as any;
expect(shared.status).toBe('restart_required'); expect(shared.native_registration).toBe('installed'); expect(shared.native).toBe('unverified');
const path = shared.native_router_path as string;
@@ -55,10 +61,10 @@ for (const harness of ['claude-code', 'codex', 'opencode']) test(`${harness} con
const content = readFileSync(path, 'utf8'); const name = path.split('/').at(-2)!;
expect(content).toContain(`name: ${name}\n`); expect(content).toContain('enrollment_epoch 1');
expect(installed.native_harness_verified).toBe(false);
- const again = await installHarnessConnection(f.credentials, { harness, toolCaller: f.call });
+ const again = await install(f.credentials, { harness, toolCaller: f.call });
expect((again.shared_skills as any).native_router_path).toBe(path); expect(readFileSync(path, 'utf8')).toBe(content);
expect(readdirSync(expected).filter(p => p.startsWith('gbrain-shared-')).length).toBe(1);
- const removed = await installHarnessConnection(f.credentials, { harness, toolCaller: f.call, remove: true });
+ const removed = await install(f.credentials, { harness, toolCaller: f.call, remove: true });
expect(removed.shared_skills?.status).toBe('left'); expect(existsSync(path)).toBe(false);
expect(readFileSync(join(expected, 'unrelated', 'SKILL.md'), 'utf8')).toBe('User-owned skill');
});
@@ -67,15 +73,15 @@ for (const harness of ['claude-code', 'codex', 'opencode']) test(`${harness} con
test('native edits block reinstall before active-reference changes and survive leave', async () => {
const root = temp(), f = fixture();
const opts = { harness: 'codex', configPath: join(root, 'config.toml'), nativeSkillsDir: join(root, 'skills'), toolCaller: f.call };
- const first = await installHarnessConnection(f.credentials, opts);
+ const first = await install(f.credentials, opts);
const shared = first.shared_skills as any;
writeFileSync(shared.native_router_path, '# User edited native router');
const refPath = join(root, '.gbrain-codex-gbrain', 'shared-skills', 'active.json');
const before = readFileSync(refPath, 'utf8');
- const next = await installHarnessConnection(f.credentials, opts);
+ const next = await install(f.credentials, opts);
expect((next.shared_skills as any).reason).toBe('local_conflict');
expect(readFileSync(refPath, 'utf8')).toBe(before);
- const left = await installHarnessConnection(f.credentials, { ...opts, remove: true });
+ const left = await install(f.credentials, { ...opts, remove: true });
expect(left.shared_skills?.status).toBe('left_with_retained_files');
expect(readFileSync(shared.native_router_path, 'utf8')).toBe('# User edited native router');
});
@@ -122,10 +128,10 @@ test('manual harnesses have no invented native discovery directory', () => {
for (const edited of [false, true]) test(`expired credentials do not prevent local native cleanup (edited=${edited})`, async () => {
const root = temp(), f = fixture();
const opts = { harness: 'codex', configPath: join(root, 'config.toml'), nativeSkillsDir: join(root, 'skills') };
- const installed = await installHarnessConnection(f.credentials, { ...opts, toolCaller: f.call });
+ const installed = await install(f.credentials, { ...opts, toolCaller: f.call });
const path = (installed.shared_skills as { native_router_path: string }).native_router_path;
if (edited) writeFileSync(path, 'User edited native router');
- const result = await installHarnessConnection({ ...f.credentials, expires_at: 1 }, { ...opts, remove: true });
+ const result = await install({ ...f.credentials, expires_at: 1 }, { ...opts, remove: true });
expect(result.shared_skills.status).toBe(edited ? 'left_with_retained_files' : 'left');
expect('remote_membership_pending' in result && result.remote_membership_pending).toBe(true);
expect(existsSync(path)).toBe(edited);
@@ -136,7 +142,7 @@ for (const edited of [false, true]) test(`expired credentials do not prevent loc
test('connect status reads only the local receipt without credentials, network or writes', async () => {
const root = temp(), f = fixture();
await withEnv({ HOME: root, CLAUDE_CONFIG_DIR: join(root, '.claude') }, async () => {
- const installed = await installHarnessConnection(f.credentials, { harness: 'claude-code', toolCaller: f.call });
+ const installed = await install(f.credentials, { harness: 'claude-code', toolCaller: f.call });
const receipt = installed.shared_skills as { native_router_path: string; desired_view: string };
const before = readFileSync(receipt.native_router_path, 'utf8');
const status = await runCli(['connect', '--harness', 'claude-code', '--status', '--json'], { env: { HOME: root, CLAUDE_CONFIG_DIR: join(root, '.claude') } });