Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (launcher must serve every indexed skill; refresh keeps the recorded Claude profile; opt-out also strips the index at a moved Codex target; orphan skills marker no longer hides resolver rows; setup skill-loading tests get a 30 s timeout)
garrytan6e3f8abbe6e9
diff --git a/src/core/check-resolvable.ts b/src/core/check-resolvable.tsindex 937a93f329..4770182353 100644--- a/src/core/check-resolvable.ts+++ b/src/core/check-resolvable.ts@@ -153,8 +153,9 @@ export function parseResolverEntries(resolverContent: string): ResolverEntry[] {let currentSection = '';let inSkillsIndex = false;- for (const line of resolverContent.split('\n')) {- if (line.trim() === SKILLS_BLOCK_BEGIN) { inSkillsIndex = true; continue; }+ const lines = resolverContent.split('\n');+ for (const [i, line] of lines.entries()) {+ if (line.trim() === SKILLS_BLOCK_BEGIN && lines.slice(i + 1).some((l) => l.trim() === SKILLS_BLOCK_END)) { inSkillsIndex = true; continue; }if (line.trim() === SKILLS_BLOCK_END) { inSkillsIndex = false; continue; }if (inSkillsIndex) continue;// Track section headingsdiff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.tsindex e4e9f042ec..56124c8013 100644--- a/src/core/setup/skills-block.ts+++ b/src/core/setup/skills-block.ts@@ -34,7 +34,7 @@ import { bundledCatalogId, bundledSkills, type SkillAudience } from '../skills/bimport { shellQuote } from '../shell-quote.ts';import { renderSkillIndexBlock, SKILL_INDEX_VERSION, SkillIndexTooLarge, skillIndexCatalog } from '../skills/spring-index.ts';import { SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../skills/index-block.ts';-import { BRAIN_FIRST_END, brainFirstTargetAt, CURSOR_HEAD, direntExists, readBrainFirstLedger, writeUnlessChanged, type BrainFirstHarness, type BrainFirstTarget } from './brain-first.ts';+import { BRAIN_FIRST_END, brainFirstTargetAt, CURSOR_HEAD, direntExists, isProjectSurface, readBrainFirstLedger, writeUnlessChanged, type BrainFirstHarness, type BrainFirstTarget } from './brain-first.ts';export { SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END };export const SKILL_LOADING_ENV = 'GBRAIN_SKILL_LOADING';@@ -68,9 +68,9 @@ export function indexLauncher(): string | null {* from the ones indexed (another install earlier on PATH, a stale* --gbrain-bin). Engine-free and read-only on the launcher's side.*/-const servedCatalogs = new Map<string, { catalog: string } | { error: string }>();+const servedCatalogs = new Map<string, { catalog: string; names: string[] } | { error: string }>();-export function launcherCatalog(launcher: string): { catalog: string } | { error: string } {+export function launcherCatalog(launcher: string): { catalog: string; names: string[] } | { error: string } {if (!isAbsolute(launcher)) return { error: `${launcher} is not an absolute path (GUI-launched harnesses inherit no PATH)` };const known = servedCatalogs.get(launcher);if (known) return known;@@ -79,12 +79,13 @@ export function launcherCatalog(launcher: string): { catalog: string } | { errorreturn served;}-function askLauncher(launcher: string): { catalog: string } | { error: string } {+function askLauncher(launcher: string): { catalog: string; names: string[] } | { error: string } {const r = spawnSync(launcher, ['bundled-skill', '--json'], { encoding: 'utf8', timeout: 20_000 }) as { status: number | null; stdout?: string; stderr?: string; error?: Error };if (r.status !== 0) return { error: `${launcher} bundled-skill --json failed: ${(r.error?.message ?? r.stderr ?? '').trim().split('\n')[0] || `exit ${r.status}`}` };try {- const catalog = (JSON.parse(r.stdout ?? '') as { catalog?: unknown }).catalog;- return typeof catalog === 'string' ? { catalog } : { error: `${launcher} reported no skill catalog (a gbrain without bundled-skill)` };+ const { catalog, skills } = JSON.parse(r.stdout ?? '') as { catalog?: unknown; skills?: unknown };+ if (typeof catalog !== 'string') return { error: `${launcher} reported no skill catalog (a gbrain without bundled-skill)` };+ return { catalog, names: Array.isArray(skills) ? skills.map((s) => (s as { name?: unknown })?.name).filter((n): n is string => typeof n === 'string') : [] };} catch {return { error: `${launcher} bundled-skill --json printed no JSON` };}@@ -389,7 +390,7 @@ const message = (e: unknown) => (e instanceof Error ? e.message : String(e));* outcome with a reason, and the file is left as it was unless the detail* says otherwise.*/-export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; settingsPath?: string }): SkillsBlockOutcome {+export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; settingsPath?: string; thisFileOnly?: boolean }): SkillsBlockOutcome {const { target, launcher, decision } = opts;const settings = opts.settingsPath ?? claudeUserSettingsPath();const audience = opts.audience ?? 'owner';@@ -420,6 +421,11 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: strireturn out('preserve', `the skills markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`, { reason: 'damaged_markers' });}if (decision.value === 'off') {+ if (!target.project && !opts.thisFileOnly && decision.source !== 'default') {+ for (const other of readSkillLoadingLedger().filter((e) => e.harness === target.harness && e.path !== target.path && e.mode === 'spring' && !isProjectSurface(e.harness, e.path))) {+ syncSkillsBlock({ ...opts, target: { ...target, path: other.path }, audience: other.audience, settingsPath: other.allow_settings, thisFileOnly: true });+ }+ }if (decision.source === 'default' && !prior && (before.state === 'current' || before.state === 'stale')) {return out('skip', `the skills index in ${target.path} is not in this gbrain's record (${skillLoadingLedgerPath()}); another gbrain home or install probably wrote it, so it is left as it is. Pass --skill-loading off to remove it from here`);}@@ -455,6 +461,10 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: striif (served.catalog !== bundledCatalogId()) {return out('preserve', `${launcher} serves skill catalog ${served.catalog}, not this gbrain's ${bundledCatalogId()}, so the index would load other text than it lists; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>, or upgrade that install`, { reason: 'launcher_catalog_mismatch' });}+ const unserved = bundledSkills(audience).filter((s) => !served.names.includes(s.name)).map((s) => s.name);+ if (unserved.length) {+ return out('preserve', `${launcher} does not serve ${unserved.length} skill(s) the index would list (${unserved.slice(0, 5).join(', ')}${unserved.length > 5 ? ', …' : ''}), probably because it runs as a thin client; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of the gbrain this agent uses>`, { reason: 'launcher_catalog_mismatch' });+ }if (target.harness === 'hermes' && (before.state === 'no_file' || (() => { try { return readFileSync(target.path, 'utf8').trim() === ''; } catch { return true; } })())) {return out('skip', `${target.path} is missing or empty, and Hermes uses a non-empty SOUL.md instead of its default identity; start Hermes once (it seeds SOUL.md) or write your identity there, then re-run`, { reason: 'hermes_soul_missing' });}@@ -719,6 +729,8 @@ export function refreshSkillsIndexes(harness: BrainFirstHarness, opts: { mode?:decision: off ? { value: 'off', source: 'flag' } : { value: 'spring', source: opts.mode === 'spring' ? 'flag' : 'prior' },writer: e.writer,dryRun: opts.dryRun,+ settingsPath: e.allow_settings,+ thisFileOnly: true,}));if (!opts.dryRun || harness !== 'claude-code') return outcomes;// Each row previewed alone sees the others still owning a shared rule. When the batch drops that rule from everydiff --git a/test/check-resolvable.test.ts b/test/check-resolvable.test.tsindex 9027476756..859b63925e 100644--- a/test/check-resolvable.test.ts+++ b/test/check-resolvable.test.ts@@ -12,6 +12,11 @@ import {const SKILLS_DIR = join(import.meta.dir, "..", "skills");describe("parseResolverEntries", () => {+ test('an orphan skills-index begin marker does not hide the resolver entries after it', () => {+ const content = '## Brain\n<!-- gbrain:skills:begin -->\n- a stale line\n| "query the brain" | `skills/query/SKILL.md` |\n';+ expect(parseResolverEntries(content).map((e) => e.skillPath)).toContain('skills/query/SKILL.md');+ });+test("extracts skill paths from markdown table rows", () => {const content = `## Brain operations| Trigger | Skill |diff --git a/test/setup-skill-loading.test.ts b/test/setup-skill-loading.test.tsindex d7e7d0e9a9..84762ac048 100644--- a/test/setup-skill-loading.test.ts+++ b/test/setup-skill-loading.test.ts@@ -15,7 +15,7 @@* value is refused.* Spawns `bun src/cli.ts setup` against a temp HOME / GBRAIN_HOME.*/-import { afterAll, describe, expect, test } from 'bun:test';+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';@@ -25,6 +25,8 @@ import { BRAIN_FIRST_BEGIN, BRAIN_FIRST_END } from '../src/core/setup/brain-firsimport { inspectSkillsBlock, loaderAllowRule, renderSkillsBlock, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';import { bundledCatalogId, bundledSkills } from '../src/core/skills/bundled.ts';+// Each test spawns setup several times, and each spawn asks the launcher for its catalog; 5 s is too tight on a loaded shard.+setDefaultTimeout(30_000);const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');const BIN_DIR = mkdtempSync(join(tmpdir(), 'gbrain-skill-bin-'));const LAUNCHER = join(BIN_DIR, 'gbrain');@@ -237,6 +239,42 @@ describe('skill loading: launcher, permission and refresh', () => {expect(JSON.parse(read(cSettings)).permissions.allow).toEqual([rule, 'Read']);});+ test('an index is never written naming a gbrain that serves fewer skills than it lists (a thin-client launcher)', async () => {+ const b = box();+ const thin = join(BIN_DIR, 'gbrain-thin');+ writeFileSync(thin, `#!/bin/sh\necho '${JSON.stringify({ schema_version: 1, catalog: bundledCatalogId(), skills: bundledSkills('downstream').map((s) => ({ name: s.name })) })}'\n`);+ chmodSync(thin, 0o755);+ const r = await setup(b, ['claude-code', '--instructions-only', '--gbrain-bin', thin, '--skill-loading', 'spring']);+ expect(r.exitCode).toBe(1);+ expect(r.doc.skills).toMatchObject({ action: 'preserve', reason: 'launcher_catalog_mismatch' });+ expect(read(join(b.home, '.claude', 'CLAUDE.md'))).not.toContain(SKILLS_BLOCK_BEGIN);+ });++ test('--skills-index-only keeps the loader rule in the Claude profile the install recorded', async () => {+ const b = box();+ const profileA = join(b.home, 'profile-a'), profileB = join(b.home, 'profile-b');+ const rule = loaderAllowRule(LAUNCHER);+ await setup(b, ['claude-code', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'spring'], { CLAUDE_CONFIG_DIR: profileA });+ expect(JSON.parse(read(join(profileA, 'settings.json'))).permissions.allow).toEqual([rule]);+ const r = await setup(b, ['claude-code', '--skills-index-only'], { CLAUDE_CONFIG_DIR: profileB });+ expect(r.exitCode).toBe(0);+ expect(JSON.parse(read(join(profileA, 'settings.json'))).permissions.allow).toEqual([rule]);+ expect(existsSync(join(profileB, 'settings.json')) ? JSON.parse(read(join(profileB, 'settings.json'))).permissions?.allow ?? [] : []).not.toContain(rule);+ });++ test('codex --no-instructions also strips the index left in AGENTS.md after AGENTS.override.md took over', async () => {+ const b = box();+ const agents = join(b.home, '.codex', 'AGENTS.md');+ await setup(b, ['codex', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'spring']);+ expect(read(agents)).toContain(SKILLS_BLOCK_BEGIN);+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), '# override rules for alice-example\n');+ const r = await setup(b, ['codex', '--instructions-only', '--no-instructions', '--no-hooks']);+ expect(r.exitCode).toBe(0);+ expect(existsSync(agents) ? read(agents) : '').not.toContain(SKILLS_BLOCK_BEGIN);+ const ledger = JSON.parse(read(join(b.home, '.gbrain', 'skill-loading.json')));+ expect(ledger.entries.filter((e: { mode: string }) => e.mode === 'spring')).toEqual([]);+ });+test('codex gets no permission edit (its sandbox runs the read-only loader)', async () => {const b = box();await setup(b, ['codex', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'spring']);