Skip to content

The agent that grows with you

feat(code-health): ENFORCEMENT switch and a pre-push hook

teknium16f0d25c1a1a5
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 82ca9ca80ee..a2ef1740fbf 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -47,6 +47,7 @@ Fixes #
- [ ] I searched for [existing PRs](https://github.com/NousResearch/hermes-agent/pulls) to make sure this isn't a duplicate
- [ ] My PR contains **only** changes related to this fix/feature (no unrelated commits)
- [ ] I've run `pytest tests/ -q` and all tests pass
+- [ ] `python scripts/check` passes (the blocking lint and code-health checks CI runs)
- [ ] I've added tests for my changes (required for bug fixes, strongly encouraged for features)
- [ ] I've tested on my platform: <!-- e.g. Ubuntu 24.04, macOS 15.2, Windows 11 -->
diff --git a/AGENTS.md b/AGENTS.md
index a98e700ea8b..c6d6580c71e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -208,7 +208,8 @@ For tests, use the independent test environment in `CONTRIBUTING.md` (or Nix);
PM activation's `PYTHONPATH` does not survive the test runner's environment scrub.
`scripts/run_tests.sh` probes `.venv`, then `venv`, then `$HOME/.hermes/hermes-agent/venv`
(worktrees sharing the main checkout's venv). **`python scripts/check`** runs every blocking lint
-check CI runs, with CI's pinned tools; run it before pushing (`--install-hook` = pre-commit hook).
+check CI runs, with CI's pinned tools; run it before pushing (`--install-hook pre-push` runs it on
+every push).
## Project Structure
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 399d7a60ae4..ffce7d398ee 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -369,7 +369,7 @@ User message → AIAgent._run_agent_loop()
- **Error handling**: Catch specific exceptions. Log with `logger.warning()`/`logger.error()` — use `exc_info=True` for unexpected errors so stack traces appear in logs
- **Error messages**: every user-facing error message names the actual cause and the remediation step — never the proximate symptom. A missing API key is "no OpenRouter API key configured — set `OPENROUTER_API_KEY`", never "payment/credit error"; a failed request logs the exception class and message (secret-redacted) rather than an empty reason; a timed-out long job reports the timeout and where the job went, not a fallback-routing noise string. If you know the cause, say it; if you don't, say what you do know plus what to check — never a placeholder that points somewhere else.
- **Cross-platform**: Never assume Unix. See [Cross-Platform Compatibility](#cross-platform-compatibility)
-- **Code health ratchet**: `python scripts/check` runs every blocking lint check CI runs, with the same pinned tools (`--install-hook` makes it your pre-commit hook, which judges exactly what you staged). Its code-health part gives every function and file its own cap: new functions stay at cyclomatic complexity ≤ 20, ≤ 300 lines and nesting ≤ 6, files at ≤ 2,000 lines, and code already over a target may only get smaller (a file already past 2,000 lines may not grow: split it first). Pattern rules (blind `except Exception`, missing timeouts, profile-scope hazards such as a hardcoded `~/.hermes` or a new `HERMES_*` env var) track each existing violation where it sits, so existing debt never blocks you, but a new instance does, even one that replaces an identical violation you removed. A file the checker cannot parse or measure fails. Each finding prints its fix; a genuine exception takes a `# health: allow <RULE> -- <why>` comment on the line (or on a comment-only line directly above it), which reviewers read. Rules and targets: `scripts/code_health/config.py`.
+- **Code health ratchet**: `python scripts/check` runs every blocking lint check CI runs, with the same pinned tools. To run it automatically, `python scripts/check --install-hook pre-push` checks each commit you push exactly as CI will judge the PR (`--install-hook` alone runs it on every commit instead, judging what you staged; `--uninstall-hook` removes either; `--no-verify` skips once). The hook covers every worktree of your clone and needs ruff 0.15.10 or `uv` on `PATH`. Its code-health part gives every function and file its own cap: new functions stay at cyclomatic complexity ≤ 20, ≤ 300 lines and nesting ≤ 6, files at ≤ 2,000 lines, and code already over a target may only get smaller (a file already past 2,000 lines may not grow: split it first). Pattern rules (blind `except Exception`, missing timeouts, profile-scope hazards such as a hardcoded `~/.hermes` or a new `HERMES_*` env var) track each existing violation where it sits, so existing debt never blocks you, but a new instance does, even one that replaces an identical violation you removed. A file the checker cannot parse or measure fails. Each finding prints its fix; a genuine exception takes a `# health: allow <RULE> -- <why>` comment on the line (or on a comment-only line directly above it), which reviewers read. Rules and targets: `scripts/code_health/config.py`. Maintainers switch the whole ratchet with `ENFORCEMENT` there (`blocking`, `advisory` or `off`): it is read from the base branch, so a one-line commit to main takes effect for every open PR, CI and local hooks alike, and a PR cannot relax its own check; one rule can be demoted with `blocking=False`.
### Fail loud at integration boundaries
diff --git a/scripts/check b/scripts/check
index 4a71cbb8b24..ffd427b5d23 100755
--- a/scripts/check
+++ b/scripts/check
@@ -4,17 +4,19 @@
python scripts/check # everything, against the merge-base with origin/main
python scripts/check --only health # just the code-health ratchet
python scripts/check --staged # judge the index (the pre-commit hook runs this)
- python scripts/check --install-hook # run it as the git pre-commit hook
+ python scripts/check --commit REV # judge one commit (the pre-push hook runs this)
+ python scripts/check --install-hook [pre-commit|pre-push] # run it automatically
+ python scripts/check --uninstall-hook
CI runs the same command (``.github/workflows/lint.yml``), so a green local run means a green
-lint lane. The pre-commit hook is skippable (``git commit --no-verify``); CI is not.
+lint lane. Hooks are skippable (``--no-verify``); CI is not. The code-health part honours the
+``ENFORCEMENT`` switch in ``scripts/code_health/config.py`` (blocking / advisory / off).
"""
from __future__ import annotations
import argparse
import os
-import shutil
import subprocess
import sys
import tempfile
@@ -30,16 +32,28 @@ sys.path.insert(0, str(REPO))
from scripts.code_health import gitio # noqa: E402
from scripts.code_health.ruff_runner import resolve_ruff # noqa: E402
-_HOOK_MARK = "# hermes-agent scripts/check pre-commit hook"
-_HOOK = f"""#!/usr/bin/env bash
-{_HOOK_MARK} (installed by `scripts/check --install-hook`; skip once with --no-verify)
+_HOOK_MARK = "# hermes-agent scripts/check hook"
+_HOOK_HEAD = f"""#!/usr/bin/env bash
+{_HOOK_MARK} (`scripts/check --install-hook`; skip once with --no-verify)
repo="$(git rev-parse --show-toplevel)"
-# Hooks are shared by every worktree; a branch that predates scripts/check commits unchecked.
+# Hooks are shared by every worktree; a branch that predates scripts/check is not checked.
[ -f "$repo/scripts/check" ] || exit 0
py=python3
command -v python3 >/dev/null 2>&1 || py=python
-exec "$py" "$repo/scripts/check" --staged
"""
+# pre-push reads "<local ref> <local sha> <remote ref> <remote sha>" per pushed ref; an all-zero
+# local sha is a branch deletion. Each pushed commit is judged as CI will judge the PR.
+_HOOKS = {
+ "pre-commit": _HOOK_HEAD + 'exec "$py" "$repo/scripts/check" --staged\n',
+ "pre-push": _HOOK_HEAD + """status=0
+while read -r _ local_sha _ _; do
+ case "$local_sha" in
+ *[!0]*) "$py" "$repo/scripts/check" --commit "$local_sha" </dev/null || status=1 ;;
+ esac
+done
+exit $status
+""",
+}
# name -> argv (relative to the repo root); mirrors the blocking steps in lint.yml.
_GUARDS = {
@@ -66,25 +80,30 @@ def _run(job: _Job) -> tuple[int, str]:
return proc.returncode, (proc.stdout + proc.stderr).strip()
+def _git_in(env: dict[str, str], *args: str) -> None:
+ proc = subprocess.run(["git", *args], cwd=REPO, env=env, capture_output=True, text=True,
+ stdin=subprocess.DEVNULL, timeout=300, check=False)
+ if proc.returncode != 0:
+ raise RuntimeError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
+
+
@contextmanager
-def _index_snapshot() -> Iterator[tuple[Path, dict[str, str]]]:
- """The staged tree checked out on its own, plus git env that sees exactly that tree.
+def _tree_snapshot(tree: str) -> Iterator[tuple[Path, dict[str, str]]]:
+ """``tree`` checked out on its own, plus git env that sees exactly that tree.
- Unstaged edits stay where they are (no stash, no checkout); the index is read from a copy,
- so nothing a checker runs can rewrite the user's real index. Always a snapshot, even when
- the worktree looks clean: ignored files (scratch, build output) are invisible to git status
- but not to the guards that walk the disk.
+ The user's worktree and index are never touched (no stash, no checkout): the tree is read
+ into a private index and written to a temp dir. Always a snapshot, even when the worktree
+ looks clean: ignored files (scratch, build output) are invisible to git status but not to
+ the guards that walk the disk.
"""
- git_dir = Path(gitio.git(REPO, "rev-parse", "--absolute-git-dir").strip())
- index = Path(gitio.git(REPO, "rev-parse", "--path-format=absolute", "--git-path", "index").strip())
- with tempfile.TemporaryDirectory(prefix="hermes-check-index-") as tmp:
+ git_dir = gitio.git(REPO, "rev-parse", "--absolute-git-dir").strip()
+ with tempfile.TemporaryDirectory(prefix="hermes-check-tree-") as tmp:
root = Path(tmp) / "tree"
- root.mkdir() # Git for Windows will not create the --prefix directory itself
- gitio.git(REPO, "checkout-index", "-a", f"--prefix={root}{os.sep}")
- index_copy = Path(tmp) / "index"
- shutil.copyfile(index, index_copy)
- env = {**os.environ, "GIT_DIR": str(git_dir), "GIT_WORK_TREE": str(root),
- "GIT_INDEX_FILE": str(index_copy)}
+ root.mkdir()
+ env = {**os.environ, "GIT_DIR": git_dir, "GIT_WORK_TREE": str(root),
+ "GIT_INDEX_FILE": str(Path(tmp) / "index")}
+ _git_in(env, "read-tree", tree)
+ _git_in(env, "checkout-index", "-a")
yield root, env
@@ -108,29 +127,52 @@ def _jobs(only: str | None, base: str | None, head: str | None,
return jobs
+def _run_jobs(jobs: dict[str, _Job]) -> dict[str, tuple[int, str]]:
+ with ThreadPoolExecutor(max_workers=len(jobs) or 1) as pool:
+ return dict(zip(jobs, pool.map(_run, jobs.values()), strict=True))
+
+
def _run_all(args: argparse.Namespace) -> dict[str, tuple[int, str]]:
- if not args.staged:
- jobs = _jobs(args.only, args.base, None)
- with ThreadPoolExecutor(max_workers=len(jobs) or 1) as pool:
- return dict(zip(jobs, pool.map(_run, jobs.values()), strict=True))
- # Pre-commit: judge the bytes being committed, not the working tree.
- tree = gitio.git(REPO, "write-tree").strip()
- with _index_snapshot() as (root, env):
- jobs = _jobs(args.only, args.base, tree, root, env)
- with ThreadPoolExecutor(max_workers=len(jobs) or 1) as pool:
- return dict(zip(jobs, pool.map(_run, jobs.values()), strict=True))
-
-
-def install_hook() -> int:
- hooks = Path(gitio.git(REPO, "rev-parse", "--path-format=absolute", "--git-path", "hooks").strip())
- target = hooks / "pre-commit"
- if target.exists() and _HOOK_MARK not in target.read_text(encoding="utf-8-sig", errors="replace"):
+ if not (args.staged or args.commit):
+ return _run_jobs(_jobs(args.only, args.base, None))
+ # Hooks judge the bytes being committed or pushed, never the working tree.
+ if args.staged:
+ tree, base = gitio.git(REPO, "write-tree").strip(), args.base
+ else:
+ commit = gitio.resolve_rev(REPO, args.commit)
+ tree, base = gitio.resolve_tree(REPO, commit), args.base or gitio.default_base(REPO, commit)
+ with _tree_snapshot(tree) as (root, env):
+ return _run_jobs(_jobs(args.only, base, tree, root, env))
+
+
+def _hooks_dir() -> Path:
+ return Path(gitio.git(REPO, "rev-parse", "--path-format=absolute", "--git-path", "hooks").strip())
+
+
+def _ours(target: Path) -> bool:
+ return _HOOK_MARK in target.read_text(encoding="utf-8-sig", errors="replace")
+
+
+def install_hook(kind: str) -> int:
+ hooks = _hooks_dir()
+ target = hooks / kind
+ if target.exists() and not _ours(target):
print(f"scripts/check: {target} exists and is not ours; add `python scripts/check` to it")
return 1
hooks.mkdir(parents=True, exist_ok=True)
- target.write_text(_HOOK, encoding="utf-8", newline="\n")
+ target.write_text(_HOOKS[kind], encoding="utf-8", newline="\n")
os.chmod(target, 0o755) # windows-footgun: ok — chmod +x is a no-op on Windows, harmless
- print(f"scripts/check: pre-commit hook installed at {target}")
+ print(f"scripts/check: {kind} hook installed at {target} (every worktree of this clone)")
+ return 0
+
+
+def uninstall_hooks() -> int:
+ removed = [t for t in (_hooks_dir() / k for k in _HOOKS) if t.exists() and _ours(t)]
+ for target in removed:
+ target.unlink()
+ print(f"scripts/check: removed {target}")
+ if not removed:
+ print("scripts/check: no scripts/check hooks installed")
return 0
@@ -139,12 +181,18 @@ def main(argv: list[str] | None = None) -> int:
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--only", help=f"comma list of: {', '.join([*_GUARDS, 'ruff', 'health'])}")
parser.add_argument("--base", help="base revision for the code-health ratchet")
- parser.add_argument("--staged", action="store_true",
+ target = parser.add_mutually_exclusive_group()
+ target.add_argument("--staged", action="store_true",
help="check the index (what `git commit` records), not the working tree")
- parser.add_argument("--install-hook", action="store_true")
+ target.add_argument("--commit", metavar="REV", help="check one commit's tree (pre-push)")
+ parser.add_argument("--install-hook", nargs="?", const="pre-commit", choices=sorted(_HOOKS),
+ help="run on every commit (default) or every push")
+ parser.add_argument("--uninstall-hook", action="store_true", help="remove our git hooks")
args = parser.parse_args(argv)
if args.install_hook:
- return install_hook()
+ return install_hook(args.install_hook)
+ if args.uninstall_hook:
+ return uninstall_hooks()
try:
results = _run_all(args)
except RuntimeError as exc:
diff --git a/scripts/code_health/cli.py b/scripts/code_health/cli.py
index 4e02d61f532..91ef3b3825e 100644
--- a/scripts/code_health/cli.py
+++ b/scripts/code_health/cli.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import argparse
import json
+import re
import sys
import time
from dataclasses import asdict
@@ -25,7 +26,18 @@ _FOOTER = """
Each function and file has its own cap: its value on main if it is already over target,
otherwise the target. New code meets the target; existing code may only go down. Fix the code
(the `fix:` line is the repo's remedy); a genuine exception takes a reviewed comment on the line,
-`# health: allow <RULE> -- <why>`. Rules and targets: scripts/code_health/config.py."""
+`# health: allow <RULE> -- <why>`. Rules and targets: scripts/code_health/config.py.
+Reproduce locally: python scripts/check --only health (every lint check: python scripts/check;
+on every push: python scripts/check --install-hook pre-push)."""
+
+_SWITCH_FILE = "scripts/code_health/config.py"
+_SWITCH = re.compile(r"^ENFORCEMENT\s*=\s*[\"'](blocking|advisory|off)[\"']", re.MULTILINE)
+
+
+def enforcement(repo: Path, base: str) -> str:
+ """The master switch as committed on the base revision; a base without one is blocking."""
+ found = _SWITCH.search(gitio.read_file(repo, base, _SWITCH_FILE) or "")
+ return found.group(1) if found else "blocking"
def _parser() -> argparse.ArgumentParser:
@@ -48,6 +60,10 @@ def _report(repo: Path, head: str | None) -> int:
def run(repo: Path, base: str, head: str | None, as_json: bool = False) -> int:
started = time.monotonic()
+ mode = enforcement(repo, base)
+ if mode == "off":
+ print(f"code health: off (ENFORCEMENT in {_SWITCH_FILE} on {base[:12]})")
+ return 0
changes = gitio.changed_files(repo, base, head)
head_paths = sorted({c.new for c in changes if c.new and in_scope(c.new)})
base_paths = sorted({c.old for c in changes if c.old and in_scope(c.old)})
@@ -63,9 +79,10 @@ def run(repo: Path, base: str, head: str | None, as_json: bool = False) -> int:
findings = compare(base_m, head_m, changes)
apply_allows(findings, head_m)
blocking, advisory = verdict(findings)
+ failed = bool(blocking) and mode == "blocking"
if as_json:
print(json.dumps([asdict(f) for f in findings], indent=2))
- return 1 if blocking else 0
+ return 1 if failed else 0
body = format_findings(findings)
if body:
print(body)
@@ -74,7 +91,9 @@ def run(repo: Path, base: str, head: str | None, as_json: bool = False) -> int:
f"{advisory} advisory ({elapsed:.1f}s)")
if blocking:
print(_FOOTER)
- return 1 if blocking else 0
+ if blocking and not failed:
+ print(f"\nadvisory mode (ENFORCEMENT in {_SWITCH_FILE}): not failing on the above.")
+ return 1 if failed else 0
def main(argv: list[str] | None = None) -> int:
diff --git a/scripts/code_health/config.py b/scripts/code_health/config.py
index b410164b050..c860d3da030 100644
--- a/scripts/code_health/config.py
+++ b/scripts/code_health/config.py
@@ -9,6 +9,12 @@ from __future__ import annotations
from dataclasses import dataclass
from fnmatch import fnmatch
+# Master switch. Read from the BASE revision, so a PR cannot relax its own check, and honoured
+# everywhere the ratchet runs (CI, `scripts/check`, the git hooks). "blocking": findings fail;
+# "advisory": findings print, the run passes; "off": the ratchet is skipped. Flip it with a
+# one-line commit to main; a single rule can instead be demoted with ``blocking=False`` below.
+ENFORCEMENT = "blocking"
+
# Per-unit targets. A unit already over its target keeps its own current value as its cap
# (measured on the base revision) and may only go down; new units must meet the target.
TARGETS = {
diff --git a/scripts/code_health/gitio.py b/scripts/code_health/gitio.py
index 8175514b5c3..d7a1db4cfea 100644
--- a/scripts/code_health/gitio.py
+++ b/scripts/code_health/gitio.py
@@ -41,10 +41,10 @@ def resolve_tree(repo: Path, rev: str) -> str:
return git(repo, "rev-parse", "--verify", f"{rev}^{{tree}}").strip()
-def default_base(repo: Path) -> str:
- """Merge-base of HEAD with origin/main (local runs); CI passes ``--base`` explicitly."""
+def default_base(repo: Path, tip: str = "HEAD") -> str:
+ """Merge-base of ``tip`` with origin/main (local runs); CI passes ``--base`` explicitly."""
for ref in ("origin/main", "main"):
- out = git(repo, "merge-base", "HEAD", ref, check=False).strip()
+ out = git(repo, "merge-base", tip, ref, check=False).strip()
if out:
return out
raise RuntimeError("no merge-base with origin/main or main; pass --base")
diff --git a/tests/scripts/test_code_health.py b/tests/scripts/test_code_health.py
index 7ca489910a1..6f04eb1dada 100644
--- a/tests/scripts/test_code_health.py
+++ b/tests/scripts/test_code_health.py
@@ -70,6 +70,19 @@ def test_ratchet_blocks_growth_new_and_swapped_violations(tmp_path, capsys):
assert code == 1 and "fresh" in out # deleting a violation never pays for an unrelated one
+def test_enforcement_switch_is_read_from_the_base(tmp_path, capsys):
+ repo, base = _repo(tmp_path)
+ grown = _LEGACY + " if x == 99:\n return 99\n\n\n" + _SWALLOW
+ switch = "scripts/code_health/config.py"
+ # A PR cannot relax its own check: the switch it commits is not the one that applies.
+ assert _verdict(repo, base, {"pkg/a.py": grown, switch: 'ENFORCEMENT = "off"\n'}, capsys)[0] == 1
+ for mode, expected in (("advisory", 0), ("off", 0), ("blocking", 1)):
+ main_tip = _commit(repo, {switch: f'ENFORCEMENT = "{mode}"\n'})
+ code, out = _verdict(repo, main_tip, {"pkg/a.py": grown}, capsys)
+ assert code == expected, (mode, out)
+ assert ("CC 23 > 22" in out) == (mode != "off"), (mode, out)
+
+
def test_moved_code_keeps_its_cap(tmp_path, capsys):
repo, base = _repo(tmp_path)
for split in ({"pkg/a.py": _SWALLOW, "pkg/a_legacy.py": _LEGACY},