Skip to content

The agent that grows with you

fix(code-health): one-to-one move matching, real deadlines, index-exact hook

teknium14f70e88c0e67
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 78e2fe97f96..b7afa0e839d 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). 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 (growing a file that is already past 2,000 lines is a warning for now, until the biggest files are split). Pattern rules (blind `except Exception`, missing timeouts, profile-scope hazards such as a hardcoded `~/.hermes` or a new `HERMES_*` env var) compare fingerprints, so existing debt never blocks you but a new instance does. Each finding prints its fix; a genuine exception takes `# health: allow <RULE> -- <why>` on the line, 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 (`--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 (growing a file that is already past 2,000 lines is a warning for now, until the biggest files are split). Pattern rules (blind `except Exception`, missing timeouts, profile-scope hazards such as a hardcoded `~/.hermes` or a new `HERMES_*` env var) compare fingerprints, so existing debt never blocks you but a new instance does. Each finding prints its fix; a genuine exception takes a `# health: allow <RULE> -- <why>` comment on the line, which reviewers read. Rules and targets: `scripts/code_health/config.py`.
### Fail loud at integration boundaries
diff --git a/scripts/check b/scripts/check
index 97de6528d9b..ef699dd51f7 100755
--- a/scripts/check
+++ b/scripts/check
@@ -3,6 +3,7 @@
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
CI runs the same command (``.github/workflows/lint.yml``), so a green local run means a green
@@ -13,9 +14,14 @@ from __future__ import annotations
import argparse
import os
+import shutil
import subprocess
import sys
+import tempfile
+from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
+from contextlib import ExitStack, contextmanager
+from dataclasses import dataclass
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
@@ -32,7 +38,7 @@ repo="$(git rev-parse --show-toplevel)"
[ -f "$repo/scripts/check" ] || exit 0
py=python3
command -v python3 >/dev/null 2>&1 || py=python
-exec "$py" "$repo/scripts/check"
+exec "$py" "$repo/scripts/check" --staged
"""
# name -> argv (relative to the repo root); mirrors the blocking steps in lint.yml.
@@ -45,24 +51,76 @@ _GUARDS = {
}
-def _run(argv: list[str]) -> tuple[int, str]:
+@dataclass
+class _Job:
+ argv: list[str]
+ cwd: Path = REPO
+ env: dict[str, str] | None = None
+
+
+def _run(job: _Job) -> tuple[int, str]:
proc = subprocess.run(
- argv, cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace",
- stdin=subprocess.DEVNULL, timeout=900, check=False,
+ job.argv, cwd=job.cwd, env=job.env, capture_output=True, text=True, encoding="utf-8",
+ errors="replace", stdin=subprocess.DEVNULL, timeout=900, check=False,
)
return proc.returncode, (proc.stdout + proc.stderr).strip()
-def _jobs(only: str | None, base: str | None) -> dict[str, list[str]]:
- jobs = {name: [sys.executable, *argv] for name, argv in _GUARDS.items()}
- jobs["ruff"] = [*resolve_ruff(REPO), "check", "."]
+def _worktree_matches_index() -> bool:
+ unstaged = gitio.git(REPO, "diff", "--name-only", "-z").strip("\0")
+ untracked = gitio.git(REPO, "ls-files", "--others", "--exclude-standard", "-z").strip("\0")
+ return not unstaged and not untracked
+
+
+@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.
+
+ 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.
+ """
+ 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:
+ root = Path(tmp) / "tree"
+ 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)}
+ yield root, env
+
+
+def _jobs(only: str | None, base: str | None, head: str | None,
+ root: Path = REPO, env: dict[str, str] | None = None) -> dict[str, _Job]:
+ jobs = {name: _Job([sys.executable, *argv], root, env) for name, argv in _GUARDS.items()}
+ jobs["ruff"] = _Job([*resolve_ruff(REPO), "check", "."], root, env)
+ # The ratchet reads both sides from git, so it runs in the real repo against the head tree.
health = [sys.executable, "-m", "scripts.code_health"]
- jobs["health"] = health + (["--base", base] if base else [])
+ health += ["--base", base] if base else []
+ health += ["--head", head] if head else []
+ jobs["health"] = _Job(health)
if only:
- return {name: argv for name, argv in jobs.items() if name in only.split(",")}
+ return {name: job for name, job in jobs.items() if name in only.split(",")}
return jobs
+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 ExitStack() as stack:
+ root, env = REPO, None
+ if not _worktree_matches_index():
+ root, env = stack.enter_context(_index_snapshot())
+ 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"
@@ -81,17 +139,17 @@ 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",
+ help="check the index (what `git commit` records), not the working tree")
parser.add_argument("--install-hook", action="store_true")
args = parser.parse_args(argv)
if args.install_hook:
return install_hook()
try:
- jobs = _jobs(args.only, args.base)
+ results = _run_all(args)
except RuntimeError as exc:
print(f"scripts/check: {exc}", file=sys.stderr)
return 2
- with ThreadPoolExecutor(max_workers=len(jobs) or 1) as pool:
- results = dict(zip(jobs, pool.map(_run, jobs.values()), strict=True))
failed = [name for name, (code, _) in results.items() if code != 0]
# A passing health run still carries advisories and comment-allowed findings that the
# reviewer must see, so its report is always shown.
diff --git a/scripts/code_health/cli.py b/scripts/code_health/cli.py
index d0255868907..4e02d61f532 100644
--- a/scripts/code_health/cli.py
+++ b/scripts/code_health/cli.py
@@ -31,7 +31,7 @@ otherwise the target. New code meets the target; existing code may only go down.
def _parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(prog="code_health", description=__doc__)
p.add_argument("--base", help="base revision (default: merge-base of HEAD with origin/main)")
- p.add_argument("--head", help="head revision (default: the working tree, untracked included)")
+ p.add_argument("--head", help="head commit or tree (default: the working tree, untracked included)")
p.add_argument("--report", action="store_true", help="burn-down summary of the whole head tree")
p.add_argument("--json", action="store_true", help="machine-readable findings")
p.add_argument("--print-pins", action="store_true",
@@ -54,7 +54,8 @@ def run(repo: Path, base: str, head: str | None, as_json: bool = False) -> int:
if not head_paths:
print("code health: no measured files changed")
return 0
- needs_ruff = any(p.endswith(".py") for p in head_paths)
+ # Base files are measured too: a deleted .py still needs ruff on the base side.
+ needs_ruff = any(p.endswith(".py") for p in (*head_paths, *base_paths))
ruff = resolve_ruff(repo) if needs_ruff else []
measurer = Measurer(repo, ruff, known_env=gitio.known_env_names(repo, base))
base_m = measurer.measure(base, base_paths)
@@ -82,7 +83,7 @@ def main(argv: list[str] | None = None) -> int:
if args.print_pins:
print(f"ruff=={pinned_version(repo)}")
return 0
- head = gitio.resolve_rev(repo, args.head) if args.head else None
+ head = gitio.resolve_tree(repo, args.head) if args.head else None
try:
if args.report:
return _report(repo, head)
diff --git a/scripts/code_health/compare.py b/scripts/code_health/compare.py
index c3e2cafd0d7..118472eba33 100644
--- a/scripts/code_health/compare.py
+++ b/scripts/code_health/compare.py
@@ -2,93 +2,126 @@
Every unit has its own cap: a function or file already over target may not grow past the value
it has on the base revision; anything new must meet the target. Pattern rules compare multisets
-of fingerprints per file, so fixing one violation and adding another still fails.
+of fingerprints, so fixing one violation and adding another still fails.
-Code that moves keeps its cap and its existing violations, matched by content: a unit's prior is
-the base unit with the same name-independent body hash (same file first, so an anonymous
-callback whose source-order ordinal shifted is still itself; then any file, for a moved
-function), else the base unit with the same qualname. Pattern hits follow ONLY such a proven
-unit move; deleting one function never pays for a violation somewhere else.
+Code that moves keeps its cap and its existing violations. Head units are matched to base units
+ONE-TO-ONE (a base unit is consumed by at most one head unit), in this order:
+
+1. same file, same name, same body (unchanged code; reserved first, so a copy of it is new);
+2. same file, same body (a rename, or an anonymous callback whose ordinal shifted);
+3. any file, same body, when the origin's name is gone from its own file (a real move);
+4. same file, same name (edited in place).
+
+Every base hit is then owned by exactly one head scope: the head unit its unit matched, else the
+same scope in the file's head path. Each old occurrence pays for one new occurrence, never two.
"""
from __future__ import annotations
from collections import Counter, defaultdict
-from dataclasses import dataclass, field
from scripts.code_health.config import ADVISORY_GROWTH, RULES_BY_ID, TARGETS
from scripts.code_health.gitio import Change
from scripts.code_health.model import MODULE_SCOPE, FileMeasure, Finding, Hit, Unit
-# (base path, base qualname) a head unit was matched to.
-Origin = tuple[str, str]
-
-
-@dataclass
-class _Moved:
- """Base units absent from their own file at head: candidates for a cross-file move."""
-
- units: dict[str, list[tuple[str, Unit]]] = field(default_factory=lambda: defaultdict(list))
-
- def take(self, body_hash: str) -> tuple[str, Unit] | None:
- bucket = self.units.get(body_hash)
- return bucket.pop() if bucket else None
+Key = tuple[str, str] # (path, qualname)
+
+
+class _Matcher:
+ def __init__(self, base: dict[str, FileMeasure], head: dict[str, FileMeasure],
+ base_of: dict[str, str | None], head_of: dict[str, str | None]) -> None:
+ self.base, self.head, self.base_of, self.head_of = base, head, base_of, head_of
+ self.taken: set[Key] = set()
+ self.match: dict[Key, tuple[str, Unit]] = {}
+ self.by_hash: dict[str, list[tuple[str, Unit]]] = defaultdict(list)
+ for bpath, bf in sorted(base.items()):
+ for unit in bf.units.values():
+ self.by_hash[unit.body_hash].append((bpath, unit))
+
+ def _base_file(self, hpath: str) -> tuple[str | None, FileMeasure | None]:
+ bpath = self.base_of.get(hpath, hpath)
+ return bpath, (self.base.get(bpath) if bpath else None)
+
+ def _name_gone(self, bpath: str, qual: str) -> bool:
+ if "<anon>" in qual: # ordinals are positional, never evidence that the unit survived
+ return True
+ hpath = self.head_of.get(bpath, bpath)
+ hf = self.head.get(hpath) if hpath else None
+ return hf is None or qual not in hf.units
+
+ def _claim(self, key: Key, origin: tuple[str, Unit]) -> None:
+ self.match[key] = origin
+ self.taken.add((origin[0], origin[1].qualname))
+
+ def _free(self, bpath: str | None, qual: str) -> bool:
+ return bpath is not None and (bpath, qual) not in self.taken
+
+ def run(self) -> dict[Key, tuple[str, Unit]]:
+ pending = [(hpath, q, u) for hpath, hf in sorted(self.head.items()) for q, u in hf.units.items()]
+ passes = (self._same_unchanged, self._same_file_body, self._moved_body, self._same_name)
+ for step in passes:
+ pending = [(hpath, q, u) for hpath, q, u in pending if not step(hpath, q, u)]
+ return self.match
+
+ def _same_unchanged(self, hpath: str, qual: str, unit: Unit) -> bool:
+ bpath, bf = self._base_file(hpath)
+ prior = bf.units.get(qual) if bf else None
+ if bpath is None or prior is None or prior.body_hash != unit.body_hash:
+ return False
+ if not self._free(bpath, qual):
+ return False
+ self._claim((hpath, qual), (bpath, prior))
+ return True
+
+ def _same_file_body(self, hpath: str, qual: str, unit: Unit) -> bool:
+ bpath, _ = self._base_file(hpath)
+ for opath, origin in self.by_hash.get(unit.body_hash, []):
+ if opath == bpath and self._free(opath, origin.qualname):
+ self._claim((hpath, qual), (opath, origin))
+ return True
+ return False
+
+ def _moved_body(self, hpath: str, qual: str, unit: Unit) -> bool:
+ for opath, origin in self.by_hash.get(unit.body_hash, []):
+ if self._free(opath, origin.qualname) and self._name_gone(opath, origin.qualname):
+ self._claim((hpath, qual), (opath, origin))
+ return True
+ return False
+
+ def _same_name(self, hpath: str, qual: str, unit: Unit) -> bool:
+ bpath, bf = self._base_file(hpath)
+ if bpath is None or bf is None or qual not in bf.units or not self._free(bpath, qual):
+ return False
+ self._claim((hpath, qual), (bpath, bf.units[qual]))
+ return True
+
+
+def _file_findings(path: str, hf: FileMeasure, bf: FileMeasure | None) -> list[Finding]:
+ lines = hf.metrics.get("FILE_LINES", 0)
+ if lines <= TARGETS["FILE_LINES"]:
+ return []
+ base_lines = bf.metrics.get("FILE_LINES", 0) if bf else 0
+ if lines <= max(TARGETS["FILE_LINES"], base_lines):
+ return []
+ grew_over = base_lines > TARGETS["FILE_LINES"] and "FILE_LINES" in ADVISORY_GROWTH
+ return [Finding(path, "FILE_LINES", MODULE_SCOPE, 1, _detail(
+ lines, TARGETS["FILE_LINES"], base_lines if bf else None, "lines"), blocking=not grew_over)]
-def _vanished(base: dict[str, FileMeasure], head: dict[str, FileMeasure],
- head_of: dict[str, str | None]) -> _Moved:
- moved = _Moved()
- for bpath, bf in base.items():
- hpath = head_of.get(bpath, bpath)
- hf = head.get(hpath) if hpath else None
- live_hashes = {u.body_hash for u in hf.units.values()} if hf else set()
- for unit in bf.units.values():
- if unit.body_hash not in live_hashes:
- moved.units[unit.body_hash].append((bpath, unit))
- return moved
-
-
-def _prior(qual: str, unit: Unit, bpath: str | None, bf: FileMeasure | None,
- moved: _Moved) -> tuple[Unit, Origin] | None:
- if bf is not None and bpath is not None:
- same_body = [u for u in bf.units.values() if u.body_hash == unit.body_hash]
- if same_body:
- pick = next((u for u in same_body if u.qualname == qual), same_body[0])
- return pick, (bpath, pick.qualname)
- if qual in bf.units:
- return bf.units[qual], (bpath, qual)
- taken = moved.take(unit.body_hash)
- return (taken[1], (taken[0], taken[1].qualname)) if taken else None
-
-
-def _metric_findings(path: str, hf: FileMeasure, bpath: str | None, bf: FileMeasure | None,
- moved: _Moved) -> tuple[list[Finding], dict[str, Origin]]:
+def _unit_findings(path: str, hf: FileMeasure, match: dict[Key, tuple[str, Unit]]) -> list[Finding]:
findings: list[Finding] = []
- lines = hf.metrics.get("FILE_LINES", 0)
- if lines > TARGETS["FILE_LINES"]:
- base_lines = bf.metrics.get("FILE_LINES", 0) if bf else 0
- cap = max(TARGETS["FILE_LINES"], base_lines)
- if lines > cap:
- grew_over = base_lines > TARGETS["FILE_LINES"] and "FILE_LINES" in ADVISORY_GROWTH
- findings.append(Finding(path, "FILE_LINES", MODULE_SCOPE, 1, _detail(
- lines, TARGETS["FILE_LINES"], base_lines if bf else None, "lines"),
- blocking=not grew_over))
- origins: dict[str, Origin] = {}
for qual, unit in hf.units.items():
- matched = _prior(qual, unit, bpath, bf, moved)
- prior = matched[0] if matched else None
- if matched:
- origins[qual] = matched[1]
+ origin = match.get((path, qual))
+ prior = origin[1] if origin else None
for metric, value in unit.metrics.items():
target = TARGETS[metric]
if value <= target:
continue
was = prior.metrics.get(metric) if prior else None
- cap = max(target, was or 0)
- if value > cap:
+ if value > max(target, was or 0):
findings.append(Finding(path, metric, qual, unit.line,
_detail(value, target, was, metric)))
- return findings, origins
+ return findings
def _detail(value: int, target: int, was: int | None, what: str) -> str:
@@ -99,18 +132,18 @@ def _detail(value: int, target: int, was: int | None, what: str) -> str:
return f"{what} {value} > {was}, its value on main (over target {target}: it may only go down)"
-def _base_hits(path: str, bf: FileMeasure | None, origins: dict[str, Origin],
- base: dict[str, FileMeasure]) -> Counter[Hit]:
- """The base hits a head file is compared against: its own base file's, plus those of each
- unit that provably moved or was renamed into it (re-keyed to the unit's head scope)."""
- counter: Counter[Hit] = Counter(bf.hits) if bf else Counter()
- for qual, (opath, oqual) in origins.items():
- if (opath, oqual) == (path, qual) or opath not in base:
- continue
- for hit, count in base[opath].hits.items():
- if hit.scope == oqual:
- counter[Hit(hit.rule, qual, hit.text)] += count
- return counter
+def _owned_base_hits(base: dict[str, FileMeasure], head_of: dict[str, str | None],
+ match: dict[Key, tuple[str, Unit]]) -> dict[str, Counter[Hit]]:
+ """Each base hit, re-keyed once to the head (path, scope) that now owns it."""
+ owner = {(opath, origin.qualname): key for key, (opath, origin) in match.items()}
+ owned: dict[str, Counter[Hit]] = defaultdict(Counter)
+ for bpath, bf in base.items():
+ for hit, count in bf.hits.items():
+ hpath, scope = owner.get((bpath, hit.scope), (head_of.get(bpath, bpath), hit.scope))
+ if hpath is None:
+ continue
+ owned[hpath][Hit(hit.rule, scope, hit.text)] += count
+ return owned
def _hit_findings(path: str, hf: FileMeasure, base_hits: Counter[Hit]) -> list[Finding]:
@@ -130,13 +163,13 @@ def compare(base: dict[str, FileMeasure], head: dict[str, FileMeasure],
changes: list[Change]) -> list[Finding]:
base_of = {c.new: c.old for c in changes if c.new}
head_of = {c.old: c.new for c in changes if c.old}
- moved = _vanished(base, head, head_of)
+ match = _Matcher(base, head, base_of, head_of).run()
+ owned = _owned_base_hits(base, head_of, match)
findings: list[Finding] = []
for path in sorted(head):
hf = head[path]
bpath = base_of.get(path, path)
- bf = base.get(bpath) if bpath else None
- metric, origins = _metric_findings(path, hf, bpath, bf, moved)
- findings += metric
- findings += _hit_findings(path, hf, _base_hits(path, bf, origins, base))
+ findings += _file_findings(path, hf, base.get(bpath) if bpath else None)
+ findings += _unit_findings(path, hf, match)
+ findings += _hit_findings(path, hf, owned.get(path, Counter()))
return findings
diff --git a/scripts/code_health/gitio.py b/scripts/code_health/gitio.py
index bd99b586f3b..afb8f83afb2 100644
--- a/scripts/code_health/gitio.py
+++ b/scripts/code_health/gitio.py
@@ -36,6 +36,11 @@ def resolve_rev(repo: Path, rev: str) -> str:
return git(repo, "rev-parse", "--verify", f"{rev}^{{commit}}").strip()
+def resolve_tree(repo: Path, rev: str) -> str:
+ """A head may be any tree-ish: a commit, or the index's tree from ``git write-tree``."""
+ 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."""
for ref in ("origin/main", "main"):
diff --git a/scripts/code_health/measure.py b/scripts/code_health/measure.py
index 2ab82e5008b..2246d163d47 100644
--- a/scripts/code_health/measure.py
+++ b/scripts/code_health/measure.py
@@ -3,6 +3,8 @@
from __future__ import annotations
import ast
+import io
+import tokenize
import json
import re
import tempfile
@@ -44,6 +46,17 @@ def _own_complexity(fm: FileMeasure, cc_by_line: dict[int, int]) -> None:
fm.units[qual].metrics["CC"] = value
+def _python_comments(text: str) -> dict[int, str]:
+ comments: dict[int, str] = {}
+ try:
+ for tok in tokenize.generate_tokens(io.StringIO(text).readline):
+ if tok.type == tokenize.COMMENT:
+ comments[tok.start[0]] = comments.get(tok.start[0], "") + tok.string
+ except (tokenize.TokenError, SyntaxError):
+ pass # unparseable source has no AST findings to waive either
+ return comments
+
+
class Measurer:
def __init__(self, repo: Path, ruff: list[str], known_env: set[str]) -> None:
self.repo = repo
@@ -81,6 +94,7 @@ class Measurer:
def _python(self, fm: FileMeasure, text: str, ruff_file) -> None:
fm.metrics["FILE_LINES"] = len(fm.lines)
+ fm.comments = _python_comments(text)
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
@@ -112,6 +126,7 @@ class Measurer:
@staticmethod
def _typescript(fm: FileMeasure, data: dict) -> None:
fm.metrics["FILE_LINES"] = len(fm.lines)
+ fm.comments = {line: text for line, text in data.get("comments", [])}
for unit in data.get("units", []):
fm.units[unit["q"]] = Unit(
qualname=unit["q"],
diff --git a/scripts/code_health/model.py b/scripts/code_health/model.py
index 6cb9ad97887..810bcdc463f 100644
--- a/scripts/code_health/model.py
+++ b/scripts/code_health/model.py
@@ -36,8 +36,11 @@ class FileMeasure:
hits: Counter[Hit] = field(default_factory=Counter)
# Line numbers of each hit occurrence, for reporting only.
hit_lines: dict[Hit, list[int]] = field(default_factory=dict)
- # 1-based line -> source text, for allow comments and messages.
+ # 1-based line -> source text, for messages.
lines: list[str] = field(default_factory=list)
+ # 1-based line -> text of the real comment tokens on it (allow directives live only here,
+ # so a string literal that happens to say "health: allow" waives nothing).
+ comments: dict[int, str] = field(default_factory=dict)
def add_hit(self, rule: str, scope: str, line_no: int) -> None:
text = " ".join(self.source_line(line_no).split())
diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.py
index e2e0b0d3300..b09a2cd0961 100644
--- a/scripts/code_health/py_rules.py
+++ b/scripts/code_health/py_rules.py
@@ -66,10 +66,6 @@ def _str_arg(call: ast.Call, index: int = 0) -> str | None:
return None
-def _has_kw(call: ast.Call, name: str) -> bool:
- return any(kw.arg in (name, None) for kw in call.keywords)
-
-
def _env_read_name(node: ast.AST) -> str | None:
"""Env var name for ``os.getenv("X")`` / ``os.environ.get("X")`` / ``os.environ["X"]``."""
if isinstance(node, ast.Call):
@@ -154,6 +150,8 @@ def unscoped_secret_fallback(tree: ast.Module, ctx: Ctx) -> Iterable[int]:
def _capture_lines(expr: ast.AST) -> Iterator[int]:
+ if isinstance(expr, (ast.Lambda, *_FUNCS)):
+ return # a deferred body reads at call time, which is the fix, not the bug
for node in _walk_skipping(expr, (ast.Lambda, *_FUNCS)):
if isinstance(node, ast.Call):
name = _call_name(node)
@@ -166,56 +164,129 @@ def _capture_lines(expr: ast.AST) -> Iterator[int]:
return
-def _is_main_guard(stmt: ast.stmt) -> bool:
- return isinstance(stmt, ast.If) and "__main__" in ast.unparse(stmt.test)
+def _main_guard(stmt: ast.stmt) -> str | None:
+ """``"=="``/``"!="`` for ``if __name__ <op> "__main__":``, else None."""
+ test = stmt.test if isinstance(stmt, ast.If) else None
+ if not (isinstance(test, ast.Compare) and len(test.ops) == 1 and len(test.comparators) == 1):
+ return None
+ sides = {ast.unparse(test.left), ast.unparse(test.comparators[0])}
+ if sides != {"__name__", "'__main__'"}:
+ return None
+ return {ast.Eq: "==", ast.NotEq: "!="}.get(type(test.ops[0]))
+
+
+# Statement blocks that execute when the enclosing block does (``match`` cases via ``cases``).
+_BLOCKS = ("body", "orelse", "finalbody")
+_COMPOUND = (ast.If, ast.Try, ast.TryStar, ast.With, ast.For, ast.While, ast.Match)
+
+
+def _import_time_blocks(stmt: ast.stmt) -> Iterator[list[ast.stmt]]:
+ guard = _main_guard(stmt)
+ if isinstance(stmt, ast.If) and guard is not None:
+ # Only the branch that runs on import: ``else`` of ``==``, body of ``!=``.
+ yield stmt.orelse if guard == "==" else stmt.body
+ return
+ for name in _BLOCKS:
+ yield getattr(stmt, name, None) or []
+ for handler in getattr(stmt, "handlers", None) or []:
+ yield handler.body
+ for case in getattr(stmt, "cases", None) or []:
+ yield case.body
def _import_time_statements(body: list[ast.stmt]) -> Iterator[ast.stmt]:
- """Statements that run at import: module/class bodies and their if/try/with blocks."""
+ """Statements that run at import: module/class bodies and every compound block in them."""
for stmt in body:
- if _is_main_guard(stmt):
- continue
yield stmt
if isinstance(stmt, ast.ClassDef):
yield from _import_time_statements(stmt.body)
- elif isinstance(stmt, (ast.If, ast.Try, ast.With)):
- for name in ("body", "orelse", "finalbody"):
- yield from _import_time_statements(getattr(stmt, name, None) or [])
- for handler in getattr(stmt, "handlers", None) or []:
- yield from _import_time_statements(handler.body)
+ elif isinstance(stmt, _COMPOUND):
+ for block in _import_time_blocks(stmt):
+ yield from _import_time_statements(block)
+
+
+def _import_time_exprs(stmt: ast.stmt) -> Iterator[ast.AST]:
+ """Expressions a statement evaluates at import (not its deferred function bodies)."""
+ if isinstance(stmt, (ast.Assign, ast.AnnAssign, ast.AugAssign)) and stmt.value:
+ yield stmt.value
+ elif isinstance(stmt, (*_FUNCS, ast.ClassDef)):
+ yield from stmt.decorator_list
+ if isinstance(stmt, ast.ClassDef):
+ yield from (*stmt.bases, *(kw.value for kw in stmt.keywords))
+ else:
+ yield from (d for d in [*stmt.args.defaults, *stmt.args.kw_defaults] if d is not None)
+ elif isinstance(stmt, (ast.For, ast.While)):
+ yield stmt.iter if isinstance(stmt, ast.For) else stmt.test
+ elif isinstance(stmt, ast.Match):
+ yield stmt.subject
def import_time_capture(tree: ast.Module, ctx: Ctx) -> Iterable[int]:
for stmt in _import_time_statements(tree.body):
- if isinstance(stmt, (ast.Assign, ast.AnnAssign, ast.AugAssign)) and stmt.value:
- yield from _capture_lines(stmt.value)
- elif isinstance(stmt, _FUNCS):
- for default in [*stmt.args.defaults, *stmt.args.kw_defaults]:
- if default is not None:
- yield from _capture_lines(default)
+ for expr in _import_time_exprs(stmt):
+ yield from _capture_lines(expr)
+
+
+def _finite(node: ast.AST | None) -> bool:
+ """A deadline expression that is present and not a literal ``None``."""
+ return node is not None and not (isinstance(node, ast.Constant) and node.value is None)
+
+
+def _deadline(call: ast.Call, name: str = "timeout", position: int | None = None) -> bool:
+ """True when ``call`` passes a finite deadline: ``name=<not None>``, the positional slot,
+ or ``**opts`` (an unknown mapping is trusted; a literal one must name the deadline)."""
+ if position is not None and len(call.args) > position:
+ return _finite(call.args[position])
+ for kw in call.keywords:
+ if kw.arg == name:
+ return _finite(kw.value)
+ if kw.arg is None:
+ if not isinstance(kw.value, ast.Dict):
+ return True
+ for key, value in zip(kw.value.keys, kw.value.values, strict=True):
+ if isinstance(key, ast.Constant) and key.value == name:
+ return _finite(value)
+ return False
+
+
+def _awaited_calls(body: list[ast.stmt]) -> Iterator[ast.Call]:
+ for stmt in body:
+ for node in _walk_skipping(stmt, (ast.Lambda, *_FUNCS)):
+ if isinstance(node, ast.Await) and isinstance(node.value, ast.Call):
+ yield node.value
-def _bounded_by_wait_for(tree: ast.Module) -> set[int]:
- """ids of calls passed to ``asyncio.wait_for``/``timeout`` (already bounded by the wrapper)."""
+def _bounded_calls(tree: ast.Module) -> set[int]:
+ """ids of calls an asyncio deadline bounds: the awaitable passed to ``wait_for(x, <finite>)``
+ and every call awaited directly inside ``async with asyncio.timeout(<finite>):``."""
bounded: set[int] = set()
for node in ast.walk(tree):
- if isinstance(node, ast.Call) and _call_name(node).rpartition(".")[2] in ("wait_for", "timeout"):
- bounded.update(id(arg) for arg in node.args)
+ if isinstance(node, ast.Call) and _call_name(node).rpartition(".")[2] == "wait_for":
+ if node.args and _deadline(node, "timeout", 1):
+ bounded.add(id(node.args[0]))
+ elif isinstance(node, ast.AsyncWith):
+ for item in node.items:
+ ctx_call = item.context_expr
+ if not isinstance(ctx_call, ast.Call):
+ continue
+ leaf = _call_name(ctx_call).rpartition(".")[2]
+ slot = {"timeout": "delay", "timeout_at": "when"}.get(leaf)
+ if slot and _deadline(ctx_call, slot, 0):
+ bounded.update(id(call) for call in _awaited_calls(node.body))
return bounded
def missing_timeout(tree: ast.Module, ctx: Ctx) -> Iterable[int]:
- bounded = _bounded_by_wait_for(tree)
+ bounded = _bounded_calls(tree)
for node in ast.walk(tree):
- if not isinstance(node, ast.Call) or _has_kw(node, "timeout") or id(node) in bounded:
+ if not isinstance(node, ast.Call) or id(node) in bounded:
continue
- name = _call_name(node)
- head, _, leaf = name.rpartition(".")
- if head == "subprocess" and leaf in _SUBPROCESS_WAITS:
+ head, _, leaf = _call_name(node).rpartition(".")
+ if head == "subprocess" and leaf in _SUBPROCESS_WAITS and not _deadline(node):
yield node.lineno
- elif leaf == "urlopen" and len(node.args) < 3:
+ elif leaf == "urlopen" and not _deadline(node, "timeout", 2):
yield node.lineno
- elif leaf == "communicate" and head and not node.args:
+ elif leaf == "communicate" and head and not _deadline(node, "timeout", 1):
yield node.lineno
diff --git a/scripts/code_health/report.py b/scripts/code_health/report.py
index 02722b84e7b..469976478c0 100644
--- a/scripts/code_health/report.py
+++ b/scripts/code_health/report.py
@@ -19,7 +19,7 @@ def _allow_lines(finding: Finding) -> list[int]:
def apply_allows(findings: list[Finding], head: dict[str, FileMeasure]) -> None:
- """Mark findings whose line carries ``# health: allow RULE -- why`` as allowed.
+ """Mark findings whose line carries ``# health: allow RULE -- why`` (in a real comment) as allowed.
A bare allow without a reason does not count; the finding stays and says why.
"""
@@ -28,7 +28,7 @@ def apply_allows(findings: list[Finding], head: dict[str, FileMeasure]) -> None:
if fm is None:
continue
for line_no in _allow_lines(finding):
- text = fm.source_line(line_no)
+ text = fm.comments.get(line_no, "")
match = _ALLOW.search(text)
if match and finding.rule in {r.strip() for r in match.group(1).split(",")}:
finding.allowed_reason = match.group(2).strip()
diff --git a/scripts/code_health/ts_units.mjs b/scripts/code_health/ts_units.mjs
index f7e75c3adf7..b5552447268 100644
--- a/scripts/code_health/ts_units.mjs
+++ b/scripts/code_health/ts_units.mjs
@@ -91,6 +91,27 @@ function ownName(node) {
return bindingName(node)
}
+// Comment trivia (not string or template text) that carries a `health: allow` directive.
+function allowComments(sf, text) {
+ const found = new Map()
+ const collect = ranges => {
+ for (const range of ranges ?? []) {
+ const body = text.slice(range.pos, range.end)
+ if (body.includes('health:')) {
+ found.set(range.pos, [sf.getLineAndCharacterOfPosition(range.pos).line + 1, body])
+ }
+ }
+ }
+ const visit = node => {
+ collect(ts.getLeadingCommentRanges(text, node.pos))
+ collect(ts.getTrailingCommentRanges(text, node.end))
+ ts.forEachChild(node, visit)
+ }
+ visit(sf)
+ collect(ts.getLeadingCommentRanges(text, sf.endOfFileToken.pos))
+ return [...found.values()]
+}
+
function measureFile(path) {
const text = readFileSync(join(root, path), 'utf8')
const kind = path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
@@ -103,7 +124,9 @@ function measureFile(path) {
return n === 1 ? q : `${q}#${n}`
}
// `lines` is a function's OWN lines: nested functions are their own units, so editing a
- // closure inside a hook never counts against the hook itself.
+ // closure inside a hook never counts against the hook itself. A line is owned by the
+ // innermost function that covers it, so siblings sharing a line give it up once, not twice.
+ const owner = new Map() // line -> unit
const walk = (node, stack, parent) => {
let next = stack
let nextParent = parent
@@ -117,10 +140,10 @@ function measureFile(path) {
const params = node.parameters.map(p => p.getText(sf)).join(',')
const body = (params + '=>' + (node.body ? node.body.getText(sf) : '')).replace(/\s+/g, ' ')
const unit = {
- q: qual, line: start, lines: end - start + 1, cc: complexity(node), nesting: nesting(node),
+ q: qual, line: start, cc: complexity(node), nesting: nesting(node),
hash: createHash('sha1').update(body).digest('hex').slice(0, 16)
}
- if (parent) parent.lines -= end - start + 1
+ for (let line = start; line <= end; line++) owner.set(line, unit)
units.push(unit)
next = [...stack, qual.split('.').pop()]
nextParent = unit
@@ -128,7 +151,9 @@ function measureFile(path) {
ts.forEachChild(node, child => walk(child, next, nextParent))
}
walk(sf, [], null)
- return { units }
+ for (const unit of units) unit.lines = 0
+ for (const unit of owner.values()) unit.lines++
+ return { units, comments: allowComments(sf, text) }
}
const paths = JSON.parse(readFileSync(0, 'utf8'))
diff --git a/tests/scripts/test_code_health.py b/tests/scripts/test_code_health.py
index 40b2568b8c0..bf371fa02d5 100644
--- a/tests/scripts/test_code_health.py
+++ b/tests/scripts/test_code_health.py
@@ -6,6 +6,8 @@ import shutil
import subprocess
from pathlib import Path
+import pytest
+
from scripts.code_health.cli import run
REPO = Path(__file__).resolve().parents[2]
@@ -77,3 +79,37 @@ def test_moved_code_keeps_its_cap(tmp_path, capsys):
renamed: dict[str, str | None] = {"pkg/a.py": None, "pkg/b.py": _LEGACY + "\n\n" + _SWALLOW}
code, out = _verdict(repo, base, renamed, capsys)
assert code == 0, out
+
+
+_RUN = "import subprocess\n\n\ndef f(cmd):\n return subprocess.run(cmd{})\n"
+_PROC = "import asyncio\n\n\nasync def f(proc):\n{}\n"
+_ENV = "import os\n\n{}\n"
+_EXCEPT = " try:\n pass\n except Exception:\n pass\n"
+
+
+_STUB = {"pkg/b.py": "def legacy(x):\n return x\n"}
+
+
[email protected]("extra_base, files, blocks", [
+ # one base unit is credit for one head unit: a copy of unchanged debt is new debt
+ ({}, {"pkg/a.py": _LEGACY + "\n\n" + _SWALLOW + "\n\n" + _LEGACY.replace("legacy", "copied")}, True),
+ # a file rename re-keys each old hit once, so a second swallow in that function is new
+ ({}, {"pkg/a.py": None, "pkg/b.py": _LEGACY + "\n\n" + _SWALLOW + _EXCEPT}, True),
+ # a function moved over a same-name stub keeps its own cap, not the stub's
+ (_STUB, {"pkg/a.py": _SWALLOW, "pkg/b.py": _LEGACY}, False),
+ ({}, {"pkg/p.py": _RUN.format(", timeout=None")}, True), # a disabled deadline is no deadline
+ ({}, {"pkg/p.py": _RUN.format(", **{}")}, True),
+ ({}, {"pkg/p.py": _PROC.format(" return await asyncio.wait_for(proc.communicate(), None)")}, True),
+ ({}, {"pkg/p.py": _PROC.format(" async with asyncio.timeout(1):\n return await proc.communicate()")}, False),
+ # an allow directive inside a string literal waives nothing
+ ({}, {"pkg/p.py": _RUN.format("").replace(" return", " print('health: allow HX006 -- doc')\n return")}, True),
+ ({}, {"pkg/c.py": _ENV.format("if __name__ != '__main__':\n CACHED = os.getenv('PATH')")}, True),
+ ({}, {"pkg/c.py": _ENV.format("for _ in range(1):\n CACHED = os.getenv('PATH')")}, True),
+ ({}, {"pkg/c.py": _ENV.format("current = lambda: os.getenv('PATH')")}, False), # deferred read
+])
+def test_verdicts_follow_ownership_deadlines_and_import_execution(tmp_path, capsys, extra_base, files, blocks):
+ repo, base = _repo(tmp_path)
+ if extra_base:
+ base = _commit(repo, extra_base)
+ code, out = _verdict(repo, base, files, capsys)
+ assert code == (1 if blocks else 0), out