Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sources harden: resolve _brain-filing-rules.json per repo instead of always using the bundled copy (#4018)
test45bd04ff9f35
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 48e561a83c..b1bb6b72ac 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -40,8 +40,9 @@ import { findResolverFile, RESOLVER_FILENAMES } from './resolver-filenames.ts';import { redactSecretsInText } from './minions/handlers/shell-redact.ts';import { ensureGbrainHome, resolveGbrainHome } from './gbrain-home.ts';import { binaryOnPath } from './execution-env.ts';-// Static import → bundled into the --compile binary so the taxonomy never drifts-// and needs no runtime skills/ directory.+import { loadFilingRules, type FilingRulesDoc } from './filing-audit.ts';+// Bundled into the --compile binary as the fallback taxonomy for repos that+// don't ship their own — see resolveFilingRules().import filingRulesDoc from '../../skills/_brain-filing-rules.json';// ── Types ───────────────────────────────────────────────────────────────────@@ -245,10 +246,26 @@ exit 4// ── Managed AGENTS/RESOLVER block (taxonomy from filing rules; no drift) ─────-function renderTaxonomyLines(): string {+/**+ * Resolve the filing-rules taxonomy for `repoPath`: prefer the repo's own+ * `skills/_brain-filing-rules.json`, then `_brain-filing-rules.json` at the+ * repo root, else the bundled default. Fails open — a missing or malformed+ * repo file must never break `sources harden`.+ */+function resolveFilingRules(repoPath: string): FilingRulesDoc {+ for (const dir of [join(repoPath, 'skills'), repoPath]) {+ try {+ const rules = loadFilingRules(dir);+ if (rules) return rules;+ } catch { /* malformed — fall through to the bundled default */ }+ }+ return filingRulesDoc as FilingRulesDoc;+}++function renderTaxonomyLines(rules: FilingRulesDoc): string {const seen = new Set<string>();const lines: string[] = [];- for (const r of (filingRulesDoc as any).rules ?? []) {+ for (const r of rules.rules ?? []) {const dir = String(r.directory || '').trim();if (!dir || seen.has(dir)) continue;seen.add(dir);@@ -257,7 +274,8 @@ function renderTaxonomyLines(): string {return lines.join('\n');}-function renderManagedBlock(): string {+function renderManagedBlock(repoPath: string): string {+ const rules = resolveFilingRules(repoPath);return `${AGENTS_BEGIN}<!-- gbrain durability rules. This block is regenerated by \`gbrain sources harden\`.Do not index as user knowledge; do not edit between the markers. -->@@ -265,7 +283,7 @@ function renderManagedBlock(): string {1. **Deterministic filing — never use /tmp as storage.** Every persistent outputgoes to its taxonomy path (canonical, from \`skills/_brain-filing-rules.json\`):-${renderTaxonomyLines()}+${renderTaxonomyLines(rules)}Writing to /tmp, scratch dirs, or outside the repo is forbidden for anythingmeant to persist.@@ -285,7 +303,7 @@ ${AGENTS_END}`;function patchResolverFile(repoPath: string, dryRun: boolean): { status: StepStatus; detail: string } {const existing = findResolverFile(repoPath);const target = existing ?? join(repoPath, RESOLVER_FILENAMES[1]); // default AGENTS.md- const block = renderManagedBlock();+ const block = renderManagedBlock(repoPath);const name = relative(repoPath, target) || target;let current = '';diff --git a/test/filing-rules-resolution.serial.test.ts b/test/filing-rules-resolution.serial.test.tsnew file mode 100644index 0000000000..43a1d508c4--- /dev/null+++ b/test/filing-rules-resolution.serial.test.ts@@ -0,0 +1,91 @@+/**+ * Per-repo filing-rules resolution (#4015): `sources harden` must render a+ * repo's OWN `skills/_brain-filing-rules.json` taxonomy into the managed+ * AGENTS/RESOLVER block, not the bundled default — falling back to the+ * bundled default only when the repo has no rules file, or that file is+ * malformed. Fixture mirrors brain-repo-durability.serial.test.ts (real git+ * against a local bare remote; HOME + GBRAIN_HOME redirected to a tmp dir).+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { execFileSync } from 'child_process';+import { hardenBrainRepo } 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();+}++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 });+}++function writeRepoRules(json: string): void {+ mkdirSync(join(work, 'skills'), { recursive: true });+ writeFileSync(join(work, 'skills', '_brain-filing-rules.json'), json);+ git(work, 'add', 'skills/_brain-filing-rules.json'); git(work, 'commit', '-qm', 'filing rules');+}++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'frr-'));+ oldHome = process.env.HOME; oldGbrainHome = process.env.GBRAIN_HOME;+ process.env.HOME = mkdtempSync(join(root, 'home-'));+ process.env.GBRAIN_HOME = join(process.env.HOME, '.gbrain');+ 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('per-source filing-rules resolution', () => {+ test('repo with its own skills/_brain-filing-rules.json → managed block carries that taxonomy', async () => {+ writeRepoRules(JSON.stringify({+ version: '1.0.0',+ rules: [{ kind: 'widget', directory: 'widgets/', description: 'A widget page.' }],+ }));+ await harden();+ const agents = readFileSync(join(work, 'AGENTS.md'), 'utf-8');+ expect(agents).toContain('`widgets/`');+ expect(agents).not.toContain('`people/`');+ });++ test('repo without a rules file → bundled default taxonomy (regression pin)', async () => {+ await harden();+ const agents = readFileSync(join(work, 'AGENTS.md'), 'utf-8');+ expect(agents).toContain('`people/`');+ });++ test('malformed JSON in the repo file → falls back to bundled default, no throw', async () => {+ writeRepoRules('{ this is not valid json');+ await harden(); // must not throw+ const agents = readFileSync(join(work, 'AGENTS.md'), 'utf-8');+ expect(agents).toContain('`people/`');+ });+});