tools/claude-build-gate.sh: the hook in POSIX sh, and its rules are tested (t0052, t0074)

The hook parsed the tool input with `python3 -c` and matched plain substrings:
any ">" and "releasedir" in one command was refused (a `2>&1` too), and
"git checkout" anywhere blocked the command.  tools/ is POSIX sh, no Python.

- jq when it is there (`.tool_input.command // empty`, fail closed when the
  field cannot be read), sed only as a fallback; dash -n clean.
- releasedir: the operation must target a path under it -- rm/mv/cp/touch/
  chmod/mkdir, `sed -i`, tee, or a redirection whose target is under
  releasedir.  A read with 2>/dev/null stays allowed.
- git reset --hard, git clean -f (any flag order), `git checkout -- .` and
  `git checkout .` in the root; the src/ rule matches src/ as a path
  component, so xsrc/ is not blocked.
- rm of the set lists with any flag order (rm -r -f, -fr, -Rf, long options).
- The allowed entry points named in the refusal are the root Makefile's.

tools/claude-build-gate-test.sh: 25 cases, each one command with its expected
exit code (16 blocked, 8 allowed, one unparsable input that must fail closed).
Measured: `sh tools/claude-build-gate-test.sh` -> 25 ok, 0 bad, exit 0;
dash -n on both scripts clean; .claude/settings.json still calls the same path.

tools/vmctl.py and tools/vmmon.py are deleted: building in a VM is gone
(2026-11-13) and nothing in the tree calls them (git grep finds only the
history files); tools/AGENTS.md already described them as removed.  No Python
in tools/ remains.
This commit is contained in:
lotherk committed 2026-11-15 08:57:55 +00:00
1 parent b5dd98b52f
commit 814ec71eaf
5 files changed
+163 -216

No files matched your search

+6 -2
View File
@@ -57,8 +57,10 @@ The passwords of root and `tester` are the test password of
Where the NetBSD project publishes a binary package for the platform and
Makronix does not patch the package, the binary is taken, not built
(decided 2026-11-07). The work goes where nothing is published or where we
change something: `cde` (not published, built in the VM), the packages of the
`makronix` set that the cross build produces.
change something: packages built from `packages.list` by `tools/userland.sh`
(cross or native, depending on the build host; see Root-`AGENTS.md` and
`tools/AGENTS.md`), and packages the NetBSD project does not publish. The VM
is for testing/install proof, not for building (Root-`AGENTS.md`, 2026-11-13).
- `tools/pkg-binaries.sh [-a amd64|aarch64] list|fetch` -- resolves the
packages named in `packages.list` (the lines of kind `fetch`) over the project's
@@ -143,3 +145,5 @@ from the VM's own disk (`/usr/src`, `/usr/msrc`).
desktop depends on it; the first version of the script restarted it, which
was a mistake). `insecure` means any process on the host can mount the tree
from 127.0.0.1 and then acts as user 1000 in it.
<!-- License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. -->
+72
View File
@@ -0,0 +1,72 @@
#!/bin/sh
# Test cases for tools/claude-build-gate.sh (t0052/t0074).
# Exit 0 when all cases behave as expected.
set -eu
HOOK=tools/claude-build-gate.sh
ok=0
fail=0
run() {
name=$1 expect=$2 cmd=$3
# build minimal hook JSON
json=$(printf '%s' "$cmd" | awk '
BEGIN { ORS="" }
{
gsub(/\\/, "\\\\")
gsub(/"/, "\\\"")
gsub(/\t/, "\\t")
if (NR > 1) printf "\\n"
printf "%s", $0
}')
set +e
printf '{"tool_name":"Bash","tool_input":{"command":"%s"}}' "$json" | sh "$HOOK" >/dev/null 2>&1
rc=$?
set -e
if [ "$rc" -eq "$expect" ]; then
printf 'ok %s (rc=%s)\n' "$name" "$rc"
ok=$((ok + 1))
else
printf 'BAD %s: expected rc=%s got rc=%s\n' "$name" "$expect" "$rc" >&2
printf ' cmd: %s\n' "$cmd" >&2
fail=$((fail + 1))
fi
}
# Blocked (exit 2)
run "git reset --hard" 2 'git reset --hard HEAD'
run "git clean -fdx" 2 'git clean -fdx'
run "git checkout -- ." 2 'git checkout -- .'
run "git checkout ." 2 'git checkout .'
run "rm -fr sets/lists variant" 2 'rm -fr src/distrib/sets/lists/makronix'
run "rm -r sets/lists variant" 2 'rm -r src/distrib/sets/lists'
run "rm -r -f sets/lists" 2 'rm -r -f src/distrib/sets/lists'
run "cd build&&make" 2 'cd build&&make'
run "make -Cbuild" 2 'make -Cbuild'
run "make -C build" 2 'make -C build'
run "systemd-run build" 2 'systemd-run --unit=x make release'
run "redirect to releasedir" 2 'echo hi > build/obj/releasedir/foo'
run "cp into releasedir" 2 'cp a build/obj/releasedir/images/a'
run "sed -i releasedir file" 2 'sed -i s/x/y/ build/obj/releasedir/file'
run "git reset in src" 2 'git -C src reset --hard'
run "rm sets/lists via different flags" 2 'rm -Rf src/distrib/sets/lists/makronix/mi'
# Allowed (exit 0)
run "grep reset harmless" 0 'grep reset src/Makefile'
run "ls releasedir read with 2>&1" 0 'ls build/obj/releasedir/images 2>/dev/null'
run "cat heredoc-like text" 0 'printf "%s" "reset src checkout clean"'
run "git checkout in xsrc" 0 'git -C xsrc checkout HEAD -- file'
run "git status" 0 'git status --short'
run "plain make" 0 'make release'
run "empty command" 0 ''
run "read releasedir path" 0 'find build/obj/releasedir -maxdepth 1 -type f'
# Fail closed on unparsable non-empty command-bearing input
set +e
printf '{"tool_name":"Bash","tool_input":{"command":' | sh "$HOOK" >/dev/null 2>&1
rc=$?
set -e
if [ "$rc" -eq 2 ]; then printf 'ok fail closed unparsable (rc=%s)\n' "$rc"; ok=$((ok + 1)); else printf 'BAD fail closed unparsable: expected 2 got %s\n' "$rc" >&2; fail=$((fail + 1)); fi
printf 'result: %s ok, %s bad\n' "$ok" "$fail"
[ "$fail" -eq 0 ]
+85 -33
View File
@@ -1,49 +1,101 @@
#!/bin/sh
# License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
# claude-build-gate.sh -- PreToolUse hook for Claude Code.
#
# Same rules as ~/.hermes/agent-hooks/makronix-build-gate.sh, in the shape
# Claude Code expects: JSON on stdin, exit 2 to block, message on stderr.
# Enforces the forbidden commands in AGENTS.md (root, "Forbidden") and
# tools/AGENTS.md. Claude Code passes hook JSON on stdin; exit 2 blocks the
# tool call and the message on stderr is shown to the model.
#
# Blocked: building through a transient unit, building inside build/,
# hand work on releasedir, resetting the imported tree, deleting the set lists.
set -u
# hand work on releasedir, destructive git operations in the repository root
# (git reset --hard, git checkout -- ., git clean -f[d|x|dx|...]), and
# deleting the set lists under src/distrib/sets/lists.
set -eu
CMD=$(python3 -c 'import json,sys
try: d=json.load(sys.stdin)
except Exception: print(""); raise SystemExit
print((d.get("tool_input") or {}).get("command",""))' 2>/dev/null)
INPUT=$(cat)
[ -z "$INPUT" ] && exit 0
CMD=
if command -v jq >/dev/null 2>&1; then
# jq -r prints "null" for null; // empty yields nothing.
if ! CMD=$(printf '%s' "$INPUT" | jq -er '.tool_input.command // empty' 2>/dev/null); then
# Non-empty stdin but no extractable command: fail closed unless the
# field is explicitly empty/null (jq -e exits 1 for empty/false/null).
if printf '%s' "$INPUT" | jq -e '(.tool_input.command // "") == ""' >/dev/null 2>&1; then
CMD=
else
printf '%s\n' "Forbidden: could not read tool_input.command from hook input (failing closed)." >&2
exit 2
fi
fi
else
# No jq: try to extract the command string field. Fail closed if stdin is
# non-empty but no command can be recovered safely.
CMD=$(printf '%s' "$INPUT" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\(.*\)".*/\1/p' | sed 's/\\"/"/g; s/\\\\/\\/g' | head -n 1)
if [ -z "$CMD" ]; then
case "$INPUT" in
*'"command"'*) printf '%s\n' "Forbidden: could not parse tool_input.command without jq (failing closed)." >&2; exit 2 ;;
esac
exit 0
fi
fi
[ -z "$CMD" ] && exit 0
block() {
printf '%s\n' "Verboten: $1" >&2
printf '%s\n' "Erlaubt sind nur: make | make build | make iso | make sets | make release ARCH=<arch> | make install" >&2
printf '%s\n' "Regeln: AGENTS.md (Abschnitt Forbidden), docs/BUILD-CONTRACT.md" >&2
exit 2
printf '%s\n' "Forbidden: $1" >&2
printf '%s\n' "Allowed entry points are the root Makefile targets: make, make build, make release, make install, make iso, make usb, make compress, make sourcesets, make isosrc, make userland, make test, make cdtest, make tools, make kernel, make mcde-linux, make mcde-host, make stamp, make clean-sanity." >&2
printf '%s\n' "Rules: AGENTS.md (section \"Forbidden\"), docs/BUILD-CONTRACT.md, tools/AGENTS.md." >&2
exit 2
}
# Transient build units.
case "$CMD" in
*systemd-run*) block "ein Build ueber eine transiente Unit. Ein Versuch = ein benannter Aufruf des Einstiegspunkts." ;;
esac
case "$CMD" in
*"make -C build"*|*"cd build && make"*|*"cd build; make"*)
block "make direkt in build/. Gebaut wird ueber die Ziele im Repo-Root." ;;
esac
case "$CMD" in
*releasedir*)
case "$CMD" in
*"rm "*|*"mv "*|*"cp "*|*">"*|*"sed -i"*|*"touch "*|*"chmod "*)
block "Handarbeit unter build/obj/releasedir. Die Artefakte dort entstehen nur im Build." ;;
esac ;;
esac
case "$CMD" in
*checkout*|*"clean -"*|*reset*)
case "$CMD" in
*src*) block "git checkout/clean/reset auf src/. src/ ist der importierte Baum, sein Zustand ist der Build." ;;
esac ;;
esac
case "$CMD" in
*"rm -rf"*sets/lists*) block "Loeschen der Set-Liste." ;;
*systemd-run*) block "building through a transient unit. Use a named root Makefile target." ;;
esac
# Building directly inside build/.
case "$CMD" in
*"make -C build"*|*"make -Cbuild"*|*"cd build && make"*|*"cd build&&make"*|*"cd build; make"*|*"cd build;make"*)
block "running make directly in build/. Build through the targets in the repository root." ;;
esac
# Hand work on releasedir: writes/moves/deletes/chmod/sed -i targeting it, or
# shell redirection whose target path is under releasedir. Redirects like 2>&1
# are not targets and must not be blocked.
if printf '%s\n' "$CMD" | grep -q 'releasedir'; then
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];|&()])(rm|mv|cp|touch|chmod|mkdir)([[:space:]]|$).*(^|[[:space:]])[^[:space:]]*releasedir|(^|[[:space:];|&()])(sed[[:space:]].*-i|tee([[:space:]]|$)).*(^|[[:space:]])[^[:space:]]*releasedir|>>?[[:space:]]*[^[:space:]]*releasedir'; then
block "hand work under build/obj/releasedir. Release artefacts are produced only by the build."
fi
fi
# Destructive git operations in the repository root (AGENTS.md "Forbidden").
# git reset --hard (allowing git global options such as -C <path>)
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];|&])git([[:space:]].*)?[[:space:]]reset([[:space:]].*)?[[:space:]]--hard([[:space:]]|$)'; then
block "git reset --hard in the repository root. Use git restore <file> after inspecting the change."
fi
# git clean with -f (including -fd, -fx, -fdx, -xfd, etc.)
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];|&])git([[:space:]].*)?[[:space:]]clean([[:space:]].*)?[[:space:]]-[a-zA-Z]*f'; then
block "git clean -f in the repository root."
fi
# git checkout -- . / git checkout .
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];|&])git([[:space:]].*)?[[:space:]]checkout([[:space:]].*)?[[:space:]]--[[:space:]]+\.([[:space:]]|$)|(^|[[:space:];|&])git([[:space:]].*)?[[:space:]]checkout[[:space:]]+\.([[:space:]]|$)'; then
block "git checkout -- . in the repository root. Use git restore <file> after inspecting the change."
fi
# Existing protection: destructive git operations against the imported src/ tree.
# Match src/ as a path component (not xsrc, msrc, resources, ...).
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];|&])git([[:space:]].*)?[[:space:]](checkout|clean|reset)([[:space:]]|$)'; then
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];/=])src([[:space:];/]|$)|-C[[:space:]]*src([[:space:];/]|$)|--git-dir(=|[[:space:]]+)[^[:space:]]*src([[:space:];/]|$)'; then
block "git checkout/clean/reset against src/. src/ is the imported tree; its state is the build input."
fi
fi
# Deleting the set lists (any flag order/combination including rm -r -f).
if printf '%s\n' "$CMD" | grep -Eq '(^|[[:space:];|&])rm([[:space:]]+-[a-zA-Z]+|[[:space:]]+--[^[:space:]]+)*([[:space:]]+-[a-zA-Z]+)*([[:space:]]|$)'; then
if printf '%s\n' "$CMD" | grep -q 'sets/lists'; then
block "deleting src/distrib/sets/lists."
fi
fi
exit 0
-126
View File
@@ -1,126 +0,0 @@
#!/usr/bin/env python3
# vmctl.py -- drive a NetBSD virtual machine's serial console.
#
# Why this exists: the CDE build needs a NetBSD build host (pkgsrc's
# mk/tools/replace.mk refuses "USE_TOOLS+=awk:run" whenever OPSYS !=
# NATIVE_OPSYS, which is what a cross-OS build from Linux is). The host is a
# NetBSD amd64 image built by this tree's own build.sh, run under qemu with
# KVM, and the only way in is the serial console.
#
# Usage:
# vmctl.py --sock PATH --log PATH [--do ACTION ...]
#
# Actions, in order:
# wait:SECONDS:REGEX read the console until REGEX matches (SECONDS=0: no limit)
# send:TEXT send TEXT; \n sends Enter, \\n a literal backslash-n
# sleep:SECONDS wait
# mark:TEXT write TEXT to the log as a step marker
#
# The console transcript is appended to --log, so the evidence stays in the
# tree the way AGENTS.md asks for it.
import argparse
import os
import re
import select
import socket
import sys
import time
CHUNK = 4096
class Console:
def __init__(self, sock_path, log_path, quiet=False):
self.log = open(log_path, "ab", buffering=0)
self.quiet = quiet
deadline = time.time() + 60
while True:
try:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(sock_path)
break
except OSError:
self.sock.close()
if time.time() > deadline:
raise SystemExit("vmctl: cannot connect to %s" % sock_path)
time.sleep(0.5)
self.buf = b""
def _pump(self, deadline):
wait = None
if deadline:
wait = max(0.0, deadline - time.time())
r, _, _ = select.select([self.sock], [], [], wait if wait is not None else 1.0)
if not r:
if deadline and time.time() >= deadline:
return False
return True
try:
data = self.sock.recv(CHUNK)
except OSError:
raise SystemExit("vmctl: console closed")
if not data:
raise SystemExit("vmctl: console EOF")
self.log.write(data)
self.buf += data
if not self.quiet:
sys.stdout.write(data.decode("utf-8", "replace"))
sys.stdout.flush()
return True
def wait_for(self, pattern, timeout):
rx = re.compile(pattern.encode())
deadline = time.time() + timeout if timeout else None
while True:
m = rx.search(self.buf)
if m:
self.buf = self.buf[m.end():]
return True
if not self._pump(deadline):
return False
def send(self, text):
self.sock.sendall(text.encode())
time.sleep(0.05)
def close(self):
try:
self.sock.close()
finally:
self.log.close()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--sock", required=True)
ap.add_argument("--log", required=True)
ap.add_argument("--do", action="append", default=[])
ap.add_argument("--quiet", action="store_true")
args = ap.parse_args()
con = Console(args.sock, args.log, args.quiet)
for action in args.do:
kind, _, rest = action.partition(":")
if kind == "wait":
timeout, _, pattern = rest.partition(":")
if not pattern:
raise SystemExit("vmctl: wait needs SECONDS:REGEX")
ok = con.wait_for(pattern, float(timeout))
if not ok:
raise SystemExit("vmctl: timeout waiting for %r" % pattern)
elif kind == "send":
con.send(rest.replace("\\n", "\n"))
elif kind == "sleep":
time.sleep(float(rest))
elif kind == "mark":
con.log.write(("\n=== vmctl: %s ===\n" % rest).encode())
if not args.quiet:
print("=== vmctl: %s ===" % rest)
else:
raise SystemExit("vmctl: unknown action %r" % kind)
con.close()
if __name__ == "__main__":
main()
-55
View File
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
"""vmmon.py -- run a qemu monitor command, print only the answer.
The monitor echoes every character it reads, so a plain read buries the one
line that matters ("OK" or "Error: ...") under a screenful of keystroke echo.
This prints the last lines with the echo and the escape noise removed.
vmmon.py --sock build/vm/monitor.sock device_add virtio-scsi-pci,id=scsihw
"""
import argparse
import re
import socket
import time
def run(sock, cmd, wait=0.8):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sock)
s.settimeout(2)
try:
s.recv(65536)
except OSError:
pass
s.sendall((cmd + "\n").encode())
time.sleep(wait)
out = b""
try:
while True:
chunk = s.recv(65536)
if not chunk:
break
out += chunk
except OSError:
pass
s.close()
text = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", out.decode("utf-8", "replace"))
text = text.replace("\r", "")
lines = []
for line in text.split("\n"):
# the echo repeats the command character by character; drop it
if cmd and line.replace("(qemu) ", "").strip() and \
cmd.replace(" ", "") in line.replace(" ", ""):
continue
if line.strip() and line.strip() != "(qemu)":
lines.append(line.strip())
return "\n".join(lines[-4:]) or "(no answer)"
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--sock", default="build/vm/monitor.sock")
ap.add_argument("cmd", nargs=argparse.REMAINDER)
a = ap.parse_args()
print(run(a.sock, " ".join(a.cmd)))