Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(setup): re-read a recorded decision under the ledger lock; print paired removals; resolve the launcher catalog before the lock
garrytan9fc4bfb87da5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 570da5b59b..2e5b03d96f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,8 +16,8 @@ identifiers and attribution are available in the pre-removal Git revision### Itemized changes-- The brain-first and skill-loading ledgers share one lock (`~/.gbrain/agent-instructions.lock`), held across each install step: the ledger read, the file edit, the Claude Code permission edit and the ledger write (#8484). An install that cannot take it within 10 seconds, or cannot create it, changes nothing and reports why (the skills outcome's reason is `ledger_locked`). A dry run takes no lock.-- `gbrain setup codex --skill-loading off`, `--no-instructions` and `GBRAIN_SKILL_LOADING=off` also strip a spring index gbrain recorded in the other global instruction file of the same `CODEX_HOME` (`AGENTS.md` or `AGENTS.override.md`), and report it as a second skills line (`paired` in `--json`), in `--dry-run` too (#8485). A plain re-run strips nothing, and no other Codex home, OpenClaw workspace or Claude profile is touched.+- The brain-first and skill-loading ledgers share one lock (`~/.gbrain/agent-instructions.lock`), held across each install step: the ledger read, the file edit, the Claude Code permission edit and the ledger write (#8484). An install that waited reads the recorded choice again under the lock, so an opt-out the other install just recorded stays in force. An install that cannot take it within 10 seconds, or cannot create it, changes nothing and reports why (the skills outcome's reason is `ledger_locked`). A dry run takes no lock.+- `gbrain setup codex --skill-loading off`, `--no-instructions` and `GBRAIN_SKILL_LOADING=off` also strip a spring index gbrain recorded in the other global instruction file of the same `CODEX_HOME` (`AGENTS.md` or `AGENTS.override.md`), and report it as a second skills line in the plain output (`paired` in `--json`), in `--dry-run` too (#8485). A plain re-run strips nothing, and no other Codex home, OpenClaw workspace or Claude profile is touched.## [0.60.565.0] - 2026-11-03diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 9668cebf1f..1c358afb8b 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -856,7 +856,7 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}${'next' in turnHook && turnHook.next ? `; wire it with: ${turnHook.next}` : ''}`);else if (!off && placed) say(out, ` note ${'turn hook'.padEnd(7)} ${adapter.label} has no per-turn hook gbrain can install; the rule reaches it through ${target.path} only.`);- if (skills && (skills.decision.value === 'spring' || skills.action !== 'skip')) say(out, describeSkillsBlockOutcome(skills, flags.dryRun));+ if (skills && (skills.decision.value === 'spring' || skills.action !== 'skip' || skills.paired)) say(out, describeSkillsBlockOutcome(skills, flags.dryRun));if (check?.ok) say(out, ` verify ${'turn hook'.padEnd(7)} ${check.message}`);if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');@@ -922,7 +922,7 @@ async function finish(out: Out, doc: {return code;}if (doc.instructions) say(out, doc.remove ? describeBrainFirstOutcome(doc.instructions, doc.dryRun) : describeInstructions(doc.instructions, doc.dryRun));- if (doc.skills && (doc.skills.decision.value === 'spring' || doc.skills.action !== 'skip')) say(out, describeSkillsBlockOutcome(doc.skills, doc.dryRun));+ if (doc.skills && (doc.skills.decision.value === 'spring' || doc.skills.action !== 'skip' || doc.skills.paired)) say(out, describeSkillsBlockOutcome(doc.skills, doc.dryRun));if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);if (doc.turnHook?.ok) say(out, `Turn hook: ok (${doc.turnHook.reason}): ${doc.turnHook.message}`);if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex 8de8a82574..46aae72afe 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -282,12 +282,15 @@ let ledgerLockHeld = false;* permission edits it records, the ledger write) under a lock shared by this* ledger and skill-loading.json, so two installs at once cannot drop each* other's entry. Reentrant within a process (an opt-out that syncs another- * surface nests). A dry run writes nothing and takes no lock. When the lock is- * held past the wait, or the host cannot take it, nothing runs and `refused`- * reports why.+ * surface nests): `fn` learns whether it is the outermost transaction, the+ * one that re-reads a recorded decision another install may have changed+ * while this one waited. A dry run writes nothing and takes no lock. When the+ * lock is held past the wait, or the host cannot take it, nothing runs and+ * `refused` reports why.*/-export function underInstructionLedgerLock<T>(dryRun: boolean, fn: () => T, refused: (why: string) => T): T {- if (dryRun || ledgerLockHeld) return fn();+export function underInstructionLedgerLock<T>(dryRun: boolean, fn: (outermost: boolean) => T, refused: (why: string) => T): T {+ if (ledgerLockHeld) return fn(false);+ if (dryRun) return fn(true);const path = join(configDir(), LEDGER_LOCK_FILE);let lock: ReturnType<typeof acquireNativeLockSync>;try {@@ -298,10 +301,10 @@ export function underInstructionLedgerLock<T>(dryRun: boolean, fn: () => T, refuif (!lock) return refused(`another gbrain install is updating the instruction ledgers (it holds ${path}); re-run once it finishes`);ledgerLockHeld = true;try {- return fn();+ return fn(true);} finally {ledgerLockHeld = false;- lock.release();+ try { lock.release(); } catch { /* the OS drops the lock with the handle when the process exits */ }}}@@ -390,7 +393,10 @@ export function writeUnlessChanged(path: string, read: string, wasMissing: boole* of the install still finishes.*/export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFirstAccess; decision: BrainFirstDecision; writer: string; dryRun: boolean }): BrainFirstOutcome {- return underInstructionLedgerLock(opts.dryRun, () => syncBrainFirstLocked(opts), (why) => ({+ return underInstructionLedgerLock(opts.dryRun, (outermost) => {+ const recorded = opts.decision.source === 'prior' || opts.decision.source === 'default';+ return syncBrainFirstLocked(outermost && recorded ? { ...opts, decision: resolveBrainFirstDecision(undefined, priorBrainFirst(opts.target.harness, opts.target.path)) } : opts);+ }, (why) => ({harness: opts.target.harness, path: opts.target.path, role: opts.target.role, decision: opts.decision, action: 'preserve',state_before: inspectBrainFirst(opts.target.path).state, detail: `${why}; ${opts.target.path} was left as it was`,}));diff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.tsindex 0e65d2f864..82f60a8ded 100644--- a/src/core/setup/skills-block.ts+++ b/src/core/setup/skills-block.ts@@ -394,17 +394,35 @@ const message = (e: unknown) => (e instanceof Error ? e.message : String(e));* says otherwise.*/export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; settingsPath?: string }): SkillsBlockOutcome {- return underInstructionLedgerLock(opts.dryRun, () => {- const outcome = syncSkillsBlockLocked(opts);- const other = codexPairedIndex(opts.target, opts.decision);+ if (opts.decision.value === 'spring') launcherCatalog(opts.launcher);+ return underInstructionLedgerLock(opts.dryRun, (outermost) => {+ const run = { ...opts, decision: outermost ? recordedSkillLoading(opts.target, opts.decision) : opts.decision };+ const outcome = syncSkillsBlockLocked(run);+ const other = codexPairedIndex(run.target, run.decision);if (!other) return outcome;- return { ...outcome, paired: syncSkillsBlockLocked({ ...opts, target: { ...opts.target, path: other.path }, settingsPath: other.allow_settings }) };+ return { ...outcome, paired: syncSkillsBlockLocked({ ...run, target: { ...run.target, path: other.path }, settingsPath: other.allow_settings }) };}, (why) => ({harness: opts.target.harness, path: opts.target.path, decision: opts.decision, action: 'preserve',state_before: inspectSkillsBlock(opts.target.path).state, detail: `${why}; ${opts.target.path} was left as it was`, reason: 'ledger_locked',}));}+/**+ * A decision taken from the record (or the default) is read again under the+ * lock, so an install that waited for another one acts on what that one+ * recorded (an opt-out stays an opt-out). An unreadable ledger keeps the+ * decision; the sync reports the ledger itself.+ */+function recordedSkillLoading(target: BrainFirstTarget, decision: SkillLoadingDecision): SkillLoadingDecision {+ if (decision.source !== 'prior' && decision.source !== 'default') return decision;+ try {+ const prior = priorSkillLoading(target.harness, target.path);+ return prior ? { value: prior.mode, source: 'prior' } : { value: 'off', source: 'default' };+ } catch {+ return decision;+ }+}+/*** #8485: Codex loads its global AGENTS.override.md when it is non-empty, else* AGENTS.md, so the file setup resolves moves when the override appears ordiff --git a/test/instruction-ledger-lock.test.ts b/test/instruction-ledger-lock.test.tsindex 81c768585c..fc8f53dfce 100644--- a/test/instruction-ledger-lock.test.ts+++ b/test/instruction-ledger-lock.test.ts@@ -15,8 +15,8 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, wrimport { tmpdir } from 'node:os';import { join } from 'node:path';import { withEnv } from './helpers/with-env.ts';-import { brainFirstLedgerPath, brainFirstTargetAt, syncBrainFirst } from '../src/core/setup/brain-first.ts';-import { skillLoadingLedgerPath, syncSkillsBlock } from '../src/core/setup/skills-block.ts';+import { brainFirstLedgerPath, brainFirstTargetAt, priorBrainFirst, resolveBrainFirstDecision, syncBrainFirst } from '../src/core/setup/brain-first.ts';+import { priorSkillLoading, readSkillLoadingLedger, resolveSkillLoading, skillLoadingLedgerPath, syncSkillsBlock } from '../src/core/setup/skills-block.ts';import { SKILL_INDEX_VERSION } from '../src/core/skills/spring-index.ts';const roots: string[] = [];@@ -31,7 +31,9 @@ if (!lock) process.exit(3);const ledger = existsSync(ledgerPath) ? JSON.parse(readFileSync(ledgerPath, 'utf8')) : { version: 1, entries: [] };writeFileSync(marker, 'held');Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500);-ledger.entries.push(JSON.parse(entry));+const next = JSON.parse(entry);+ledger.entries = ledger.entries.filter((e) => !(e.harness === next.harness && e.path === next.path));+ledger.entries.push(next);writeFileSync(ledgerPath, JSON.stringify(ledger, null, 2) + '\n');lock.release();`;@@ -107,3 +109,50 @@ describe('#8484: concurrent installs keep every ledger entry', () => {});});});++describe('#8484: an install that waited acts on what the other one recorded', () => {+ const BIN = mkdtempSync(join(tmpdir(), 'gbrain-ledger-lock-bin-'));+ roots.push(BIN);+ const LAUNCHER = join(BIN, 'gbrain');+ writeFileSync(LAUNCHER, '#!/bin/sh\nexec \'' + process.execPath + '\' --no-env-file \'' + join(import.meta.dir, '..', 'src', 'cli.ts') + '\' "$@"\n');+ chmodSync(LAUNCHER, 0o755);++ test('skills: an opt-out recorded while this install waited is kept, and the index is not written back', async () => {+ const home = sandbox();+ await withEnv({ GBRAIN_HOME: home, HOME: home, GBRAIN_SKILL_LOADING: undefined }, async () => {+ const file = join(home, '.codex', 'AGENTS.md');+ const target = brainFirstTargetAt('codex', file);+ const first = syncSkillsBlock({ target, launcher: LAUNCHER, decision: { value: 'spring', source: 'flag' }, writer: 'gbrain setup codex', dryRun: false });+ expect(first.action).toBe('write');+ const stale = resolveSkillLoading(undefined, priorSkillLoading('codex', file));+ expect(stale).toEqual({ value: 'spring', source: 'prior' });+ const ledger = skillLoadingLedgerPath();+ const optOut = { ...readSkillLoadingLedger()[0], mode: 'off', writer: 'gbrain setup codex --skill-loading off' };+ const { exited } = await otherInstall(home, ledger, optOut);+ const out = syncSkillsBlock({ target, launcher: LAUNCHER, decision: stale, writer: 'gbrain setup codex', dryRun: false });+ expect(await exited).toBe(0);+ expect(out.decision).toEqual({ value: 'off', source: 'prior' });+ expect(readSkillLoadingLedger()[0]!.mode).toBe('off');+ });+ }, 60_000);++ test('brain-first: a decline recorded while this install waited is kept, and the block is not written back', async () => {+ const home = sandbox();+ await withEnv({ GBRAIN_HOME: home, HOME: home, GBRAIN_AGENT_INSTRUCTIONS: undefined }, async () => {+ const file = join(home, '.claude', 'CLAUDE.md');+ const target = brainFirstTargetAt('claude-code', file);+ const access = { kind: 'mcp' as const, server: 'gbrain' };+ expect(syncBrainFirst({ target, access, decision: { value: 'accepted', source: 'flag' }, writer: 'gbrain setup claude-code', dryRun: false }).action).toBe('write');+ const stale = resolveBrainFirstDecision(undefined, priorBrainFirst('claude-code', file));+ expect(stale).toEqual({ value: 'accepted', source: 'prior' });+ writeFileSync(file, '# My rules\n');+ const declined = { harness: 'claude-code', path: file, status: 'declined', block_version: 2, access, writer: 'gbrain setup claude-code --no-instructions', created_file: false, updated_at: '2026-11-03T00:00:00.000Z' };+ const { exited } = await otherInstall(home, brainFirstLedgerPath(), declined);+ const out = syncBrainFirst({ target, access, decision: stale, writer: 'gbrain setup claude-code', dryRun: false });+ expect(await exited).toBe(0);+ expect(out.decision).toEqual({ value: 'declined', source: 'prior' });+ expect(readFileSync(file, 'utf8')).toBe('# My rules\n');+ expect(priorBrainFirst('claude-code', file)?.status).toBe('declined');+ });+ }, 60_000);+});diff --git a/test/setup-skill-loading.test.ts b/test/setup-skill-loading.test.tsindex 379a5dfd02..e6828b45dd 100644--- a/test/setup-skill-loading.test.ts+++ b/test/setup-skill-loading.test.ts@@ -337,6 +337,16 @@ describe('skill loading: the Codex AGENTS.md / AGENTS.override.md pair (#8485)',expect(inspectSkillsBlock(join(otherHome, 'AGENTS.md')).state).toBe('current');});+ test('the plain-text setup output names the paired removal', async () => {+ const b = box();+ const agents = join(b.home, '.codex', 'AGENTS.md');+ await codex(b, ['--skill-loading', 'spring']);+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), '# Override rules\n');+ const r = await runCli(['setup', 'codex', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'off'], { env: b.env, cwd: b.project });+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain(`skills index from ${agents}`);+ });+test('--no-instructions after the override took over also strips the index from AGENTS.md', async () => {const b = box();const agents = join(b.home, '.codex', 'AGENTS.md');