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
In this repository21 other files it gives its agents.
- auth/CLAUDE.mdCLAUDE.md
- bin/CLAUDE.mdCLAUDE.md
- chat/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- daemons/CLAUDE.mdCLAUDE.md
- dash/CLAUDE.mdCLAUDE.md
- driver/CLAUDE.mdCLAUDE.md
- mcp/CLAUDE.mdCLAUDE.md
- monitor/CLAUDE.mdCLAUDE.md
- scan/CLAUDE.mdCLAUDE.md
- skills/CLAUDE.mdCLAUDE.md
- state_store/CLAUDE.mdCLAUDE.md
- stdio/CLAUDE.mdCLAUDE.md
- tests/CLAUDE.mdCLAUDE.md
- tools/CLAUDE.mdCLAUDE.md
- ui/CLAUDE.mdCLAUDE.md
- buildsystemSkill
- dashboardSkill
- fleetSkill
- healthcheckSkill
- powerSkill
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
- Very specific: line 50
All string values must be JSON-escaped (backslash → \\, quote → \", control chars → \uXXXX).
≈ “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.
Files
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 --stagedexit 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:
main()TTY guard — rejects interactive hook invocation (tty stdin) with exit 1 before any checks (fail-closed); logsinteractive_invocation_blocked. Realgit pushalways pipes stdin; tty means human ran hook directly. 2a. Gate pinning (F-04): every gate script runs from the trunk'stools/(gate_base_dir; trunk =origin/HEADtarget, elseorigin/main, elseorigin/masterviagate_trunk_ref; fail-closed when unreadable), never the pushed branch's copy. BOOTSTRAP (no trunk on origin yet): base = HEAD, printsBOOTSTRAP: no trunk on origin; base = HEADonce, and fails closed iftools/INDEX.md,.pyflakes-baseline.jsonor.subprocess-guard-baseline.jsonis not committed at HEAD (the subprocess baseline is read fromgit 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 extractstools/ANDstate_store/(state_storeimportstools.*;tools/tracker_guard.pyimportsstate_store.read_api) into cacheaesop-gate-base-v5-<uid>-<sha>(the exec bit is set ontools/*.pyso the[ -x ]check incheck_secret_scanpasses 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.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 targetingrefs/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/xfrom local main is allowed). The current-branch check is only a fallback when stdin carries no tuples at all.check_secret_scan()— runstools/secret_scan.py --rangefor 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 usinggit 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.check_import_resolution()— runstools/import_resolution_check.py --rangeonce per ref tuple on git pre-push stdin (guardrail G5), reusingget_commit_range()exactly ascheck_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 evaluatedgit 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.check_conflict_markers()— runstools/conflict_marker_check.py --stagedonce per ref tuple on git pre-push stdin (reusingget_commit_range()exactly ascheck_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_failurelogged). Added after the PR #834 incident, where a merge commit (b2c4db77) landed a literal<<<<<<< HEADblock intools/CLAUDE.mdon 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) — runstools/pr_symbol_survival_check.py --base <remote-sha> --head <local-sha>once per ref tuple fromget_commit_range(); blocks (exit 1 = symbol dropped by a merge commit in range, exit 2 = tool/git error,symbol_survival_failurelogged). The script runs from the BASE copy (gate_base_dir, trunktools/), 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).--testTest 29 drives this function against a lossy merge (must block) and a clean push (must pass).check_tracker_guard()— runstools/tracker_guard.py --checkagainst live runtime state (AESOP_STATE_ROOT, default$AESOP_ROOT/state); exit 1 (push blocked,tracker_guard_failurelogged) 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_missinglogged) — the hook installs into repos without an aesop checkout.check_claudemd_sync()— runstools/claudemd_sync_gate.py --checkto 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.check_gen_tool_index()— runstools/gen_tool_index.py --checkto 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. Alsocheck_machinery_map_symbols()(after it): runstools/check_machinery_map_symbols.py --checkon 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 andbin/cli.jsis 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.check_metrics()— runstools/metrics_gate.pyto 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 runsmetrics_gate.py <range>once per range fromget_commit_range(), the same derivationcheck_secret_scan()uses. Empty, delete-only and unparseable stdin fall back to the defaultorigin/main...HEADrange (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 emptyX..Xand scanned zero files for the tag.- 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 runstools/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. check_claudemd_headroom()— runstools/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_REFnaming the branch head is refused (claudemd_headroom_base_is_branch_head). A missing tool fails open, loggingclaudemd_headroom_skipped_tool_missing.check_encoding_lint()— runstools/encoding_lint.py --checkover the WHOLE repo. There is NO baseline: the tool has no--baselineflag, so this gate is fail-closed on any finding anywhere and one violation blocks every Python-touching push. (The committed.encoding-baseline.jsonthat nothing read was removed as a dead baseline with no consumer -- see the dead-baseline liveness guardrail.) Flagssubprocess.run/check_output/Popenwithtext=True/universal_newlines=Trueand noencoding=(the Windows cp1252 trap), ANDsubprocess.*that setsencoding=without a safeerrors=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: callsresolve_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.check_test_coverage()— runstools/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: callsresolve_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.check_generated_paths()— runstools/generated_paths.py --checkover the pushed diff (each ref tuple's<remote-sha>..<local-sha>range throughgit 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_editlogged) 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 hatchAESOP_ALLOW_GENERATED=1(honored inside the tool; exactly1, 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 bycheck_secret_scan, which runs first).check_generated_regen()— runstools/generated_push_gate.py --range <remote-sha>..<local-sha>(one--rangeper ref tuple, same captured stdin ascheck_generated_paths()), preceded byensure_merge_drivers()(fail-open, quiettools/install_merge_drivers.py: registers theaesop-json-unionandaesop-regenmerge 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::REGISTRYentries with aregenargv — todaytools/INDEX.md), or the merge driver's per-worktree.needs-regenstamp names one, it checks the tip out in a throwaway detached worktree, runs the registered generator there, and exits 1 (generated_artifact_stalelogged) printing exactlyrun: python tools/gen_tool_index.py --regenerate && git add tools/INDEX.mdwhen the committed bytes differ. Closes the gap behind #784/#856/#739:check_gen_tool_index()(item 8) runs--checkon the WORKING TREE, so a regenerated-but-uncommitted tree or aunion-stale merge commit pushed green and failed ci(0). No escape hatch (a stale artifact is never a legitimate write); fail-closed whentools/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 trunktools/copy fromgate_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 overmerge-base(origin/main, tip)..tip) whose tip blob equals the merge-base blob is INHERITED unchanged from trunk and not verified; the gate printsgenerated 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_tamperalso flagstools/gen_*.pyandtools/generated_*.pyin the GATE-CHANGED banner.check_linux_shape()— runstools/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.mjsand 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 withUSERPROFILEunset 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 (unlessAESOP_REQUIRE_LINUX_SHAPE=1), except that a push touching covered paths (the gate's ownshould_check_linux_shaperule, 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).check_pyflakes_ratchet()(guardrail G15) — runstools/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/ withpython -m pyflakes. Never lets unused-import / unused-variable debt grow: NEW findings above baseline block the push (exit 1,pyflakes_ratchet_failurelogged); 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 linepyflakes 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 viaAESOP_PYFLAKES_SKIP=1(exact string match) for emergency escapes (logspyflakes_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 whentools/exists, no python, or any non-zero exit; skips only with no aesop checkout. Parity with ci.yml is asserted bytests/test_pre_push_policy.shTest 40. 17c.check_inprocess_http_timeout()(escape main-full-windows-shard2-ui-acceptance-timeout) -- runstools/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 (_generatedolder 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").check_emit_receipt()— runs LAST, only after every check above has passed: first callsenv -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 sameenv -uprefix withtools/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 withoutemit_receipt.pyfails 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: theenv -uprefix 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.pyalso scrubs these vars); whenemit_receipt.py --postgets 422 (commit not found on GitHub yet because we're in pre-push), instead of raising, it writes the signed envelope tostate/receipts/spool/<head_sha>.jsonand 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 spawnstools/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=0opts 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 underAESOP_PUSH_RED=1, receipt stampedpushed_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 intimeout(AESOP_RECEIPT_TIMEOUT, default 900s) — a timeout blocks with a BLOCKED line, never hangs the push.AESOP_RECEIPT_EMIT=0is INERT: it logsreceipt_emit_optout_ignoredand 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 astools/receipt_common.py::resolve_receipt_key_path()—AESOP_RECEIPT_KEYenv var, thenAESOP_RECEIPT_HMAC_SECRETenv var, then~/.aesop/receipt_key.pem(or$AESOP_HOME/.aesop/receipt_key.pemif 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 notimeout/gtimeout): the background-job path captures the child's real status withwait "$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 recordedAESOP_PUSH_REDoverride. The earlierwait ... || truethen$?form always read 0 and failed open. Regression case:red_no_timeoutintests/test_pre_push_policy.sh, which shadowstimeout/gtimeoutto exercise this branch. 18c. Bounded python probe (resolve_py_bin): each candidate (python3, thenpython) is probed withtimeout 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 inmain()via_AESOP_PY_BIN. Regression case: the hung-python3push test intests/test_pre_push_policy.sh. Unnumbered checks also in the file:check_aesop_root_pin()blocks on anAESOP_ROOTmismatch;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 eventgate_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.- 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 asBASHPID).mkdiralone does not grant ownership (CI run 43636610785: two writers both got mkdir success for one dir): the winner creates<lock>/pidwith an O_EXCL noclobber write; a loser keeps waiting and never touches the dir. Opt-inAUDIT_TRACE_FILElogs 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 toAUDIT_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
mkdirand 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 tostate/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 PowerShellCopy-Item) - Auto-installed by scaffold;
npx @matt82198/aesop [dir] --forceto 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/toolsdoes 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 asskip, 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-xturned any checkout without exec bits into a silently ungated one. check_encoding_lintandcheck_test_coveragenow resolve their root viaresolve_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_modelfromaesop.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 tostate/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.
| Hook | Matcher | Denies | Escape hatch (logged) |
no-heredoc-file-authoring.mjs | Bash | any 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.mjs | Bash|Read|Grep|Glob | reading ~/.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.pyabsent is already fail-closed (FATAL, push denied) - Root: an aesop checkout's git toplevel (has
tools/, or package name@matt82198/aesop) wins;AESOP_ROOTis a fallback outside a checkout and a mismatch blocks (check_aesop_root_pin, logsaesop_root_pin_mismatch); no hardcoded machine paths/usernames. The pin check compares directory identity with[ AESOP_ROOT -ef toplevel ], notpwd -Pstrings: on Git Bashpwd -Pmaps one directory to different strings by spelling (C:/...->/tmp/...,/c/...->/c/...), which blocked a checkout that is the pinned root.-effails 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.pyfails when a gate tool has no owner line.
Dropped (reason)
docs/archive/HOOK-INSTALL.mdcomprehensive 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.shmain): when the git dir holds theaesop-box-fence-offlinemarker, runstools/box_fence.py --push-check; failure blocks the push (fail-closed).
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
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.

