Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.45.9.0 fix(bootstrap): preview source_id + create brain/ eagerly in hooks phase (#4064)
Masa3eccd4ccd663
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 9bcc9af6b9..7863515470 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -109,9 +109,15 @@ you needed; report the count at the end (it feeds the install-time measurement).4. **Render.** `gbrain bootstrap render` — identity files appear. Show the humanSOUL.md. Existing files are never overwritten (re-runs are safe; `--force`backs up first).-5. **Skills + brain wiring.** The CLI scaffolds the skill set and registers- `brain/` as the workspace source. Nothing to judge here; relay the output.-6. **Wire the harness.** `gbrain bootstrap hooks --harness <detected>`:+5. **Skills.** `gbrain skillpack scaffold --all` — the CLI scaffolds the skill+ set. Nothing to judge here; relay the output.+6. **Wire the harness + register the brain source.** `gbrain bootstrap hooks+ --harness <detected>` creates `<workspace>/brain` and prints the exact+ `gbrain sources add <source_id> --path <brain> --force` command for THIS+ workspace — run it verbatim (don't guess a different id; a guessed id+ only surfaces as an FK error at `verify` time, by which point a wrong+ guess also blocks the correct id with an `overlapping_path` error). It+ also:- Claude Code: installs per-turn hooks ON by default — do NOT ask; loading thebrain every turn is the whole point of installing gbrain for your agent. Tellthe human it is on and how to turn it off (`GBRAIN_HOOKS=0`, or re-run withdiff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex 1dc76bcb1e..3a9ae4544c 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -74,7 +74,7 @@ import {statusReport,type StatusReport,} from '../core/bootstrap/status.ts';-import { verifyWorkspace } from '../core/bootstrap/verify.ts';+import { verifyWorkspace, deriveWorkspaceSourceId } from '../core/bootstrap/verify.ts';export const BOOTSTRAP_HELP = `gbrain bootstrap — paste-in agent install (Claude Code / Codex)@@ -208,6 +208,19 @@ function resolveWorkspace(args: string[]): string {return ws ? resolve(ws) : process.cwd();}+/**+ * POSIX single-quote anything not already shell-safe, for commands printed+ * as copy/paste guidance (mirror of the private `shellQuote` in+ * core/bootstrap/hooks.ts, core/sources-ops.ts, and commands/connect.ts —+ * same contract: `$()`/backticks in a value are inert literals once quoted).+ * A workspace path containing a space or shell metacharacter must not turn+ * "the exact command to run" into a broken (or, pasted blind, dangerous) one.+ */+function shellQuoteForDisplay(arg: string): string {+ if (/^[A-Za-z0-9_.:/@=-]+$/.test(arg)) return arg;+ return `'${arg.replace(/'/g, "'\\''")}'`;+}+// ── Shared plumbing ─────────────────────────────────────────────────────────type Harness = 'claude-code' | 'codex';@@ -789,6 +802,41 @@ async function runHooks(ws: string, rest: string[], home: string, runner: ExecRuconst gbrainHome = process.env.GBRAIN_HOME?.trim() || undefined;return withLock(ws, async () => {+ // 0. source_id visibility seam: `hooks` is the last ENGINE-FREE phase+ // before `verify` (which alone can detect a source_id collision — the+ // sources registry lives only in the DB). Without this, a human who+ // hand-registers a source before verify has no way to know the exact id+ // the workspace expects, guesses an "intuitive" name instead, and only+ // discovers the mismatch via a `verify` roundtrip FK error — then, after+ // switching to the manifest's id, an `overlapping_path` error from the+ // earlier guess still claiming the same brain/ dir. Printing the current+ // id (and the collision-fallback id verify would derive, a pure path+ // hash that needs no engine) up front — plus creating brain/ so+ // registration can happen immediately — collapses that multi-round-trip+ // loop to one command.+ const brainDir = join(ws, 'brain');+ mkdirSync(brainDir, { recursive: true });+ // --force: brain/ was just created empty — `sources add` fail-fasts on a+ // --path that exists but isn't a git repo with committed, tracked+ // content (#2707), and gbrain deliberately never auto-git-inits a --path+ // source itself (a --path source is the user's own directory — the+ // consent boundary #2967 established for sync-time self-heal applies+ // here too). --force is the sanctioned opt-in for exactly this "register+ // before git-init exists" case (see sources-ops.ts's own not_a_git_repo+ // message), and it is safe here because brainDir is not an arbitrary+ // user path — it is the fixed `<workspace>/brain` subdir this phase just+ // created. Without --force, the printed command below would itself throw+ // not_a_git_repo the instant it's pasted.+ const quoted = shellQuoteForDisplay(brainDir);+ console.log(+ `brain source: register this workspace's brain/ now if you haven't — ` ++ `\`gbrain sources add ${sourceId} --path ${quoted} --force\` (brain/ is freshly created and empty; ` ++ `--force is the documented opt-in for registering before git-init exists). If '${sourceId}' is ` ++ `already claimed by a different checkout on this brain, \`gbrain bootstrap verify\` will detect the ` ++ `collision and switch this workspace to '${deriveWorkspaceSourceId(ws)}' — re-run the same command ` ++ `with that id instead.`,+ );+// 1. MCP registration — argv built by the host-format module, executed// through the runner seam, recorded on the receipt.const argvs =diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex a1812a8be0..1fb929106e 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -477,16 +477,33 @@ function checkMcpSurface(): VerifyCheck {}}+/**+ * Pure, engine-free derivation of the collision-fallback source_id for a+ * workspace — a deterministic hash of the workspace's real path, no DB+ * lookup involved. `resolveSourceIdCollision` (below) is the only thing that+ * decides WHETHER this id is actually needed (that half requires the engine,+ * since the sources registry lives only in the DB) — but the id itself is+ * safe to preview from an engine-free phase. `bootstrap hooks` does exactly+ * that, so a human has the fallback id in hand before they ever hand-register+ * a source, instead of discovering it only after an FK error + a corrective+ * `verify` run.+ */+export function deriveWorkspaceSourceId(ws: string): string {+ const hash = createHash('sha256').update(realpathOrResolve(ws)).digest('hex').slice(0, 8);+ return `workspace-${hash}`;+}+/*** source_id collision resolution [engine seam]. Render is ENGINE-FREE and the* sources registry lives ONLY in the DB (no registry file exists), so verify —* the one bootstrap subcommand holding an engine — is where a manifest* source_id already registered to a DIFFERENT checkout is detected. On- * collision it derives a stable `workspace-<8char-path-hash>` id, persists it- * to agent.json (render preserves it on re-render), and names the re-register- * steps; every consumer (hooks GBRAIN_SOURCE env, verify, status hints,- * attach, repo persistence) reads manifest.source_id, so the derived id- * propagates. Returns a sourceId ONLY when it derived one.+ * collision it derives a stable `workspace-<8char-path-hash>` id (via+ * `deriveWorkspaceSourceId`), persists it to agent.json (render preserves it+ * on re-render), and names the re-register steps; every consumer (hooks+ * GBRAIN_SOURCE env, verify, status hints, attach, repo persistence) reads+ * manifest.source_id, so the derived id propagates. Returns a sourceId ONLY+ * when it derived one.*/async function resolveSourceIdCollision(engine: BrainEngine,@@ -506,8 +523,7 @@ async function resolveSourceIdCollision(if (realpathOrResolve(registered) === realpathOrResolve(brainDir)) {return { sourceId: null, check: null }; // same checkout — no collision}- const hash = createHash('sha256').update(realpathOrResolve(ws)).digest('hex').slice(0, 8);- const derived = `workspace-${hash}`;+ const derived = deriveWorkspaceSourceId(ws);writeManifest(ws, { ...state.manifest, source_id: derived });return {sourceId: derived,diff --git a/test/bootstrap-dispatcher.serial.test.ts b/test/bootstrap-dispatcher.serial.test.tsindex 6b8a27a873..832dfc68f5 100644--- a/test/bootstrap-dispatcher.serial.test.ts+++ b/test/bootstrap-dispatcher.serial.test.ts@@ -22,6 +22,7 @@ import { runBootstrap, workspaceBrainStats } from '../src/commands/bootstrap.ts'import type { ExecRunner } from '../src/core/bootstrap/repo.ts';import { attachWorkspace } from '../src/core/bootstrap/attach.ts';import { readReceipt, receiptPath, writeManifest, type InstallReceipt } from '../src/core/bootstrap/format.ts';+import { deriveWorkspaceSourceId } from '../src/core/bootstrap/verify.ts';import { initState, setAnswer, skipAnswer, confirm, readBackHash } from '../src/core/bootstrap/interview.ts';let tmpParent: string; // GBRAIN_HOME parent (configDir appends .gbrain)@@ -121,6 +122,147 @@ describe('consent-skip is a decline (HOOKS_CONSENT)', () => {}, 30_000);});+describe('hooks previews the source_id + creates brain/ eagerly [defect: multi-round-trip source registration]', () => {+ // Self-contained fixtures (same pattern as the flip block below): the+ // file-level `ws` is shared by other describes, so this needs its own.+ const scratch: string[] = [];+ function freshWorkspace(): { fws: string; fhome: string; fparent: string } {+ const fparent = mkdtempSync(join(tmpdir(), 'gb-srcid-'));+ const fhome = join(fparent, '.gbrain');+ mkdirSync(fhome, { recursive: true });+ const fws = mkdtempSync(join(tmpdir(), 'gb-srcid-ws-'));+ scratch.push(fparent, fws);+ const prev = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = fparent;+ try {+ expect(initState(fws).ok).toBe(true);+ for (const [key, value] of Object.entries(REQUIRED_ANSWERS)) {+ const r = setAnswer(fws, key, value);+ if (!r.ok) throw new Error(r.message);+ }+ expect(setAnswer(fws, 'MCP_SCOPE', 'project').ok).toBe(true);+ const h = readBackHash(fws);+ if (!h.ok) throw new Error(h.message);+ expect(confirm(fws, h.hash).ok).toBe(true);+ } finally {+ if (prev === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prev;+ }+ return { fws, fhome, fparent };+ }+ afterAll(() => {+ for (const d of scratch) rmSync(d, { recursive: true, force: true });+ });++ async function withHome<T>(parent: string, fn: () => Promise<T>): Promise<T> {+ const prev = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = parent;+ try {+ return await fn();+ } finally {+ if (prev === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prev;+ }+ }++ test('hooks prints the exact `sources add` command up front and creates brain/ before verify ever runs', async () => {+ const { fws, fparent } = freshWorkspace();+ const brainDir = join(fws, 'brain');+ const out = await withHome(fparent, async () => {+ expect((await capture(() => runBootstrap(['render', '--workspace', fws]))).result).toBe(0);+ // render is engine-free and never touches brain/ — the gap this fix closes.+ expect(existsSync(brainDir)).toBe(false);+ const { runner } = makeRunner();+ return capture(() =>+ runBootstrap(['hooks', '--workspace', fws, '--harness', 'claude-code', '--gbrain-bin', process.execPath], {+ runner,+ }),+ );+ });+ expect(out.result).toBe(0);+ // brain/ now exists — ready for `sources add` without a manual mkdir+ // round trip.+ expect(existsSync(brainDir)).toBe(true);+ // The manifest's actual source_id (default: 'workspace' for a first+ // render) is spelled out verbatim — no guessing an "intuitive" name that+ // would only surface as an FK error three steps later at verify time.+ // --force is required and printed: brain/ is freshly created and has no+ // git history yet, so `sources add` without --force would fail-fast on+ // `not_a_git_repo` (#2707) the instant the printed command is pasted —+ // the exact same `{ force: true }` the engine-backed verify fixtures use+ // to register a brand new brain/ (test/bootstrap-verify.serial.test.ts).+ expect(out.out).toContain(`gbrain sources add workspace --path ${brainDir} --force`);+ // The collision-fallback id is previewed too, pinned to the SAME formula+ // verify.ts would derive (not just the id's shape) — so preview/verify+ // drift, or a change to the derivation formula, fails this test.+ expect(out.out).toContain(`'${deriveWorkspaceSourceId(fws)}'`);+ expect(deriveWorkspaceSourceId(fws)).toMatch(/^workspace-[0-9a-f]{8}$/);+ }, 30_000);++ test('a --repair re-run is idempotent: brain/ survives, the same preview reprints', async () => {+ const { fws, fparent } = freshWorkspace();+ const brainDir = join(fws, 'brain');+ await withHome(fparent, async () => {+ expect((await capture(() => runBootstrap(['render', '--workspace', fws]))).result).toBe(0);+ expect((await capture(() => runBootstrap(['hooks', '--workspace', fws, '--harness', 'claude-code', '--gbrain-bin', process.execPath], { runner: makeRunner().runner }))).result).toBe(0);+ // Simulate the human having already registered + committed into brain/.+ writeFileSync(join(brainDir, 'probe.md'), '# probe\n');+ const repaired = await capture(() =>+ runBootstrap(+ ['hooks', '--workspace', fws, '--harness', 'claude-code', '--repair', '--gbrain-bin', process.execPath],+ { runner: makeRunner().runner },+ ),+ );+ expect(repaired.result).toBe(0);+ expect(repaired.out).toContain(`gbrain sources add workspace --path ${brainDir} --force`);+ // Idempotent mkdir never clobbers what the human already committed.+ expect(existsSync(join(brainDir, 'probe.md'))).toBe(true);+ });+ }, 30_000);++ test('a workspace path containing a space is shell-quoted in the printed command', async () => {+ const fparent = mkdtempSync(join(tmpdir(), 'gb-srcid-space-'));+ scratch.push(fparent);+ const fhome = join(fparent, '.gbrain');+ mkdirSync(fhome, { recursive: true });+ const fwsRoot = mkdtempSync(join(tmpdir(), 'gb-srcid-space-root-'));+ scratch.push(fwsRoot);+ const fws = join(fwsRoot, 'has space');+ mkdirSync(fws, { recursive: true });+ const prev = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = fparent;+ try {+ expect(initState(fws).ok).toBe(true);+ for (const [key, value] of Object.entries(REQUIRED_ANSWERS)) {+ const r = setAnswer(fws, key, value);+ if (!r.ok) throw new Error(r.message);+ }+ expect(setAnswer(fws, 'MCP_SCOPE', 'project').ok).toBe(true);+ const h = readBackHash(fws);+ if (!h.ok) throw new Error(h.message);+ expect(confirm(fws, h.hash).ok).toBe(true);+ } finally {+ if (prev === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prev;+ }+ const brainDir = join(fws, 'brain');+ const out = await withHome(fparent, async () => {+ expect((await capture(() => runBootstrap(['render', '--workspace', fws]))).result).toBe(0);+ const { runner } = makeRunner();+ return capture(() =>+ runBootstrap(['hooks', '--workspace', fws, '--harness', 'claude-code', '--gbrain-bin', process.execPath], {+ runner,+ }),+ );+ });+ expect(out.result).toBe(0);+ // A bare, unquoted path with a space would split into two shell words —+ // the printed command must single-quote it so copy/paste actually works.+ expect(out.out).toContain(`--path '${brainDir}' --force`);+ expect(out.out).not.toContain(`--path ${brainDir} --force`);+ }, 30_000);+});+describe('per-turn hooks are ON by default (v0.45 flip); --no-hooks opts out', () => {// Self-contained fixtures: the file-level `ws` deliberately SKIPS// HOOKS_CONSENT (for the decline test), so the default-on path needs a