Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(hook): versioned pre-commit hook validates staged blobs in one call (#5988)
garrytane7c2c2bc364b
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 6003a8c4d7..a3c29f2dfb 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -39,4 +39,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/friction.ts` + `src/core/friction.ts` — `gbrain friction {log,render,list,summary,diff}` reporter. Append-only JSONL under `$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError`; every claw-test run opens with a `phase-marker`/`start` meta record carrying `agent` + `scenario` + `harness_schema` (agent-name resolution depends on it). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). `diff --base <run-or-agent> --compare <run-or-agent>` is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is `(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)` over `kind ∈ {friction, delight}` as MULTISETS (per-severity counts + totals are the compared attributes: `count_changed` = volume, `severity_changed` = distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to <run>" — an instrument, never a blame-attributor. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises carry a `_friction-protocol.md` callout so agents know when to log friction.-- `src/commands/frontmatter-install-hook.ts` — `gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]`: writes the frontmatter pre-commit hook at `<git root>/.githooks/pre-commit` and sets `core.hooksPath` when unset. The root comes from `discoverGitRoot` (the same `git rev-parse --show-toplevel` walk `gbrain sync` uses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's `<workspace>/brain`) is accepted rather than skipped: the hook lands at the host root with `git diff --cached` limited to that subdirectory via shell-quoted git pathspecs, recorded as `# gbrain-scope: <dir>/` marker lines (one per guarded scope). The script lists staged paths with `-z | tr '\0' '\n'` and walks them in a `while IFS= read -r` loop fed by a heredoc (POSIX sh, no subshell), so names with spaces or non-ASCII characters are validated instead of silently skipped by word-splitting or git's `core.quotePath` quoting; a newline inside a filename is the one unsupported shape. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script (no marker, byte-identical to the single-repo form) and owns the whole hook. A foreign `.githooks/pre-commit` still needs `--force` (`.bak` saved, restored on uninstall). Both install and uninstall resolve the hook location through `hookPaths(root)`, which lstat-refuses a symlinked `.githooks/` or `pre-commit` (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a `skipped` line and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write, `--force` overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while `core.hooksPath` is per-clone config: a fresh clone of a repo that committed the hook reports `installed` (and gets wired) rather than `unchanged` while inert; `unchanged` means current AND wired. Before wiring `core.hooksPath`, `hooksPathBlocker(root)` returns the operator-facing reason wiring is unsafe, or null: a `core.hooksPath` already set (any scope — a global/corporate value counts; `--type=path`-expanded and resolved against the root) to anywhere that does not realpath to `.githooks` (theirs to keep; git never reads `.githooks/` then, so `installed` would lie — one that resolves to `.githooks` is left alone and counts as wired), a foreign executable under `.githooks/` (wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (`activeGitHooks` — executable non-`*.sample` entries under `<git rev-parse --git-common-dir>/hooks`, worktree-safe and, unlike `--git-path hooks`, immune to a foreign `core.hooksPath`; wiring would make git ignore `.git/hooks/*` for every hook type). Every git spawn in the module goes through one `git(root, args)` helper that passes `env: process.env` (Bun's default child env is a startup snapshot; Node's is live), so `GIT_CONFIG_*` overrides from `withEnv` reach the child. Any blocker returns `installed_unwired` — the hook is written, `core.hooksPath` stays untouched, and the CLI prints the reason + the manual `git config core.hooksPath .githooks` step. Pinned by `test/frontmatter-install-hook.test.ts`.+- `src/commands/frontmatter-install-hook.ts` — `gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]`: writes the frontmatter pre-commit hook at `<git root>/.githooks/pre-commit` and sets `core.hooksPath` when unset. The root comes from `discoverGitRoot` (the same `git rev-parse --show-toplevel` walk `gbrain sync` uses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's `<workspace>/brain`) is accepted rather than skipped: the hook lands at the host root with `git diff --cached` limited to that subdirectory via shell-quoted git pathspecs, recorded as `# gbrain-scope: <dir>/` marker lines (one per guarded scope). The script carries `# gbrain-hook-version: N` (`FRONTMATTER_HOOK_VERSION`; no marker = version 1, which validated working-tree bytes), lists staged paths with `-z | tr '\0' '\n'`, collects them in a heredoc-fed `while IFS= read -r` loop (spaces and non-ASCII names survive; a newline inside a name is unsupported) and runs ONE `gbrain frontmatter validate --staged -- <paths>`, which checks the staged blobs under the strict producer rule and names failures as staged content. `inspectFrontmatterHook(localPath, sourceId?)` (read-only) returns the installed gbrain hook's version, `current`, and the `install-hook --force` refresh argv for doctor and post-upgrade. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script and owns the whole hook. A foreign `.githooks/pre-commit` still needs `--force` (`.bak` saved, restored on uninstall). Both install and uninstall resolve the hook location through `hookPaths(root)`, which lstat-refuses a symlinked `.githooks/` or `pre-commit` (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a `skipped` line and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write, `--force` overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while `core.hooksPath` is per-clone config: a fresh clone of a repo that committed the hook reports `installed` (and gets wired) rather than `unchanged` while inert; `unchanged` means current AND wired. Before wiring `core.hooksPath`, `hooksPathBlocker(root)` returns the operator-facing reason wiring is unsafe, or null: a `core.hooksPath` already set (any scope — a global/corporate value counts; `--type=path`-expanded and resolved against the root) to anywhere that does not realpath to `.githooks` (theirs to keep; git never reads `.githooks/` then — one resolving to `.githooks` counts as wired), a foreign executable under `.githooks/` (wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (`activeGitHooks` — executable non-`*.sample` entries under `<git rev-parse --git-common-dir>/hooks`, immune to a foreign `core.hooksPath`; wiring would make git ignore them). Every git spawn passes `env: process.env` (Bun's default child env is a startup snapshot), so `GIT_CONFIG_*` overrides reach the child. Any blocker returns `installed_unwired` — the hook is written, `core.hooksPath` stays untouched, and the CLI prints the reason + the manual `git config core.hooksPath .githooks` step. Pinned by `test/frontmatter-install-hook.test.ts`.diff --git a/src/commands/frontmatter-install-hook.ts b/src/commands/frontmatter-install-hook.tsindex 9801039aaa..2173bfd00d 100644--- a/src/commands/frontmatter-install-hook.ts+++ b/src/commands/frontmatter-install-hook.ts@@ -41,6 +41,13 @@ import { discoverGitRoot } from '../core/sync-git.ts';const HOOK_BANNER = '# gbrain frontmatter pre-commit hook (v0.22.4+)';/** One line per guarded subdirectory (root-relative, trailing slash). No lines = whole repo. */const SCOPE_MARKER = '# gbrain-scope: ';+const VERSION_MARKER = '# gbrain-hook-version: ';+/**+ * Bump when the generated script changes behavior. 2: one+ * `gbrain frontmatter validate --staged` process checks the staged blobs.+ * A gbrain hook without the marker is version 1 (validated working-tree bytes).+ */+export const FRONTMATTER_HOOK_VERSION = 2;const shellQuote = (s: string): string => `'${s.replace(/'/g, "'\\''")}'`;@@ -64,10 +71,11 @@ const git = (root: string, args: string[]): string =>execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', env: process.env }).trim();/**- * Render the hook script. Empty `scopes` = the whole repo (byte-identical to- * the pre-#4600 script); otherwise `git diff --cached` is limited to the- * listed pathspecs. Git runs hooks from the worktree root, so the- * root-relative paths it lists resolve as-is for `gbrain frontmatter validate`.+ * Render the hook script. Empty `scopes` = the whole repo; otherwise+ * `git diff --cached` is limited to the listed pathspecs. Git runs hooks from+ * the worktree root, so the root-relative paths it lists resolve as-is for+ * `gbrain frontmatter validate --staged`, which checks the staged blobs (not+ * the working-tree bytes) of all of them in one process.*/function renderHookScript(scopes: string[]): string {scopes.forEach(assertNoLineTerminator);@@ -75,7 +83,8 @@ function renderHookScript(scopes: string[]): string {const pathspec = scopes.length > 0 ? ` -- ${scopes.map(shellQuote).join(' ')}` : '';return `#!/bin/sh${HOOK_BANNER}-${marker}# Validates YAML frontmatter on staged .md / .mdx files. Bypass with+${VERSION_MARKER}${FRONTMATTER_HOOK_VERSION}+${marker}# Validates the staged YAML frontmatter of .md / .mdx files. Bypass with# 'git commit --no-verify'. Uninstall with 'gbrain frontmatter install-hook --uninstall'.set -e@@ -88,29 +97,67 @@ fi# One path per line: -z disables git's quoting (a non-ASCII name would print# as "caf\\303\\251.md"), tr turns the NUL terminators into newlines, and the# read loop keeps spaces intact (a newline INSIDE a name is the one unsupported-# shape). The heredoc keeps the loop in this shell so 'failed' survives it.+# shape). The heredoc keeps the loop in this shell so the argument list survives it.staged=$(git diff --cached --name-only -z --diff-filter=ACM${pathspec} | tr '\\0' '\\n' | grep -E '\\.mdx?$' || true)[ -z "$staged" ] && exit 0-failed=0+set --while IFS= read -r f; do- [ -f "$f" ] || continue- if ! gbrain frontmatter validate "$f" >/dev/null 2>&1; then- gbrain frontmatter validate "$f" >&2- failed=1- fi+ if [ -n "$f" ]; then set -- "$@" "$f"; fidone <<EOF$stagedEOF+[ $# -eq 0 ] && exit 0-if [ $failed -ne 0 ]; then+if ! report=$(gbrain frontmatter validate --staged -- "$@" 2>&1); then+ printf '%s\\n' "$report" >&2echo "" >&2- echo "Frontmatter validation failed. Run 'gbrain frontmatter validate <file> --fix' to repair, or 'git commit --no-verify' to bypass." >&2+ echo "Frontmatter validation failed for the staged content above. Fix each file ('gbrain frontmatter validate <file> --fix'; on a managed brain 'gbrain repair frontmatter --source <id>'), then restage it with 'git add <file>'. Bypass once with 'git commit --no-verify'." >&2exit 1fi`;}+/**+ * The generated-script version of an installed hook: null when the content+ * is not a gbrain frontmatter hook, 1 for gbrain hooks written before the marker.+ */+export function frontmatterHookVersion(hook: string): number | null {+ if (!hook.includes(HOOK_BANNER)) return null;+ const line = hook.split('\n').find((l) => l.startsWith(VERSION_MARKER));+ const version = line ? Number(line.slice(VERSION_MARKER.length).trim()) : 1;+ return Number.isInteger(version) && version > 0 ? version : 1;+}++export interface InstalledFrontmatterHook {+ hookPath: string;+ version: number;+ current: boolean;+ /** Present when outdated: refreshes the script (an existing gbrain hook is replaced without a .bak). */+ fix?: string[];+}++/**+ * The gbrain pre-commit hook guarding `localPath`, read-only: null when the+ * path is outside git, the hook path is a symlink, or no gbrain hook is+ * installed at its root. Doctor and post-upgrade use `current` to recommend+ * `gbrain frontmatter install-hook --force`.+ */+export function inspectFrontmatterHook(localPath: string, sourceId?: string): InstalledFrontmatterHook | null {+ let hookPath: string;+ try {+ hookPath = hookPaths(resolveHookTarget(localPath).root).hookPath;+ } catch {+ return null;+ }+ if (!existsSync(hookPath)) return null;+ const version = frontmatterHookVersion(readFileSync(hookPath, 'utf8'));+ if (version === null) return null;+ const current = version >= FRONTMATTER_HOOK_VERSION;+ return { hookPath, version, current,+ ...(current ? {} : { fix: ['gbrain', 'frontmatter', 'install-hook', ...(sourceId ? ['--source', sourceId] : []), '--force'] }) };+}+function parseScopes(hook: string): string[] {return hook.split('\n')diff --git a/test/frontmatter-install-hook.test.ts b/test/frontmatter-install-hook.test.tsindex 51ea2a1046..6c0fa75c86 100644--- a/test/frontmatter-install-hook.test.ts+++ b/test/frontmatter-install-hook.test.ts@@ -3,7 +3,9 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSyncimport { join } from 'path';import { tmpdir } from 'os';import { execFileSync } from 'child_process';-import { activeGitHooks, installHook, uninstallHook } from '../src/commands/frontmatter-install-hook.ts';+import {+ activeGitHooks, FRONTMATTER_HOOK_VERSION, frontmatterHookVersion, inspectFrontmatterHook, installHook, uninstallHook,+} from '../src/commands/frontmatter-install-hook.ts';import { withEnv } from './helpers/with-env.ts';function gitInit(dir: string) {@@ -43,6 +45,28 @@ function runHookWithFailingGbrain(repo: string): number {}}+/**+ * Run the installed hook with a `gbrain` stub that records each invocation's+ * argv (one line per call, NUL-separated args) and exits `exit`.+ */+function runHookRecordingGbrain(repo: string, exit = 0): { status: number; calls: string[][] } {+ const bin = mkdtempSync(join(tmpdir(), 'fm-hook-bin-'));+ const log = join(bin, 'calls');+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nfor a in "$@"; do printf '%s\\0' "$a" >> '${log}'; done\necho >> '${log}'\nexit ${exit}\n`, { mode: 0o755 });+ try {+ let status = 0;+ try {+ execFileSync('sh', [join(repo, '.githooks', 'pre-commit')], { cwd: repo, env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ''}` }, stdio: 'pipe' });+ } catch (e) {+ status = (e as { status: number }).status;+ }+ const calls = existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean).map((l) => l.split('\0').filter(Boolean)) : [];+ return { status, calls };+ } finally {+ rmSync(bin, { recursive: true, force: true });+ }+}+/** The repo-local core.hooksPath ('' when unset) — global scope never leaks in. */function localHooksPath(dir: string): string {try {@@ -390,4 +414,73 @@ describe('frontmatter install-hook (B13)', () => {rmSync(plain, { recursive: true, force: true });}});++ test('#5988 the hook carries a version marker and validates every staged file in ONE --staged call', async () => {+ mkdirSync(join(tmp, 'brain'));+ await install(join(tmp, 'brain'));+ const hookPath = join(tmp, '.githooks', 'pre-commit');+ const content = readFileSync(hookPath, 'utf8');+ expect(content).toContain(`# gbrain-hook-version: ${FRONTMATTER_HOOK_VERSION}`);+ expect(frontmatterHookVersion(content)).toBe(FRONTMATTER_HOOK_VERSION);+ writeFileSync(join(tmp, 'brain', 'a.md'), 'x\n');+ writeFileSync(join(tmp, 'brain', 'my note.md'), 'x\n');+ writeFileSync(join(tmp, 'README.md'), 'outside\n');+ execFileSync('git', ['-C', tmp, 'add', '.']);+ const run = runHookRecordingGbrain(tmp, 0);+ expect(run.status).toBe(0);+ expect(run.calls).toEqual([['frontmatter', 'validate', '--staged', '--', 'brain/a.md', 'brain/my note.md']]);+ expect(runHookRecordingGbrain(tmp, 1).status).toBe(1);+ });++ test('#5988 hook version detection: old gbrain hooks are outdated and name the refresh; foreign hooks are not ours', async () => {+ expect(inspectFrontmatterHook(tmp)).toBeNull();+ const hooksDir = join(tmp, '.githooks');+ mkdirSync(hooksDir, { recursive: true });+ const hookPath = join(hooksDir, 'pre-commit');+ writeFileSync(hookPath, '#!/bin/sh\necho "user hook"\n');+ expect(frontmatterHookVersion(readFileSync(hookPath, 'utf8'))).toBeNull();+ expect(inspectFrontmatterHook(tmp)).toBeNull();++ // A pre-marker gbrain hook (validated working-tree bytes) is version 1.+ writeFileSync(hookPath, '#!/bin/sh\n# gbrain frontmatter pre-commit hook (v0.22.4+)\n# gbrain-scope: brain/\ngbrain frontmatter validate "$f"\n');+ expect(inspectFrontmatterHook(tmp, 'wiki')).toEqual({+ hookPath, version: 1, current: false, fix: ['gbrain', 'frontmatter', 'install-hook', '--source', 'wiki', '--force'],+ });++ mkdirSync(join(tmp, 'brain'));+ expect(await install(join(tmp, 'brain'))).toBe('installed');+ const refreshed = readFileSync(hookPath, 'utf8');+ expect(refreshed).toContain('# gbrain-scope: brain/');+ expect(refreshed).toContain('validate --staged');+ expect(existsSync(hookPath + '.bak')).toBe(false);+ expect(inspectFrontmatterHook(join(tmp, 'brain'))).toMatchObject({ version: FRONTMATTER_HOOK_VERSION, current: true });+ });++ test('#5988 with the real CLI: a broken staged blob blocks the commit even though the working copy is fixed', async () => {+ await install(tmp);+ const bin = mkdtempSync(join(tmpdir(), 'fm-hook-real-'));+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec '${process.execPath}' '${join(import.meta.dir, '..', 'src', 'cli.ts')}' "$@"\n`, { mode: 0o755 });+ const env = { ...process.env, PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_HOME: join(bin, 'home'), DATABASE_URL: '', GBRAIN_DATABASE_URL: '', GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ const hook = () => {+ try {+ execFileSync('sh', [join(tmp, '.githooks', 'pre-commit')], { cwd: tmp, env, stdio: 'pipe' });+ return { status: 0, stderr: '' };+ } catch (e) {+ return { status: (e as { status: number }).status, stderr: String((e as { stderr: Buffer }).stderr) };+ }+ };+ try {+ writeFileSync(join(tmp, 'note.md'), '---\ntitle: a: b\ntype: note\n---\n\nbody\n');+ execFileSync('git', ['-C', tmp, 'add', 'note.md']);+ writeFileSync(join(tmp, 'note.md'), '---\ntitle: "a: b"\ntype: note\n---\n\nbody\n');+ const blocked = hook();+ expect(blocked.status).toBe(1);+ expect(blocked.stderr).toContain('the staged version of note.md is broken; the working copy passes. Review it and git add note.md');+ expect(blocked.stderr).toContain('importable but not canonical; run gbrain frontmatter validate note.md --fix (quoting only)');+ execFileSync('git', ['-C', tmp, 'add', 'note.md']);+ expect(hook().status).toBe(0);+ } finally {+ rmSync(bin, { recursive: true, force: true });+ }+ }, 60_000);});