diff --git a/.gitignore b/.gitignore index b410ee2..d198dad 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ site/ # vm-test logs and driver output. .vm-tests/ .baton-pass/ +# Generated by the devenv shell (git-hooks); points into the nix store. +.pre-commit-config.yaml diff --git a/README.md b/README.md index e8c6de8..542af42 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,9 @@ e.g. `nixosModules.tailscale` or `homeModules.starship`. from external-systems/skills); `instructions.mode = "replace"` puts it in place of the built-in system prompt (pi and kimi `SYSTEM.md`, a claude output style; opencode stays on `"append"`). + `gitHookGuard.enable` (on by default) blocks claude's shell commands + that skip git hooks (`--no-verify`, `git commit -n`, core.hooksPath, + `PREK_ALLOW_NO_CONFIG`/`SKIP`), as the org ground rules require. - **VSCodium.** `homeModules.vscodium` (`homeSpec.programs.vscodium`) is VSCodium only. Everything past `enable` is per user: `languages.{nix,go,python,rust,gleam,zig,web,yaml,shell,markdown}.enable`, diff --git a/devenv.lock b/devenv.lock index 7cb9dcf..352dc6f 100644 --- a/devenv.lock +++ b/devenv.lock @@ -76,6 +76,30 @@ "type": "github" } }, + "git-hooks": { + "inputs": { + "flake-compat": [ + "org-pkgs" + ], + "nixpkgs": [ + "org-pkgs", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1795608474, + "narHash": "sha256-CwC7f1DripMBQjB7BozobprSYiA8Cn9rz8vsBthWJwk=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "5c6bf7c418b4abf003e6d00d231e87f5e6ad5230", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, "import-tree": { "locked": { "lastModified": 1788467110, @@ -109,11 +133,11 @@ ] }, "locked": { - "lastModified": 1794064691, - "narHash": "sha256-a2/vYgnX7W3MZurxMDkY8y+sIJuGT2z08tUER3wcbxY=", + "lastModified": 1794808658, + "narHash": "sha256-RbvK/ghvMuWWx/riUqtCZCxjZFji2n3onTo2Kg60T3s=", "owner": "numtide", "repo": "llm-agents.nix", - "rev": "3d32ec231e746b4253bda8bd427025b4dac51785", + "rev": "733d5b0fa81d5aad7c623dca8d8170ce411fba1d", "type": "github" }, "original": { @@ -201,6 +225,7 @@ "org-pkgs": { "inputs": { "flake-parts": "flake-parts", + "git-hooks": "git-hooks", "import-tree": "import-tree", "llm-agents": "llm-agents", "moscripts": "moscripts", @@ -214,17 +239,17 @@ "zen-browser": "zen-browser" }, "locked": { - "lastModified": 1794710907, - "narHash": "sha256-kdDp4EUFxT8WXCEx93nZN8Xxb6T7sWg7vf8eYvG8utI=", + "lastModified": 1795691814, + "narHash": "sha256-AwEuB0gohCMXSpSYwykwwRLbi02B7hegbshQihbtF54=", "owner": "external-systems", "repo": "pkgs", - "rev": "2bacfc8371dd6988db44eaa9f52f707ad0b2399f", + "rev": "36cc52f2599b2415f726b82f35745ac15ed6fd6e", "type": "github" }, "original": { "owner": "external-systems", "repo": "pkgs", - "rev": "2bacfc8371dd6988db44eaa9f52f707ad0b2399f", + "rev": "36cc52f2599b2415f726b82f35745ac15ed6fd6e", "type": "github" } }, @@ -298,6 +323,10 @@ "root": { "inputs": { "devenv": "devenv", + "git-hooks": [ + "org-pkgs", + "git-hooks" + ], "nixpkgs": [ "org-pkgs", "nixpkgs" diff --git a/devenv.yaml b/devenv.yaml index 31eb3bd..411e2a7 100644 --- a/devenv.yaml +++ b/devenv.yaml @@ -6,9 +6,12 @@ # pkgs ("attribute 'bash' missing"). inputs: org-pkgs: - url: github:external-systems/pkgs/2bacfc8371dd6988db44eaa9f52f707ad0b2399f + url: github:external-systems/pkgs/36cc52f2599b2415f726b82f35745ac15ed6fd6e nixpkgs: follows: org-pkgs/nixpkgs + # The org shell's git hooks; devenv reads inputs from this file only. + git-hooks: + follows: org-pkgs/git-hooks imports: # The org shell: fmt, check, sync-locks, docs, slides; devenv up serves # docs and slides. diff --git a/flake-parts/homeModules/agents/_git-hook-guard.nix b/flake-parts/homeModules/agents/_git-hook-guard.nix new file mode 100644 index 0000000..13771df --- /dev/null +++ b/flake-parts/homeModules/agents/_git-hook-guard.nix @@ -0,0 +1,144 @@ +# The git hook guard: a claude-code PreToolUse hook on Bash that blocks +# git commands that skip git hooks. The org shell's hooks (fmt on commit, +# a repo's own on push) are part of the gate, and the ground rules say +# never to skip them; this makes that hold for the agent. The owner can +# still skip a hook from their own shell, or from claude with the `!` +# prefix (that runs outside the agent's tool calls). +# +# Blocked, in any part of a compound command (and inside `sh -c`/`bash -c`): +# - `--no-verify` on any git subcommand (commit, push, merge, rebase, am) +# - `git commit -n` (also in a short-option cluster such as `-anm`) +# - core.hooksPath set by `git -c` or `git config` +# - PREK_ALLOW_NO_CONFIG or SKIP (prek skips the named hooks) on a git command +# +# Exit 2 blocks the tool call; claude shows the stderr to the model. A +# command that does not parse as shell is left alone (claude's own Bash +# tool rejects it). A plain function, not a module. +{ + lib, + pkgs, +}: let + guard = pkgs.writers.writePython3Bin "agent-git-hook-guard" {flakeIgnore = ["E501"];} '' + import json + import os + import shlex + import sys + + OPERATORS = {"&&", "||", ";", "|", "&", "(", ")", ";;", "|&"} + SHELLS = {"sh", "bash", "zsh", "dash"} + # git commit short options that take a value: the rest of the cluster, + # or the next word, is that value. + COMMIT_VALUE_OPTS = set("mFCct") + SKIP_ENV = {"PREK_ALLOW_NO_CONFIG", "SKIP"} + + + def simple_commands(command): + lexer = shlex.shlex(command, posix=True, punctuation_chars=True) + lexer.whitespace_split = True + words = [] + for token in lexer: + if token in OPERATORS: + if words: + yield words + words = [] + else: + words.append(token) + if words: + yield words + + + def commit_skips(args): + for arg in args: + if arg == "--": + return False + if arg.startswith("-") and not arg.startswith("--"): + for letter in arg[1:]: + if letter == "n": + return True + if letter in COMMIT_VALUE_OPTS: + break + return False + + + def git_reason(words, env): + i = 1 + while i < len(words) and words[i].startswith("-"): + if words[i] in ("-C", "-c"): + if words[i] == "-c" and i + 1 < len(words) and words[i + 1].lower().startswith("core.hookspath"): + return "sets core.hooksPath" + i += 2 + else: + i += 1 + if i >= len(words): + return None + sub, args = words[i], words[i + 1:] + if env & SKIP_ENV: + return "sets " + ", ".join(sorted(env & SKIP_ENV)) + if "--no-verify" in args: + return "uses --no-verify" + if sub == "commit" and commit_skips(args): + return "uses git commit -n" + if sub == "config" and any(a.lower() == "core.hookspath" for a in args): + return "sets core.hooksPath" + return None + + + def reason(command, depth=0): + try: + commands = list(simple_commands(command)) + except ValueError: + return None + for words in commands: + env = set() + while words and "=" in words[0] and not words[0].startswith("="): + env.add(words[0].split("=", 1)[0]) + words = words[1:] + if words and words[0] == "env": + words = words[1:] + while words and "=" in words[0]: + env.add(words[0].split("=", 1)[0]) + words = words[1:] + if not words: + continue + name = os.path.basename(words[0]) + if name == "git": + found = git_reason(words, env) + if found: + return found + elif name in SHELLS and depth < 3 and "-c" in words[1:]: + script = words[words.index("-c") + 1:][:1] + if script: + found = reason(script[0], depth + 1) + if found: + return found + return None + + + try: + event = json.load(sys.stdin) + except ValueError: + sys.exit(0) + command = (event.get("tool_input") or {}).get("command") or "" + found = reason(command) + if found: + print( + f"Blocked: this git command {found}, which skips the git hooks. " + "The hooks are part of the gate (external-systems ground rules): " + "fix what the hook reports and commit or push again. If a skip is " + "really needed, ask the owner to run the command.", + file=sys.stderr, + ) + sys.exit(2) + ''; +in { + package = guard; + claude.hook = { + matcher = "Bash"; + hooks = [ + { + type = "command"; + command = lib.getExe guard; + } + ]; + }; +} diff --git a/flake-parts/homeModules/agents/agents.nix b/flake-parts/homeModules/agents/agents.nix index 33728f2..fd32e73 100644 --- a/flake-parts/homeModules/agents/agents.nix +++ b/flake-parts/homeModules/agents/agents.nix @@ -168,6 +168,9 @@ formatOnEdit = wf.enable && wf.formatOnEdit; nixWorkflow = import ./_nix-workflow.nix {inherit lib pkgs;}; + # ---- Git hook guard (homeSpec.agents.gitHookGuard) ---- # + gitHookGuard = import ./_git-hook-guard.nix {inherit lib pkgs;}; + # ---- Shared MCP bindings (homeSpec.agents.mcp.*) ---- # # PAT file used by the wrapper: explicit patFile override or the # canonical sops-nix deployment path of the per-user "github-" @@ -268,6 +271,9 @@ (lib.optionalAttrs formatOnEdit { hooks.PostToolUse = [nixWorkflow.claude.hook]; }) + (lib.optionalAttrs cfg.gitHookGuard.enable { + hooks.PreToolUse = [gitHookGuard.claude.hook]; + }) (lib.optionalAttrs skillsRuntimeEnabled {inherit (skillsRuntime) env;}) (lib.optionalAttrs (claudeInstructions.mode == "replace") {outputStyle = claudeOutputStyle;}) cfg.claude.settings @@ -444,6 +450,19 @@ }; }; + # ---- Git hook guard: homeSpec.agents.gitHookGuard.* ---- # + gitHookGuard.enable = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Block agent shell commands that skip git hooks: `--no-verify`, + `git commit -n`, core.hooksPath, PREK_ALLOW_NO_CONFIG or SKIP on + a git command (claude, a PreToolUse hook on Bash). The org + shell's hooks are part of the gate; the owner can still skip one + from their own shell. + ''; + }; + # ---- pi: homeSpec.agents.pi.* ---- # pi = { enable = lib.mkEnableOption "the pi coding agent (badlogic/pi-mono)"; diff --git a/flake.lock b/flake.lock index a2e6f68..e15e19d 100644 --- a/flake.lock +++ b/flake.lock @@ -98,6 +98,30 @@ "type": "github" } }, + "git-hooks": { + "inputs": { + "flake-compat": [ + "org-pkgs" + ], + "nixpkgs": [ + "org-pkgs", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1795608474, + "narHash": "sha256-CwC7f1DripMBQjB7BozobprSYiA8Cn9rz8vsBthWJwk=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "5c6bf7c418b4abf003e6d00d231e87f5e6ad5230", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, "home-manager": { "inputs": { "nixpkgs": [ @@ -172,11 +196,11 @@ ] }, "locked": { - "lastModified": 1794064691, - "narHash": "sha256-a2/vYgnX7W3MZurxMDkY8y+sIJuGT2z08tUER3wcbxY=", + "lastModified": 1794808658, + "narHash": "sha256-RbvK/ghvMuWWx/riUqtCZCxjZFji2n3onTo2Kg60T3s=", "owner": "numtide", "repo": "llm-agents.nix", - "rev": "3d32ec231e746b4253bda8bd427025b4dac51785", + "rev": "733d5b0fa81d5aad7c623dca8d8170ce411fba1d", "type": "github" }, "original": { @@ -324,6 +348,7 @@ "org-pkgs": { "inputs": { "flake-parts": "flake-parts", + "git-hooks": "git-hooks", "import-tree": "import-tree", "llm-agents": "llm-agents", "moscripts": "moscripts", @@ -337,11 +362,11 @@ "zen-browser": "zen-browser" }, "locked": { - "lastModified": 1794710907, - "narHash": "sha256-kdDp4EUFxT8WXCEx93nZN8Xxb6T7sWg7vf8eYvG8utI=", + "lastModified": 1795691814, + "narHash": "sha256-AwEuB0gohCMXSpSYwykwwRLbi02B7hegbshQihbtF54=", "owner": "external-systems", "repo": "pkgs", - "rev": "2bacfc8371dd6988db44eaa9f52f707ad0b2399f", + "rev": "36cc52f2599b2415f726b82f35745ac15ed6fd6e", "type": "github" }, "original": { @@ -489,11 +514,11 @@ "skills-terraform": "skills-terraform" }, "locked": { - "lastModified": 1794710495, - "narHash": "sha256-qTW2ArdMcVxV2iJi5m8JkXBm41Sn0+483Eay9SoT5FM=", + "lastModified": 1795692051, + "narHash": "sha256-N5Rk6VAmDyGZNlCsuCbyTdiCDCvYw8b2TVEmTrxYF7c=", "owner": "external-systems", "repo": "skills", - "rev": "d72f0fde19edcd630874f72bdae5cea1c6c4fba1", + "rev": "ec7cff722867607b77ed7b6887aff22bf9089bd5", "type": "github" }, "original": { diff --git a/tests/flake-module.nix b/tests/flake-module.nix index 6c47808..7cd6486 100644 --- a/tests/flake-module.nix +++ b/tests/flake-module.nix @@ -250,6 +250,7 @@ assert expect (lib.elem "Bash(nix eval:*)" claude.permissions.allow) "nix eval not allowed"; assert expect (claude.env ? BASH_MAX_TIMEOUT_MS && claude.env ? NODE_PATH) "claude env misses the timeouts or the skills runtime"; assert expect (lib.length claude.hooks.PostToolUse == 1) "no .nix format hook"; + assert expect (lib.length claude.hooks.PreToolUse == 1) "no git hook guard"; assert expect (!(claude ? mcpServers)) "settings.json carries mcpServers"; assert expect (hm.home.activation ? claudeMcpServers) "no ~/.claude.json MCP sync"; assert expect (hm.programs.opencode.settings.mcp.servers.github.type == "local") "opencode github not on the pat server"; @@ -269,6 +270,55 @@ assert expect (hm.home.activation ? kimiNixWorkflow) "no kimi config.toml merge"; pkgs.writeText "agents-wiring" "ok"; + # The git hook guard blocks every way an agent could skip git hooks + # and lets ordinary git (and text that only mentions a flag) through. + agents-git-hook-guard = let + guard = (import ../flake-parts/homeModules/agents/_git-hook-guard.nix {inherit lib pkgs;}).package; + blocked = [ + "git commit --no-verify -m wip" + "git push --no-verify" + "git commit -n -m wip" + "git commit -anm wip" + "cd repo && git commit -qn -m wip" + "git -C repo commit --no-verify" + "git -c core.hooksPath=/dev/null commit -m wip" + "git config core.hooksPath /dev/null" + "PREK_ALLOW_NO_CONFIG=1 git commit -m wip" + "SKIP=fmt git commit -m wip" + "env SKIP=fmt git commit -m wip" + "bash -c 'git commit --no-verify -m wip'" + "git merge --no-verify feature" + ]; + allowed = [ + "git commit -m wip" + "git commit -am 'fix -n handling'" + "git commit -m 'never use --no-verify'" + "git commit -F msg -m n" + "git push -n origin HEAD" + "git log -n 3" + "grep -rn no-verify docs" + "echo --no-verify" + "git status && git push -u origin HEAD" + ]; + expectExit = verdict: + if verdict == "blocked" + then "2" + else "0"; + run = verdict: command: '' + printf '%s' ${lib.escapeShellArg (builtins.toJSON {tool_input = {inherit command;};})} | ${lib.getExe guard} 2>/dev/null && got=0 || got=$? + if [ "$got" != ${expectExit verdict} ]; then + echo "agents-git-hook-guard: expected ${verdict} (got exit $got): "${lib.escapeShellArg command} >&2 + exit 1 + fi + ''; + in + pkgs.runCommand "agents-git-hook-guard" {} '' + ${lib.concatMapStrings (run "blocked") blocked} + ${lib.concatMapStrings (run "allowed") allowed} + printf '%s' 'not json' | ${lib.getExe guard} + touch $out + ''; + # Instructions reach every agent the same way: machine context, the # org ground rules, the user's text, then the agent's own text; # "replace" moves them into each agent's system-prompt spot