agentleFS
matt82198matt82198/aesop/hooks/CLAUDE.md

aesop / hooks

CLAUDE.md2 starsChanged 31 days agoMITView on GitHub

Purpose: Installable git hooks (pre-push, pre-commit) and Claude Code hooks (PreToolUse) that gate commits/pushes with security & cost policies. Runs on git push via .git/hooks/pre-push (symlink on Unix/macOS/Git Bash; copy on Windows). Checks & Exit Contract: 1. main() TTY guard — rejects interactive hook invocation (tty stdin) with exit 1 before any checks (fail-closed); logs interactive_invocation_blocked. Real git push always pipes stdin; tty means human ran hook directly. 2a. Gate pinning (F-04): every gate script runs from the trunk's tools/…

  • Deletes or force-pushes
  • Commits and pushes

The file

We split this CLAUDE.md into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All string values must be JSON-escaped (backslash → \\, quote → \", control chars → \uXXXX).

    line 50

≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

hooks/ — Git & Claude Code policy enforcement

Purpose: Installable git hooks (pre-push, pre-commit) and Claude Code hooks (PreToolUse) that gate commits/pushes with security & cost policies.

Universal rules (every domain)

  • Feature branch only, never main; every push gated by python tools/secret_scan.py --staged exit 0.
  • Tests never pollute cwd or global git config; temp dirs only; dummy secrets are runtime-concatenated, never literal.
  • In worktrees use ABSOLUTE paths under the worktree for every write.
  • Domain docs stay minimal-but-complete; update this file in the same PR as code it describes.

pre-push-policy.sh

Runs on git push via .git/hooks/pre-push (symlink on Unix/macOS/Git Bash; copy on Windows).

Checks & Exit Contract:

  1. main() TTY guard — rejects interactive hook invocation (tty stdin) with exit 1 before any checks (fail-closed); logs interactive_invocation_blocked. Real git push always pipes stdin; tty means human ran hook directly. 2a. Gate pinning (F-04): every gate script runs from the trunk's tools/ (gate_base_dir; trunk = origin/HEAD target, else origin/main, else origin/master via gate_trunk_ref; fail-closed when unreadable), never the pushed branch's copy. BOOTSTRAP (no trunk on origin yet): base = HEAD, prints BOOTSTRAP: no trunk on origin; base = HEAD once, and fails closed if tools/INDEX.md, .pyflakes-baseline.json or .subprocess-guard-baseline.json is not committed at HEAD (the subprocess baseline is read from git show HEAD:). Bootstrap never applies once a trunk ref exists; a push editing gate files prints a non-blocking GATE-CHANGED banner (check_gate_tamper). Tests: tests/test_pre_push_gate_base.sh. Gate base extracts tools/ AND state_store/ (state_store imports tools.*; tools/tracker_guard.py imports state_store.read_api) into cache aesop-gate-base-v5-<uid>-<sha> (the exec bit is set on tools/*.py so the [ -x ] check in check_secret_scan passes on Linux, where git's 100644 mode would fail it); a cached copy is reused only when this user owns it (gate_owned_dir) and has .complete, and a slot held by anything else is never deleted or reused: the push extracts privately, staged per PID (item c730e29d46ea). Older cache versions are never reused.
  2. check_branch_policy() — judges the REMOTE ref on each stdin tuple (<local ref> <local sha> <remote ref> <remote sha>), never the local checkout. Any tuple targeting refs/heads/main|master (including deletes) blocks, exit 1. Tag-only and delete-only pushes pass. Other remote refs pass from any local branch (e.g. git push origin HEAD:refs/heads/checkpoint/x from local main is allowed). The current-branch check is only a fallback when stdin carries no tuples at all.
  3. check_secret_scan() — runs tools/secret_scan.py --range for each ref tuple on git pre-push stdin; exit 1 on findings. Scans all branches in multi-ref pushes (e.g., git push --all). Commit range fix: For NEW branches (remote ref all-zeros), get_commit_range() now computes the base using git merge-base <local-sha> origin/main (falling back to origin/master, then local main/master), not the local main ref. This ensures correctness in worktrees where local main is checked out from a stale commit far behind origin/main; the remote reference is authoritative.
  4. check_import_resolution() — runs tools/import_resolution_check.py --range once per ref tuple on git pre-push stdin (guardrail G5), reusing get_commit_range() exactly as check_secret_scan() does; AST-parses each pushed .py file (blob read at the range TIP, not the working tree) and resolves its imports against repo structure + stdlib + environment; exit 1 on unresolvable imports. Delete-only (import_check_skipped_delete_only_push) and empty stdin (import_check_skipped_empty_stdin) pass; malformed stdin is fail-closed (import_check_stdin_parse_failed). Fail-open only when the tool is absent (import_check_skipped_tool_missing). Was vacuously green. It previously ran with no arguments, so it evaluated git diff --cached. A pre-push hook runs after the commit, so the index is EMPTY: the gate printed "No staged Python files found" and exited 0 on every normal push — it had never actually run. Any change here must keep feeding it the pushed range (check_import_resolution <<< "$prepush_stdin"); a fail-closed gate that evaluates nothing is worse than no gate, because it reads as protection.
  5. check_conflict_markers() — runs tools/conflict_marker_check.py --staged once per ref tuple on git pre-push stdin (reusing get_commit_range() exactly as check_import_resolution() does); scans only the ADDED lines in that range's diff for literal unresolved conflict markers (<<<<<<<, =======, >>>>>>>, |||||||); exit 1 on any marker found (conflict_marker_check_failure logged). Added after the PR #834 incident, where a merge commit (b2c4db77) landed a literal <<<<<<< HEAD block in tools/CLAUDE.md on main and every other gate (claudemd_lint, claudemd_sync_gate, all PR CI) passed. Delete-only/empty-stdin pass; malformed stdin is fail-closed. Fail-open only when the tool is absent (conflict_marker_check_skipped_no_aesop_tools). 5a. check_symbol_survival() (Guardrail G13, BLOCKING) — runs tools/pr_symbol_survival_check.py --base <remote-sha> --head <local-sha> once per ref tuple from get_commit_range(); blocks (exit 1 = symbol dropped by a merge commit in range, exit 2 = tool/git error, symbol_survival_failure logged). The script runs from the BASE copy (gate_base_dir, trunk tools/), never the pushed tree; a base copy without it fails closed (no skip branch). A merge commit drops a symbol when ANY parent held it and the merge tree lacks it (main as first parent included); only a NON-merge commit's deletion counts as an intentional removal (add-then-delete, passes, printed as REMOVED). --test Test 29 drives this function against a lossy merge (must block) and a clean push (must pass).
  6. check_tracker_guard() — runs tools/tracker_guard.py --check against live runtime state (AESOP_STATE_ROOT, default $AESOP_ROOT/state); exit 1 (push blocked, tracker_guard_failure logged) on zombie-resurrection detection. Wired here rather than CI because tracker.json is git-ignored runtime state a CI checkout never has. Fail-open only when the tool itself is absent (tracker_guard_skipped_tool_missing logged) — the hook installs into repos without an aesop checkout.
  7. check_claudemd_sync() — runs tools/claudemd_sync_gate.py --check to verify domain code changes are accompanied by corresponding domain/CLAUDE.md updates; exit 1 on drift. Detects when domain directories change without documenting what changed. Fail-open only for missing tool.
  8. check_gen_tool_index() — runs tools/gen_tool_index.py --check to verify tools/INDEX.md is in sync with per-tool INDEX: docstring lines; exit 1 on drift or any tool missing its INDEX: line (fail-closed). Wired after CLAUDE.md sync gate. Fail-open only for missing tool. Also check_machinery_map_symbols() (after it): runs tools/check_machinery_map_symbols.py --check on docs/MACHINERY-MAP.md; exit 1 on a :<digits> line citation or a missing cited symbol. The checker runs with --skip-if-scaffold, so it exits 0 (machinery_map_symbols_skipped_scaffold) only when the map is absent and bin/cli.js is absent (scaffold tree); an aesop tree with a missing map still fails closed. Bootstrap: a gate new in the pushed tree runs from the pushed copy until it merges.
  9. check_metrics() — runs tools/metrics_gate.py to verify hard numeric claims (percentages, multipliers, dollar amounts) in markdown have source verification markers; exit 1 on unverified claims. Fail-open only for missing tool. Scans the pushed refs, not HEAD: it reads the git pre-push stdin (main() passes <<< "$prepush_stdin") and runs metrics_gate.py <range> once per range from get_commit_range(), the same derivation check_secret_scan() uses. Empty, delete-only and unparseable stdin fall back to the default origin/main...HEAD range (today's behaviour). Before this fix a tag-only push (git push origin v0.10.1) was judged by the current branch's unpushed commits and failed on metrics that were not being pushed. Tests: tests/test_pre_push_policy.sh (tag-only passes, branch adding a metric still fails, empty stdin fail-closed). Tag range (get_commit_range): a NEW tag (refs/tags/* with an all-zero remote sha) now yields the tagged commit alone, <commit>^..<commit> (empty tree for a root commit), instead of the merge-base range, which collapsed to an empty X..X and scanned zero files for the tag.
  10. Validates that the documented test suite count stays in sync with the actual number of test suites in the repo. Implemented as check_test_suite_count(), which runs tools/verify_test_suite_count.py --check; exit 1 on mismatch. Detects when test suite counts drift without updating documentation. Fail-open only when the tool is absent.
  11. check_claudemd_headroom() — runs tools/claudemd_lint.py --headroom --base-ref ${AESOP_HEADROOM_BASE_REF:-origin/main}; previews the merge and lints the UNION's CLAUDE.md line cap, catching the cascade where a branch passes at 149/150 but merges to 151. Exit 1 (a union busts its cap) is fail-closed; exit 2 (union unreadable) gets one fetch/unshallow of the base ref and one re-run, then BLOCKS with the tool tail (claudemd_headroom_unreadable_blocked); AESOP_HEADROOM_BASE_REF naming the branch head is refused (claudemd_headroom_base_is_branch_head). A missing tool fails open, logging claudemd_headroom_skipped_tool_missing.
  12. check_encoding_lint() — runs tools/encoding_lint.py --check over the WHOLE repo. There is NO baseline: the tool has no --baseline flag, so this gate is fail-closed on any finding anywhere and one violation blocks every Python-touching push. (The committed .encoding-baseline.json that nothing read was removed as a dead baseline with no consumer -- see the dead-baseline liveness guardrail.) Flags subprocess.run/check_output/Popen with text=True/universal_newlines=True and no encoding= (the Windows cp1252 trap), AND subprocess.* that sets encoding= without a safe errors= handler — strict decoding kills subprocess's reader thread, leaves stdout None, and crashed the merge queue on 24+ consecutive passes while this gate reported clean. Fail-open only when the tool or a python interpreter is absent. Worktree fix: calls resolve_aesop_root() to resolve the pushed repo (not a hardcoded primary tree path), so gate fixes on a branch take effect immediately from that branch's push.
  13. check_test_coverage() — runs tools/verify_test_coverage.py --check; detects test files no CI job runs (the fake-green class). Fail-closed on orphans; fail-open only when the tool is absent. Worktree fix: calls resolve_aesop_root() to resolve the pushed repo (not a hardcoded primary tree path), so gate fixes on a branch take effect immediately from that branch's push.
  14. check_generated_paths() — runs tools/generated_paths.py --check over the pushed diff (each ref tuple's <remote-sha>..<local-sha> range through git diff --name-only; paths go over stdin, not argv, so a large diff cannot blow the command-line length limit); exit 1 (generated_path_hand_edit logged) when the push touches a registered machine-generated path, and the message names the owning generator. A generated file has exactly one legitimate writer, so a hand edit is both silently reverted on the next regeneration and a guaranteed conflict with every concurrent lane — this gate is what kills that contended-file class. Escape hatch AESOP_ALLOW_GENERATED=1 (honored inside the tool; exactly 1, nothing else) is the DESIGNED writer path for generator / merge-train regeneration / daemon pushes, not a weakening — an ordinary push never sets it. Fail-open only when the tool or python is absent; delete-only or empty stdin simply means no diff to classify (malformed stdin is already fail-closed by check_secret_scan, which runs first).
  15. check_generated_regen() — runs tools/generated_push_gate.py --range <remote-sha>..<local-sha> (one --range per ref tuple, same captured stdin as check_generated_paths()), preceded by ensure_merge_drivers() (fail-open, quiet tools/install_merge_drivers.py: registers the aesop-json-union and aesop-regen merge drivers in this clone's config so no pushing clone can forget). The gate verifies the pushed COMMIT, not the working tree: when a range touches a registered regenerable artifact (tools/generated_paths.py::REGISTRY entries with a regen argv — today tools/INDEX.md), or the merge driver's per-worktree .needs-regen stamp names one, it checks the tip out in a throwaway detached worktree, runs the registered generator there, and exits 1 (generated_artifact_stale logged) printing exactly run: python tools/gen_tool_index.py --regenerate && git add tools/INDEX.md when the committed bytes differ. Closes the gap behind #784/#856/#739: check_gen_tool_index() (item 8) runs --check on the WORKING TREE, so a regenerated-but-uncommitted tree or a union-stale merge commit pushed green and failed ci(0). No escape hatch (a stale artifact is never a legitimate write); fail-closed when tools/ exists but the script or python is missing; skip only with no aesop checkout; delete-only/empty stdin = nothing to verify. The hook passes --base-dir "$gate_dir" (the trunk tools/ copy from gate_base_dir): every generator then runs from the base copy, so a push that edits a generator cannot bless its own output; without a base dir, a generator changed by the push fails closed. D46 (2026-10-16): a registered path the push neither touches (artifact nor generator, judged over merge-base(origin/main, tip)..tip) whose tip blob equals the merge-base blob is INHERITED unchanged from trunk and not verified; the gate prints generated path <p> inherited unchanged from base; regeneration belongs to main (regen-on-main heals main), and the hook echoes that pass line. A registered path whose generator is absent at the tip now blocks (it was a silent pass). check_gate_tamper also flags tools/gen_*.py and tools/generated_*.py in the GATE-CHANGED banner.
  16. check_linux_shape() — runs tools/linux_shape_check.py --range <commit-range> for commits touching shell/workflow/Node-test files to catch platform-specific failures via WSL-based test execution. Detects changes to *.sh, hooks/*, .github/workflows/*.yml, tests/**/*.test.mjs and runs owning test suites under WSL (e.g., wsl bash -lc 'cd /mnt/c/... && bash tools/run_shell_tests.sh'), with Node tests run under WSL with USERPROFILE unset to catch environment variable assumptions (fixed #864: isolated-home assumption in tripwire test, #870: shell test failures on Ubuntu CI). Exit contract: skip if no changes detected, or (Windows without WSL) print NOTICE + exit 0 (unless AESOP_REQUIRE_LINUX_SHAPE=1), except that a push touching covered paths (the gate's own should_check_linux_shape rule, read from the base copy) BLOCKS (linux_shape_wsl_absent_covered_blocked); a coverage-probe error blocks. Fail-closed on test failure. Fail-open only when tools/ absent (no aesop checkout).
  17. check_pyflakes_ratchet() (guardrail G15) — runs tools/pyflakes_gate.py --root <aesop_root> --baseline <aesop_root>/.pyflakes-baseline.json --trunk-baseline <gate_base_dir>/.pyflakes-baseline.json (D40: the trunk baseline is the authority; the branch copy may only burn it down); scans tools/, bin/, ui/, state_store/, driver/, monitor/, daemons/, tests/, bench/ with python -m pyflakes. Never lets unused-import / unused-variable debt grow: NEW findings above baseline block the push (exit 1, pyflakes_ratchet_failure logged); A branch baseline that is a strict burn-down of the trunk baseline (a subset, with the current scan within it) PASSES with the note line pyflakes baseline burned down: N entries removed; any entry the trunk lacks (an addition), a missing or malformed branch baseline, or a finding above the branch baseline blocks (fail-CLOSED). Single-baseline mode (no --trunk-baseline) stays an exact-match bidirectional ratchet: STALE entries block until regenerated with --update-baseline (review-only; CI never passes it). Exit codes: 0 = clean/baselined, 1 = new-or-stale findings (fail-CLOSED), 2 = error condition (pyflakes not installed, baseline unreadable, etc; fail-CLOSED: blocks with the tool output tail). Pyflakes is a dev-only dependency (not installed by default; CI installs it in the "Install Python test dependencies" step). Opt-out via AESOP_PYFLAKES_SKIP=1 (exact string match) for emergency escapes (logs pyflakes_ratchet_skipped_env_opt_out). Fail-open only when the tool is absent or pyflakes is not importable; actual baseline mismatches are fail-closed. 17b. check_subprocess_guard_ratchet() (guardrail G6, ratchet) — runs the SAME invocation ci.yml runs from the repo root, python tools/subprocess_guard.py --check --baseline .subprocess-guard-baseline.json (pushed tree, not pinned to origin/main, so the flag set matches CI exactly). Any finding above baseline (or stale entry) blocks the push (subprocess_guard_ratchet_failure). Fail-closed on a missing baseline, a missing tool when tools/ exists, no python, or any non-zero exit; skips only with no aesop checkout. Parity with ci.yml is asserted by tests/test_pre_push_policy.sh Test 40. 17c. check_inprocess_http_timeout() (escape main-full-windows-shard2-ui-acceptance-timeout) -- runs tools/inprocess_http_timeout_lint.py --root <aesop_root> --baseline <gate_dir>/.inprocess-timeout-baseline.json (trunk baseline is the authority). Any hit (loopback or non-literal-host client call with a timeout under 30 s, or any non-literal timeout), unparseable test, expired baseline (_generated older than 30 days), or escape/per-file count above the trunk baseline blocks (inprocess_http_timeout_failure). Fail-CLOSED when the trunk lacks the tool from a repo that has tools/ (gate_tool_missing_block); skip only with no tools/ directory. Also wired in ci.yml shard 0 (step "In-process HTTP timeout lint").
  18. check_emit_receipt() — runs LAST, only after every check above has passed: first calls env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_PREFIX -u GIT_COMMON_DIR -u GIT_OBJECT_DIRECTORY tools/receipt_flush.py --repo <aesop_root> (fail-open, bounded, ~10s) to flush any prior spooled receipts whose shas now exist on GitHub (flush also runs with scrubbed env for isolation), then runs the same env -u prefix with tools/emit_receipt.py --repo <aesop_root> --post (docs/archive/RECEIPT-GATE.md); both scripts run from the BASE copy (gate_base_dir), and a base copy without emit_receipt.py fails closed. Day-1 measurement found 41 merged PRs and ZERO receipts (nothing ever ran the emitter); this makes emission automatic instead of lane-memory-dependent. Isolation and spool-and-flush: the env -u prefix scrubs git hook environment variables to prevent matrix parts from committing to the lane's repo via inherited GIT_DIR/GIT_WORK_TREE (defense in depth; emit_receipt.py also scrubs these vars); when emit_receipt.py --post gets 422 (commit not found on GitHub yet because we're in pre-push), instead of raising, it writes the signed envelope to state/receipts/spool/<head_sha>.json and returns "spooled"; the flush step retries any prior spooled receipts before emitting a new one, ensuring receipts are published once shas are pushed; a "spooled" result now also spawns tools/receipt_autoflush.py --spawn (a detached poller that posts the receipt once the sha is on GitHub; log <spool>/<sha>.flush.log; AESOP_RECEIPT_AUTOFLUSH=0 opts out). CONCLUSION GATE (2026-10-15, PR #990 pushed a known-red head): the emitter runs with --fail-on-red, so exit 3 (a required part red) BLOCKS the push after the failure receipt is posted; exit 4 (red under AESOP_PUSH_RED=1, receipt stamped pushed_red: true) is the recorded override; any other exit, or a timeout, is an unreadable conclusion and BLOCKS (fail closed); a missing python, gh, or signing-key material BLOCKS (receipt_emit_no_python / _no_gh / _no_key_material), and so does a missing base emitter (receipt_emit_base_tool_missing): no conclusion can be produced or signed. The default matrix re-runs all 4 python shards (measured ~500s for the slowest shard alone), so the emit call is wrapped in timeout (AESOP_RECEIPT_TIMEOUT, default 900s) — a timeout blocks with a BLOCKED line, never hangs the push. AESOP_RECEIPT_EMIT=0 is INERT: it logs receipt_emit_optout_ignored and emission runs (no orchestrator-only mechanism exists to honor it). Key path resolution: hooks/pre-push-policy.sh checks for signing key material using the same precedence as tools/receipt_common.py::resolve_receipt_key_path() — AESOP_RECEIPT_KEY env var, then AESOP_RECEIPT_HMAC_SECRET env var, then ~/.aesop/receipt_key.pem (or $AESOP_HOME/.aesop/receipt_key.pem if AESOP_HOME is set). Only if none of the three exist does the hook BLOCK (fail closed); lane shells without the env vars can still emit receipts via the default path. Tests: tests/test_pre_push_policy.sh. 18b. No-timeout receipt branch exit code (check_emit_receipt, hosts with no timeout/gtimeout): the background-job path captures the child's real status with wait "$receipt_pid" || wait_rc=$? and passes it to the same exit-code handling as the timeout path, so a red matrix (exit 3) blocks the push and exit 4 stays the recorded AESOP_PUSH_RED override. The earlier wait ... || true then $? form always read 0 and failed open. Regression case: red_no_timeout in tests/test_pre_push_policy.sh, which shadows timeout/gtimeout to exercise this branch. 18c. Bounded python probe (resolve_py_bin): each candidate (python3, then python) is probed with timeout 5 "$c" -c "import sys"; an unusable or hung candidate is skipped with a WARN line, and no usable interpreter fails closed (Error: no usable python interpreter; push blocked., exit 1). Resolved once per push in main() via _AESOP_PY_BIN. Regression case: the hung-python3 push test in tests/test_pre_push_policy.sh. Unnumbered checks also in the file: check_aesop_root_pin() blocks on an AESOP_ROOT mismatch; check_gate_tamper() is a non-blocking GATE-CHANGED banner; check_escape_rate() alerts only and always returns 0. 19a. Crash-backup refs: a push whose EVERY remote ref matches ^refs/heads/backup/crash-YYYY-MM-DD/<name>$ (backup_only_push) skips ONLY the metrics and test_coverage gates (stderr NOTE + audit event gate_skipped_backup_ref); secret scan and all other gates still run; mixed, malformed or empty stdin runs everything. Tests: tests/test_pre_push_policy.sh.
  19. Policy violations trigger log_block() to append audit record (JSON-lines) before exit

Audit Ledger: Append-only path: <root>/state/SECURITY-AUDIT.log (git-ignored). Escape-rate counter (EXIT trap, never blocks): counts skipped|opted_out|tool_missing|no_python|red_override events in the last hour; above AESOP_ESCAPE_ALERT_THRESHOLD (default 3, clamped to 3) writes one escape_rate_ALERT line and one ALERT: stderr line per hour. Tests: "escape-rate counter" in tests/test_pre_push_policy.sh. Schema: {"seq":N,"prev_hash":"SHA256_OF_PREV_LINE","ts":"2025-07-12T14:32:01Z","repo":"aesop","event":"push_blocked","reason":"secret_scan_failure"|"push_to_protected_branch","user":"alice"}

  • seq: Monotonically increasing (starts 1); detects truncation.
  • prev_hash: SHA-256 of prior line (no newline); first entry = "GENESIS". Detects tampering.
  • All string values must be JSON-escaped (backslash → \\, quote → \", control chars → \uXXXX).
  • Concurrent writes run one critical section (read tail, compute, append) under an atomic directory lock (.audit-log-lock/, owner pid recorded as BASHPID). mkdir alone does not grant ownership (CI run 43636610785: two writers both got mkdir success for one dir): the winner creates <lock>/pid with an O_EXCL noclobber write; a loser keeps waiting and never touches the dir. Opt-in AUDIT_TRACE_FILE logs lock events (diagnostic, reduce once CI is clean). Only the owner's release removes the lock; there is no age-based or pid-based reclaim (an mv-based reclaim raced a live release and forked the chain, 2026-11-14). A writer waits up to AUDIT_LOCK_DEADLINE_SECS (60s, poll 0.05s), then FAILS with exit 1 and never writes unlocked; later acquires in that process make one try and return 1 at once if it fails (AUDIT_LOCK_UNAVAILABLE; a lock freed meanwhile is still taken), and a fresh process tries normally.
  • Accepted consequence of no-reclaim: a writer killed between mkdir and the pid create leaves a lock dir nothing removes, and every later push fails its audit write until it is cleared. The acquire error gives the owner pid (absent or not running), the lock dir age in seconds, and the manual step: once no push is running, remove the lock directory (rm -rf -- <state>/.audit-log-lock); never automatic. Tail-hash sidecar (state/.audit-tail-hash) anchors against truncation. A record that hits the deadline (or a fast-failed acquire) is NOT chained: it spills to state/audit-spill-<pid>-<ts>.jsonl (never dropped), the write returns 1, and the next lock holder merges spills in ts-then-pid order before verifying the sidecar.

Installation:

  • Symlink (Unix/macOS/Git Bash): ln -s ../../hooks/pre-push-policy.sh .git/hooks/pre-push && chmod +x .git/hooks/pre-push
  • Copy (Windows): cp hooks/pre-push-policy.sh .git/hooks/pre-push (or PowerShell Copy-Item)
  • Auto-installed by scaffold; npx @matt82198/aesop [dir] --force to replace existing hook.

Test Command: bash hooks/pre-push-policy.sh --test — runs 27 validation tests covering: branch policy (blocks main/master, allows feature/*, tag-only, mixed), secret scan (multi-ref, no-starvation), audit log (JSON format, escaping, hash-chain), hash verification, documentation gates skipping when there is no aesop checkout, the same gates failing CLOSED when tools/ exists but their script is missing, tool index gate validation (passes when INDEX in sync, fails when INDEX line missing), CLAUDE.md headroom exit contract (0/1/2), the generated-path gate (fail-open when tool missing, blocks a registered path, passes an ordinary one), the conflict-marker gate (fail-open when tool missing, blocks a push introducing a literal marker), and get_commit_range() behavior (uses origin/main for new branches in worktrees with stale local main, not the stale ref). Exit 0 = pass; exit 1 = fail. python -m unittest tests.test_generated_paths drives check_generated_paths() against the REAL registry over fixture git repos (rejection, generator naming, escape hatch, delete-only, fail-open). python tests/test_conflict_marker_check.py drives tools/conflict_marker_check.py directly (full-tree + --staged diff modes, allowlist, inline suppression, binary skip, fail-closed on a bad range).

Gate tool resolution (fail-closed)

gate_tool_status() classifies a missing gate script into ok / skip / missing:

  • skip — $aesop_root/tools does not exist at all: no aesop checkout, nothing to gate. Logs <gate>_skipped_no_aesop_tools, returns 0. This is the adopter case the fail-open was for.
  • missing — tools/ exists but this gate's script does not. Blocks the push (<gate>_tool_missing). Previously every absence was treated as skip, so deleting, renaming, or failing to ship one gate script silently disabled it in the repo that owns it — a green push that verified nothing.
  • Interpreter absence is likewise fail-closed (<gate>_no_python); the top-of-file guard already hard-requires Python, so a fail-open branch there was dead code that only looked like a safety valve.
  • Executability is not required. Gates run as "$py_bin" "$script", so the exec bit is irrelevant; demanding -x turned any checkout without exec bits into a silently ungated one.
  • check_encoding_lint and check_test_coverage now resolve their root via resolve_aesop_root(). They still used the hardcoded ${AESOP_ROOT:-$HOME/aesop} fallback, which ran the primary tree's script when pushing from a worktree and skipped the gate outright on any machine without ~/aesop.

Verify Audit Log: bash hooks/pre-push-policy.sh --verify-audit-log — detects hash-chain breaks and tail truncation via sidecar anchor.

pre-commit-waveguard.sh

Prevents accidental commits to PRIMARY tree during orchestrated wave cycles. Runs on git commit via .git/hooks/pre-commit.

Mechanism: Orchestrator sets marker file state/.wave-in-flight in PRIMARY tree only (git-ignored, so sibling worktrees do NOT inherit it during checkout). Hook resolves marker relative to CURRENT tree via git rev-parse --show-toplevel — NOT hardcoded $AESOP_ROOT (that resolved to primary from every worktree and blocked entire fleet mid-wave: wave-24 incident). Primary tree (marker present) → exit 1; sibling worktree (no marker) → exit 0.

Error Message: Error: Wave in flight in this tree (<marker_path>). Commit from a sibling worktree, or clear the marker to override.

Installation: bash hooks/install-waveguard.sh idempotently installs into .git/hooks/pre-commit. If a pre-commit hook already exists, backs it up (.git/hooks/pre-commit.waveguard-backup) and chains both (waveguard first, existing hook second).

Exit Contract: Exit 0 = marker absent, commit allowed (normal); Exit 1 = marker present, commit blocked.

force-model-policy.mjs

Claude Code PreToolUse hook enforcing "subagents are always Haiku" cardinal rule (cost optimization).

Policy:

  • Main orchestrator (Fable/Opus on primary): no constraint
  • Subagent dispatch (Agent/Task): enforce Haiku or cardinal_rules.subagent_model from aesop.config.json (searched in $AESOP_ROOT, then cwd). Non-compliant model rewritten before dispatch.
  • Escape hatch: Prompt containing [[ALLOW-NON-HAIKU]] bypasses rewrite; escape logged to state/MODEL-POLICY-ESCAPES.log (JSON-lines: ts, event, tool, session_id, cwd, description, requested_model, prompt_head).

Fail-closed reliability: Malformed, empty, or timed-out stdin (2s race), or an internal error → permissionDecision: "deny" with a fixed one-line reason, exit 0. Hook never crashes harness or logs payload contents.

Registration (.claude/settings.json):

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Agent|Task",
        "hooks": [{"type":"command","command":"node \"$CLAUDE_PROJECT_DIR/hooks/claude/force-model-policy.mjs\""}]
      }
    ]
  }
}

Test Command: node --test tests/force-model-policy.test.mjs (the .mjs itself has no --test mode). Validates Haiku allowed on subagents, non-Haiku (e.g., Opus) blocked, orchestrator not subject to policy, JSON logging format valid. Exit 0 = pass; exit 1 = fail.

Record-discipline guards (no-heredoc-file-authoring.mjs, no-scrollback-as-record.mjs)

Two Claude Code PreToolUse hooks, one owner per rule. Full rule + evidence lives in each .mjs file's header comment; both are gates (refuse before the cost is paid), not memories (advisory, read after the fact), and both fail open on malformed stdin.

HookMatcherDeniesEscape hatch (logged)
no-heredoc-file-authoring.mjsBashany heredoc in a Bash command — cat/tee and interpreter-piped forms (python - <<PY, node <<JS, sh <<SH) alike; single-line printf/echo redirects stay allowed[[ALLOW-HEREDOC-WRITE]] -> ${AESOP_ROOT:-$HOME/aesop}/state/HEREDOC-WRITE-ESCAPES.log
no-scrollback-as-record.mjsBash|Read|Grep|Globreading ~/.claude/projects/**/*.jsonl session transcripts as the record, via shell or Read/Grep/Glob; the memory/ subtree stays allowed[[ALLOW-TRANSCRIPT-READ]] -> ~/.claude/TRANSCRIPT-READ-ESCAPES.log

Registration: same .claude/settings.json hooks.PreToolUse shape as force-model-policy.mjs above — one entry per hook, each with its own matcher from the table and command pointing at that hook's path under hooks/claude/.

Test Command: node hooks/claude/no-heredoc-file-authoring.test.mjs and node hooks/claude/no-scrollback-as-record.test.mjs — 19 co-located behavioral cases (no-heredoc) and 34 (no-scrollback-as-record, incl. the transcript-read bypass forms: cd ~/.claude && cat projects/..., globs, $HOME/CLAUDE_CONFIG_DIR paths, relative Read/Grep paths) (verdictFor exported directly; no --test mode). Exit 0 = pass; exit 1 = fail.

pre-commit-dispatch-lint.sh

Pre-commit hook running tools/dispatch_lint.py on staged files. Blocks commits containing dispatch policy violations (forbidden flags like --admin, --no-verify, git stash, credential hunting). BASH_SOURCE guarded. Blocks on the linter's exit code (1 = violations, printed findings; 2 = error) and fails CLOSED when python or tools/dispatch_lint.py is missing. Installed chained after the waveguard step in .git/hooks/pre-commit by hooks/install-waveguard.sh and the scaffolder (bin/cli.js installPreCommitWaveguard); an existing wrapper is skipped by the installer, so delete .git/hooks/pre-commit and re-run it to pick this step up. Test: bash tests/test_pre_commit_dispatch_hook.sh.

Key Invariants

  • Bash required (explicit shebang), CRLF-safe
  • Tolerate git pre-push stdin (ref list: <local-ref> <local-oid> <remote-ref> <remote-oid> per line) + optional args without crashing
  • Fail-closed for policy checks (branch, marker, model) AND for any gate whose script is missing from an existing tools/; skip only when there is no aesop checkout at all (see § Gate tool resolution). secret_scan.py absent is already fail-closed (FATAL, push denied)
  • Root: an aesop checkout's git toplevel (has tools/, or package name @matt82198/aesop) wins; AESOP_ROOT is a fallback outside a checkout and a mismatch blocks (check_aesop_root_pin, logs aesop_root_pin_mismatch); no hardcoded machine paths/usernames. The pin check compares directory identity with [ AESOP_ROOT -ef toplevel ], not pwd -P strings: on Git Bash pwd -P maps one directory to different strings by spelling (C:/... -> /tmp/..., /c/... -> /c/...), which blocked a checkout that is the pinned root. -ef fails closed when the pinned path does not exist.
  • Local convenience defense only; real enforcement requires server-side branch protection (GitHub) and centralized audit logs

hook_preflight.py — Interpreter health check

Verifies interpreters in hooks/daemons are present and executable. Detects missing/broken interpreters that silently fail. Usage: python tools/hook_preflight.py — exit 0=all OK, 1=broken interpreter, 2=no checks performed. Early guard in pre-push-policy.sh blocks push if Python missing (required for secret_scan.py).

  • CODEOWNERS (.github/CODEOWNERS): owner map for the enforcement surface (hooks/, gate tools, workflows, baselines) -- tests/test_codeowners.py fails when a gate tool has no owner line.

Dropped (reason)

  • docs/archive/HOOK-INSTALL.md comprehensive guide inlined above (GitHub config, troubleshooting, customization, rotation); refer to that file if org needs full runbook for distribution teams.
  • Map of all domains: /CLAUDE.md
  • Box fence push re-check (pre-push-policy.sh main): when the git dir holds the aesop-box-fence-offline marker, runs tools/box_fence.py --push-check; failure blocks the push (fail-closed).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.