The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(code-health): occurrence provenance, alias-aware rules, strict file cap (round 4)
teknium1cf0755f947ee
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 4d70dd2c0e5..44a8b17a0d2 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -11,6 +11,9 @@# same review for the same reason./.github/ @NousResearch/hermes-agent-core/scripts/ci/ @NousResearch/hermes-agent-core+# The code-health gate decides whether a PR passes; weakening it is a CI change.+/scripts/check @NousResearch/hermes-agent-core+/scripts/code_health/ @NousResearch/hermes-agent-core# eslint configs can define custom ``fix`` functions that run arbitrary code.eslint.config.* @NousResearch/hermes-agent-corediff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex 3679aa1f41b..cc5df3238e9 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -153,6 +153,7 @@ jobs:uses: ./.github/workflows/lint.ymlwith:event_name: ${{ needs.detect.outputs.event_name }}+ python: ${{ needs.detect.outputs.python == 'true' }}js-tests:name: JS & TS checksdiff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex cf9228ec509..07f2ad0cc57 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -19,6 +19,10 @@ on:description: The event name from the calling orchestrator (pull_request or push).type: stringrequired: true+ python:+ description: Python changed. A frontend-only PR runs just the code-health ratchet (TS).+ type: boolean+ default: truepermissions:contents: read@@ -30,7 +34,7 @@ concurrency:jobs:lint-diff:name: ruff + ty diff- if: inputs.event_name == 'pull_request'+ if: inputs.event_name == 'pull_request' && inputs.pythonruns-on: ubuntu-latesttimeout-minutes: 10steps:@@ -124,6 +128,7 @@ jobs:# ``lint-diff`` job above runs independently so reviewers still get# the diff comment even when enforcement fails.name: ruff enforcement (blocking)+ if: inputs.pythonruns-on: ubuntu-latesttimeout-minutes: 5steps:@@ -180,6 +185,7 @@ jobs:# shebang scripts via subprocess, bare open() without encoding=, etc.# See scripts/check-windows-footguns.py for the full rule list.name: Windows footguns (blocking)+ if: inputs.pythonruns-on: ubuntu-latesttimeout-minutes: 5steps:diff --git a/AGENTS.md b/AGENTS.mdindex a8e50ad377e..a98e700ea8b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -271,7 +271,7 @@ families: `hermes_state.py` (21), `gateway/run.py` (15), `tools/mcp_tool.py` (15(blind repointing to defining modules broke 130+ tests).- **Size and complexity are ratcheted per unit** (`scripts/code_health/config.py`): newfunctions CC ≤ 20, ≤ 300 lines, nesting ≤ 6; files ≤ 2,000 lines; units already over may only- go down (growing a file already past 2,000 is a warning for now). Split along `<stem>_<topic>` first, in its own commit; behaviour goes in a sibling,+ go down (a file already past 2,000 lines may not grow). Split along `<stem>_<topic>` first, in its own commit; behaviour goes in a sibling,never a facade; name ladders become a dict → handler (`_SLASH_DISPATCH`).- **No re-export shims for internal moves** ("keep the old name importable"). Internal pathsare not API: plugins build on `ctx` and the documented ABCs. The one-time Sep 2026diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b7afa0e839d..399d7a60ae4 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 (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`.+- **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`.### Fail loud at integration boundariesdiff --git a/scripts/check b/scripts/checkindex ef699dd51f7..4a71cbb8b24 100755--- a/scripts/check+++ b/scripts/check@@ -20,7 +20,7 @@ import sysimport tempfilefrom collections.abc import Iteratorfrom concurrent.futures import ThreadPoolExecutor-from contextlib import ExitStack, contextmanager+from contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Path@@ -66,23 +66,20 @@ def _run(job: _Job) -> tuple[int, str]:return proc.returncode, (proc.stdout + proc.stderr).strip()-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--@contextmanagerdef _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.+ 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."""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"+ root.mkdir() # Git for Windows will not create the --prefix directory itselfgitio.git(REPO, "checkout-index", "-a", f"--prefix={root}{os.sep}")index_copy = Path(tmp) / "index"shutil.copyfile(index, index_copy)@@ -93,15 +90,21 @@ def _index_snapshot() -> Iterator[tuple[Path, dict[str, str]]]: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"]- health += ["--base", base] if base else []- health += ["--head", head] if head else []- jobs["health"] = _Job(health)+ names = [*_GUARDS, "ruff", "health"]if only:- return {name: job for name, job in jobs.items() if name in only.split(",")}+ names = [n for n in names if n in only.split(",")]+ jobs: dict[str, _Job] = {}+ for name in names: # built only when selected: `--only shebangs` needs no ruff+ if name in _GUARDS:+ jobs[name] = _Job([sys.executable, *_GUARDS[name]], root, env)+ elif name == "ruff":+ jobs[name] = _Job([*resolve_ruff(REPO), "check", "."], root, env)+ else:+ # The ratchet reads both sides from git: real repo, judged against the head tree.+ health = [sys.executable, "-m", "scripts.code_health"]+ health += ["--base", base] if base else []+ health += ["--head", head] if head else []+ jobs[name] = _Job(health)return jobs@@ -112,10 +115,7 @@ def _run_all(args: argparse.Namespace) -> dict[str, tuple[int, str]]: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())+ 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))diff --git a/scripts/code_health/compare.py b/scripts/code_health/compare.pyindex 118472eba33..f68c0d3dd95 100644--- a/scripts/code_health/compare.py+++ b/scripts/code_health/compare.py@@ -14,13 +14,20 @@ ONE-TO-ONE (a base unit is consumed by at most one head unit), in this order:Every base hit is then owned by exactly one head scope: the head unit its unit matched, else thesame scope in the file's head path. Each old occurrence pays for one new occurrence, never two.++An occurrence is old only if it still sits where it was: inside a unit whose body is unchanged+(matched by passes 1-3, so moves and renames keep their debt), or on a line that survives from+the base file (compared without comments or whitespace, so dropping an allow comment or+re-indenting is not new debt). An identical violation re-added on a new line is new, even in+the same function as one that was removed."""from __future__ import annotationsfrom collections import Counter, defaultdict+from difflib import SequenceMatcher-from scripts.code_health.config import ADVISORY_GROWTH, RULES_BY_ID, TARGETS+from scripts.code_health.config import RULES_BY_ID, TARGETSfrom scripts.code_health.gitio import Changefrom scripts.code_health.model import MODULE_SCOPE, FileMeasure, Finding, Hit, Unit@@ -33,6 +40,7 @@ class _Matcher:self.base, self.head, self.base_of, self.head_of = base, head, base_of, head_ofself.taken: set[Key] = set()self.match: dict[Key, tuple[str, Unit]] = {}+ self.same_body: set[Key] = set() # head units matched to an identical base bodyself.by_hash: dict[str, list[tuple[str, Unit]]] = defaultdict(list)for bpath, bf in sorted(base.items()):for unit in bf.units.values():@@ -58,9 +66,10 @@ class _Matcher: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:+ for step in (self._same_unchanged, self._same_file_body, self._moved_body):pending = [(hpath, q, u) for hpath, q, u in pending if not step(hpath, q, u)]+ self.same_body = set(self.match)+ pending = [(hpath, q, u) for hpath, q, u in pending if not self._same_name(hpath, q, u)]return self.matchdef _same_unchanged(self, hpath: str, qual: str, unit: Unit) -> bool:@@ -97,15 +106,16 @@ class _Matcher:def _file_findings(path: str, hf: FileMeasure, bf: FileMeasure | None) -> list[Finding]:+ if hf.error:+ return [Finding(path, "MEASURE", MODULE_SCOPE, 1, f"could not be measured: {hf.error}")]lines = hf.metrics.get("FILE_LINES", 0)if lines <= TARGETS["FILE_LINES"]:return []base_lines = bf.metrics.get("FILE_LINES", 0) if bf else 0if lines <= max(TARGETS["FILE_LINES"], base_lines):return []- grew_over = base_lines > TARGETS["FILE_LINES"] and "FILE_LINES" in ADVISORY_GROWTHreturn [Finding(path, "FILE_LINES", MODULE_SCOPE, 1, _detail(- lines, TARGETS["FILE_LINES"], base_lines if bf else None, "lines"), blocking=not grew_over)]+ lines, TARGETS["FILE_LINES"], base_lines if bf else None, "lines"))]def _unit_findings(path: str, hf: FileMeasure, match: dict[Key, tuple[str, Unit]]) -> list[Finding]:@@ -146,14 +156,29 @@ def _owned_base_hits(base: dict[str, FileMeasure], head_of: dict[str, str | Nonereturn owned-def _hit_findings(path: str, hf: FileMeasure, base_hits: Counter[Hit]) -> list[Finding]:+def _surviving_lines(hf: FileMeasure, bf: FileMeasure | None) -> set[int]:+ """Head lines that are unchanged base lines (code only: comments and whitespace ignored)."""+ if bf is None:+ return set()+ old = [bf.code_line(n) for n in range(1, len(bf.lines) + 1)]+ new = [hf.code_line(n) for n in range(1, len(hf.lines) + 1)]+ # autojunk off: `except Exception:` and `pass` are frequent lines, never noise here.+ blocks = SequenceMatcher(None, old, new, autojunk=False).get_matching_blocks()+ return {b.b + i + 1 for b in blocks for i in range(b.size)}+++def _hit_findings(path: str, hf: FileMeasure, base_hits: Counter[Hit],+ kept: set[int], unchanged_scopes: set[str]) -> list[Finding]:findings: list[Finding] = []- for hit, count in sorted(hf.hits.items(), key=lambda kv: hf.hit_lines[kv[0]][0]):- extra = count - base_hits.get(hit, 0)- if extra <= 0:- continue+ for hit, lines in sorted(hf.hit_lines.items(), key=lambda kv: kv[1][0]):+ if hit.scope in unchanged_scopes:+ old, fresh = lines, []+ else:+ old = [n for n in lines if n in kept]+ fresh = [n for n in lines if n not in kept]+ extra = max(0, len(old) - base_hits.get(hit, 0))rule = RULES_BY_ID[hit.rule]- for line in hf.hit_lines[hit][-extra:]:+ for line in sorted(fresh + old[len(old) - extra:]):findings.append(Finding(path, hit.rule, hit.scope, line, rule.title,blocking=rule.blocking))return findings@@ -163,13 +188,17 @@ 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}- match = _Matcher(base, head, base_of, head_of).run()+ matcher = _Matcher(base, head, base_of, head_of)+ match = matcher.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)- findings += _file_findings(path, hf, base.get(bpath) if bpath else None)+ bf = base.get(bpath) if bpath else None+ unchanged = {qual for hpath, qual in matcher.same_body if hpath == path}+ findings += _file_findings(path, hf, bf)findings += _unit_findings(path, hf, match)- findings += _hit_findings(path, hf, owned.get(path, Counter()))+ findings += _hit_findings(path, hf, owned.get(path, Counter()),+ _surviving_lines(hf, bf), unchanged)return findingsdiff --git a/scripts/code_health/config.py b/scripts/code_health/config.pyindex ba7b95f9919..fd6ef4e019d 100644--- a/scripts/code_health/config.py+++ b/scripts/code_health/config.py@@ -18,11 +18,6 @@ TARGETS = {"FILE_LINES": 2000,}-# Growth of a unit ALREADY over target is advisory for these metrics; crossing the target still-# blocks. Replay of 300 merged PRs: a blocking FILE_LINES ratchet would have stopped 46 of them-# for +2..+70 lines on one of the 119 files already over 2,000, before those files are split.-ADVISORY_GROWTH = {"FILE_LINES"}-METRIC_FIX = {"CC": "split it: extract phases into a topical sibling (`<stem>_<topic>.py`), or replace a"" branch ladder with a dict/table -> handler",@@ -30,6 +25,8 @@ METRIC_FIX = {"NESTING": "return early, or extract the inner block into a helper","FILE_LINES": "split along `<stem>_<topic>` (facade + siblings, see root AGENTS.md); new"" behaviour goes in a new or topical sibling, never appended to a facade",+ "MEASURE": "the file must parse and measure (a file that cannot be measured cannot be"+ " judged); fix the syntax, or report the measurer bug",}PY_EXCLUDE = ("website/*", "*/node_modules/*", "node_modules/*")diff --git a/scripts/code_health/measure.py b/scripts/code_health/measure.pyindex 2246d163d47..184895dad25 100644--- a/scripts/code_health/measure.py+++ b/scripts/code_health/measure.py@@ -88,8 +88,9 @@ class Measurer:ruff_out = run_ruff(self.ruff, root, py) if py else {}for path in py:self._python(result[path], contents[path], ruff_out.get(path))- for path, data in measure_ts(self.repo, root, ts).items():- self._typescript(result[path], data)+ ts_out = measure_ts(self.repo, root, ts) if ts else {}+ for path in ts:+ self._typescript(result[path], ts_out.get(path))return resultdef _python(self, fm: FileMeasure, text: str, ruff_file) -> None:@@ -99,17 +100,21 @@ class Measurer:with warnings.catch_warnings():warnings.simplefilter("ignore", SyntaxWarning)tree = ast.parse(text)- except SyntaxError:+ rules_tree = py_rules.canonical_tree(ast.parse(text))+ except SyntaxError as exc:+ fm.error = f"does not parse: {exc.msg} (line {exc.lineno})"returnscopes = py_structure.measure_structure(fm, tree)- if ruff_file is not None:+ if ruff_file is None or ruff_file.errors:+ fm.error = "ruff could not measure it: " + "; ".join((ruff_file.errors if ruff_file else ["no result"])[:3])+ else:_own_complexity(fm, ruff_file.cc_by_line)for code, row in ruff_file.hits:if code in RULES_BY_ID and rule_applies(RULES_BY_ID[code], fm.path):fm.add_hit(code, scopes.scope(row), row)for rule_id, checker in py_rules.CHECKERS.items():if rule_applies(RULES_BY_ID[rule_id], fm.path):- for row in sorted(set(checker(tree, self.ctx))):+ for row in sorted(set(checker(rules_tree, self.ctx))):fm.add_hit(rule_id, scopes.scope(row), row)self._regex(fm, scopes)@@ -124,8 +129,11 @@ class Measurer:fm.add_hit(rule_id, scopes.scope(index), index)@staticmethod- def _typescript(fm: FileMeasure, data: dict) -> None:+ def _typescript(fm: FileMeasure, data: dict | None) -> None:fm.metrics["FILE_LINES"] = len(fm.lines)+ if data is None or "error" in data:+ fm.error = (data or {}).get("error", "the TypeScript measurer returned nothing for it")+ returnfm.comments = {line: text for line, text in data.get("comments", [])}for unit in data.get("units", []):fm.units[unit["q"]] = Unit(diff --git a/scripts/code_health/model.py b/scripts/code_health/model.pyindex 810bcdc463f..a4079e6c184 100644--- a/scripts/code_health/model.py+++ b/scripts/code_health/model.py@@ -41,10 +41,22 @@ class FileMeasure:# 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)+ # Why this file could not be measured (unparseable, measurer failure): a measurement gap+ # must fail the check, never read as "no findings".+ error: str | None = None++ def code_line(self, line_no: int) -> str:+ """The line's code with its comment removed and whitespace normalised: the identity of+ a violation, so editing or dropping a comment (an allow included) never makes old debt+ look new."""+ line = self.source_line(line_no)+ comment = self.comments.get(line_no)+ if comment and comment in line:+ line = line[: line.rindex(comment)]+ return " ".join(line.split())def add_hit(self, rule: str, scope: str, line_no: int) -> None:- text = " ".join(self.source_line(line_no).split())- hit = Hit(rule, scope, text)+ hit = Hit(rule, scope, self.code_line(line_no))self.hits[hit] += 1self.hit_lines.setdefault(hit, []).append(line_no)diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.pyindex 0f85e85eda1..9338c6b7dc7 100644--- a/scripts/code_health/py_rules.py+++ b/scripts/code_health/py_rules.py@@ -39,6 +39,50 @@ class Ctx:known_env: set[str] = field(default_factory=set)+def canonical_tree(tree: ast.Module) -> ast.Module:+ """``tree`` with every import-bound name spelled out: ``sp.run`` -> ``subprocess.run``,+ ``execute`` (``from subprocess import run as execute``) -> ``subprocess.run``.++ Rules then match canonical API names, so an alias neither hides a call nor lets a local+ helper that merely shares a leaf name (``def wait_for``) pass as the real API. A name the+ module also rebinds (def, class, assignment, parameter) is left alone: it is ambiguous.+ """+ bound: dict[str, str] = {}+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.asname:+ bound[alias.asname] = alias.name+ else:+ top = alias.name.split(".")[0]+ bound[top] = top+ elif isinstance(node, ast.ImportFrom):+ # A relative import keeps its module path minus the dots: rules match the leaf.+ for alias in node.names:+ if alias.name != "*":+ target = f"{node.module}.{alias.name}" if node.module else alias.name+ bound[alias.asname or alias.name] = target+ rebound = {+ n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and not isinstance(n.ctx, ast.Load)+ } | {n.arg for n in ast.walk(tree) if isinstance(n, ast.arg)} | {+ n.name for n in ast.walk(tree) if isinstance(n, (*_FUNCS, ast.ClassDef))+ }+ names = {k: v for k, v in bound.items() if k not in rebound and k != v}++ class _Spell(ast.NodeTransformer):+ def visit_Name(self, node: ast.Name) -> ast.AST:+ target = names.get(node.id)+ if target is None or not isinstance(node.ctx, ast.Load):+ return node+ parts = target.split(".")+ expr: ast.expr = ast.Name(parts[0], ast.Load())+ for part in parts[1:]:+ expr = ast.Attribute(expr, part, ast.Load())+ return ast.copy_location(expr, node)++ return ast.fix_missing_locations(_Spell().visit(tree)) if names else tree++def _dotted(node: ast.AST) -> str:"""``os.environ.get`` for an Attribute chain, ``""`` for anything else."""parts: list[str] = []@@ -86,6 +130,28 @@ def _env_read_name(node: ast.AST) -> str | None:return None+def _env_write_names(node: ast.AST) -> list[str]:+ """Env var names a node SETS: ``os.environ["X"] = ...``, ``setdefault``, ``update``, ``putenv``."""+ if isinstance(node, ast.Subscript) and not isinstance(node.ctx, ast.Load):+ key = node.slice+ if _dotted(node.value) == "os.environ" and isinstance(key, ast.Constant) and isinstance(key.value, str):+ return [key.value]+ return []+ if not isinstance(node, ast.Call):+ return []+ name = _call_name(node)+ if name in ("os.environ.setdefault", "os.putenv"):+ key = _str_arg(node)+ return [key] if key else []+ if name == "os.environ.update":+ keys = [kw.arg for kw in node.keywords if kw.arg]+ for arg in node.args:+ if isinstance(arg, ast.Dict):+ keys += [k.value for k in arg.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)]+ return keys+ return []++def _deferred_parts(node: ast.AST) -> list[ast.AST] | None:"""For a node whose evaluation defers part of itself, the parts that run NOW; else None.@@ -136,9 +202,11 @@ def hardcoded_home(tree: ast.Module, ctx: Ctx) -> Iterable[int]:def new_env_var(tree: ast.Module, ctx: Ctx) -> Iterable[int]:+ # Setting a variable introduces it as surely as reading one does.for node in ast.walk(tree):- name = _env_read_name(node)- if name and name.startswith("HERMES_") and name not in ctx.known_env:+ read = _env_read_name(node)+ names = [read] if read else _env_write_names(node)+ if any(n.startswith("HERMES_") and n not in ctx.known_env for n in names):yield getattr(node, "lineno", 0)@@ -249,9 +317,23 @@ def import_time_capture(tree: ast.Module, ctx: Ctx) -> Iterable[int]:yield from _capture_lines(expr)+_INFINITE = {"inf", "+inf", "infinity", "+infinity"}++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)+ """A deadline that is present and not statically disabled: ``None``, ``math.inf``,+ ``float("inf")`` and an overflowing literal all wait forever. An unknown expression is+ trusted (it is usually a configured value)."""+ if node is None:+ return False+ if isinstance(node, ast.Constant):+ return node.value is not None and node.value != float("inf")+ if _dotted(node).rpartition(".")[2] == "inf":+ return False+ if isinstance(node, ast.Call) and _call_name(node) == "float":+ arg = _str_arg(node)+ return arg is None or arg.strip().lower() not in _INFINITE+ return Truedef _deadline(call: ast.Call, name: str = "timeout", position: int | None = None) -> bool:@@ -279,12 +361,28 @@ def _awaited_calls(body: list[ast.stmt]) -> Iterator[ast.Call]:yield node.value+_WAIT_FOR = {"asyncio.wait_for"}+# deadline context manager -> its deadline parameter (positional slot 0)+_TIMEOUT_CMS = {+ "asyncio.timeout": "delay",+ "asyncio.timeout_at": "when",+ "async_timeout.timeout": "delay",+ "async_timeout.timeout_at": "deadline",+}+_SPAWNS = {+ "subprocess.Popen": "sync",+ "asyncio.create_subprocess_exec": "async",+ "asyncio.create_subprocess_shell": "async",+}++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>):``."""+ """ids of calls an asyncio deadline bounds: the awaitable passed to ``asyncio.wait_for(x,+ <finite>)`` and every call awaited directly inside ``async with asyncio.timeout(<finite>):``.+ Only the real APIs count (names are canonical); a same-named local helper bounds nothing."""bounded: set[int] = set()for node in ast.walk(tree):- if isinstance(node, ast.Call) and _call_name(node).rpartition(".")[2] == "wait_for":+ if isinstance(node, ast.Call) and _call_name(node) in _WAIT_FOR:awaitable = node.args[0] if node.args else next((kw.value for kw in node.keywords if kw.arg in ("fut", "aw")), None)if awaitable is not None and _deadline(node, "timeout", 1):@@ -294,15 +392,44 @@ def _bounded_calls(tree: ast.Module) -> set[int]:ctx_call = item.context_exprif not isinstance(ctx_call, ast.Call):continue- leaf = _call_name(ctx_call).rpartition(".")[2]- slot = {"timeout": "delay", "timeout_at": "when"}.get(leaf)+ slot = _TIMEOUT_CMS.get(_call_name(ctx_call))if slot and _deadline(ctx_call, slot, 0):bounded.update(id(call) for call in _awaited_calls(node.body))return bounded+def _spawn_kind(value: ast.AST | None) -> str | None:+ if isinstance(value, ast.Await):+ value = value.value+ return _SPAWNS.get(_call_name(value)) if isinstance(value, ast.Call) else None+++def _process_handles(tree: ast.Module) -> dict[str, str]:+ """Dotted names that hold a child process (``proc``, ``self._proc``) -> ``sync``/``async``."""+ handles: dict[str, str] = {}+ for node in ast.walk(tree):+ pairs: list[tuple[ast.AST, ast.AST | None]] = []+ if isinstance(node, ast.Assign):+ pairs = [(t, node.value) for t in node.targets]+ elif isinstance(node, (ast.AnnAssign, ast.NamedExpr)):+ pairs = [(node.target, node.value)]+ elif isinstance(node, (ast.With, ast.AsyncWith)):+ pairs = [(i.optional_vars, i.context_expr) for i in node.items if i.optional_vars]+ for target, value in pairs:+ kind = _spawn_kind(value)+ if kind and _dotted(target):+ handles[_dotted(target)] = kind+ return handles+++# Process methods that wait for the child, with the slot of their ``timeout`` (sync Popen);+# the asyncio Process versions take no timeout and must be bounded by asyncio.+_PROCESS_WAITS = {"communicate": 1, "wait": 0}++def missing_timeout(tree: ast.Module, ctx: Ctx) -> Iterable[int]:bounded = _bounded_calls(tree)+ handles = _process_handles(tree)for node in ast.walk(tree):if not isinstance(node, ast.Call) or id(node) in bounded:continue@@ -311,8 +438,9 @@ def missing_timeout(tree: ast.Module, ctx: Ctx) -> Iterable[int]:yield node.linenoelif leaf == "urlopen" and not _deadline(node, "timeout", 2):yield node.lineno- elif leaf == "communicate" and head and not _deadline(node, "timeout", 1):- yield node.lineno+ elif leaf in _PROCESS_WAITS and head in handles:+ if handles[head] == "async" or not _deadline(node, "timeout", _PROCESS_WAITS[leaf]):+ yield node.linenodef sync_config_in_async(tree: ast.Module, ctx: Ctx) -> Iterable[int]:@@ -332,33 +460,72 @@ def get_event_loop(tree: ast.Module, ctx: Ctx) -> Iterable[int]:yield node.lineno-def _gathers_exceptions(func: ast.AST) -> bool:- for node in ast.walk(func):- if isinstance(node, ast.Call) and _call_name(node).endswith("gather"):- for kw in node.keywords:- if kw.arg == "return_exceptions" and getattr(kw.value, "value", False) is True:- return True+def _is_exc_gather(node: ast.AST | None) -> bool:+ if isinstance(node, ast.Await):+ node = node.value+ if not (isinstance(node, ast.Call) and _call_name(node) == "asyncio.gather"):+ return False+ return any(kw.arg == "return_exceptions" and getattr(kw.value, "value", False) is True+ for kw in node.keywords)+++def _names(target: ast.AST) -> set[str]:+ return {n.id for n in ast.walk(target) if isinstance(n, ast.Name)}+++def _from_results(node: ast.AST | None, results: set[str]) -> bool:+ """``node`` is a gather-with-exceptions call, a results name, or built from one+ (``results[i]``, ``zip(xs, results)``, ``enumerate(results)``)."""+ if node is None:+ return False+ if _is_exc_gather(node):+ return True+ if isinstance(node, ast.Name):+ return node.id in results+ if isinstance(node, ast.Subscript):+ return _from_results(node.value, results)+ if isinstance(node, ast.Call) and _call_name(node) in ("zip", "enumerate", "list", "reversed"):+ return any(_from_results(arg, results) for arg in node.args)return False+def _result_names(func: ast.AST) -> set[str]:+ """Names bound to gather(return_exceptions=True) results in ``func``'s own body."""+ results: set[str] = set()+ nodes = [n for stmt in func.body for n in _eager(stmt)]+ for _ in range(3): # results -> loop vars -> unpacked loop vars+ for node in nodes:+ if isinstance(node, ast.Assign) and _from_results(node.value, results):+ results |= set().union(*(_names(t) for t in node.targets))+ elif isinstance(node, (ast.For, ast.AsyncFor, ast.comprehension)) and _from_results(node.iter, results):+ results |= _names(node.target)+ return results++def gather_exception_check(tree: ast.Module, ctx: Ctx) -> Iterable[int]:for func in ast.walk(tree):- if not isinstance(func, _FUNCS) or not _gathers_exceptions(func):+ if not isinstance(func, _FUNCS):continue- for node in ast.walk(func):- if (- isinstance(node, ast.Call)- and _call_name(node) == "isinstance"- and len(node.args) == 2- and _dotted(node.args[1]) == "Exception"- ):- yield node.lineno+ results = _result_names(func)+ if not results:+ continue+ for stmt in func.body:+ for node in _eager(stmt):+ if (+ isinstance(node, ast.Call)+ and _call_name(node) == "isinstance"+ and len(node.args) == 2+ and _dotted(node.args[1]) == "Exception"+ and _from_results(node.args[0], results)+ ):+ yield node.linenodef bool_of_env(tree: ast.Module, ctx: Ctx) -> Iterable[int]:for node in ast.walk(tree):if isinstance(node, ast.Call) and _call_name(node) == "bool" and len(node.args) == 1:- if isinstance(node.args[0], ast.Call) and _env_read_name(node.args[0]):+ arg = node.args[0]+ if isinstance(arg, (ast.Call, ast.Subscript)) and _env_read_name(arg):yield node.lineno@@ -391,7 +558,7 @@ def elif_ladder(tree: ast.Module, ctx: Ctx) -> Iterable[int]:def raw_thread(tree: ast.Module, ctx: Ctx) -> Iterable[int]:for node in ast.walk(tree):- if isinstance(node, ast.Call) and _call_name(node) in ("threading.Thread", "Thread"):+ if isinstance(node, ast.Call) and _call_name(node) == "threading.Thread":yield node.linenodiff --git a/scripts/code_health/py_structure.py b/scripts/code_health/py_structure.pyindex b228a934acc..db4efbf1af4 100644--- a/scripts/code_health/py_structure.py+++ b/scripts/code_health/py_structure.py@@ -55,13 +55,28 @@ def nesting_depth(stmts: list[ast.stmt], depth: int = 0) -> int:def body_hash(node: ast.AST) -> str:- """Name-independent hash, so a function moved or renamed unchanged keeps its cap."""- dumped = ast.dump(node, annotate_fields=False)+ """Name-independent hash, so a function moved or renamed unchanged keeps its cap.++ The declared name is dropped, and so are the body's references to it (``name(...)``,+ ``self.name(...)``, ``cls.name(...)``), unless the body rebinds that name itself: a+ recursive function renamed together with its self-call is still the same code.+ """name = getattr(node, "name", "")- dumped = dumped.replace(repr(name), "''", 1)+ dumped = ast.dump(node, annotate_fields=False).replace(repr(name), "''", 1)+ if name and f"Name({name!r}, Store())" not in dumped and f"arg({name!r}" not in dumped:+ dumped = dumped.replace(f"Name({name!r}, Load())", "Name('', Load())")+ for receiver in ("self", "cls"):+ dumped = dumped.replace(f"Attribute(Name({receiver!r}, Load()), {name!r}, Load())",+ f"Attribute(Name({receiver!r}, Load()), '', Load())")return hashlib.sha1(dumped.encode("utf-8")).hexdigest()[:16]+def _first_line(node: ast.AST) -> int:+ """A def/class starts at its first decorator: decorator code belongs to it (and moves+ with it), not to the module."""+ return min([node.lineno, *(d.lineno for d in getattr(node, "decorator_list", []))])++class _UnitCollector(ast.NodeVisitor):def __init__(self) -> None:self.stack: list[str] = []@@ -84,7 +99,11 @@ class _UnitCollector(ast.NodeVisitor):def visit_ClassDef(self, node: ast.ClassDef) -> None:qual = self._qualname(node.name)- self.spans.append(Span(node.lineno, node.end_lineno or node.lineno, qual))+ # A class has no size metrics of its own, but it is a unit so that a renamed or moved+ # class keeps the violations in its body (decorators, attributes) one-to-one.+ self.units[qual] = Unit(qualname=qual, line=node.lineno, metrics={},+ body_hash=body_hash(node), parent=self.funcs[-1] if self.funcs else None)+ self.spans.append(Span(_first_line(node), node.end_lineno or node.lineno, qual))self.stack.append(qual.rsplit(".", 1)[-1])self.generic_visit(node)self.stack.pop()@@ -92,7 +111,7 @@ class _UnitCollector(ast.NodeVisitor):def _visit_func(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:qual = self._qualname(node.name)end = node.end_lineno or node.lineno- first = min([node.lineno, *(d.lineno for d in node.decorator_list)])+ first = _first_line(node)self.total_lines[qual] = end - first + 1self.units[qual] = Unit(qualname=qual,@@ -101,7 +120,7 @@ class _UnitCollector(ast.NodeVisitor):body_hash=body_hash(node),parent=self.funcs[-1] if self.funcs else None,)- self.spans.append(Span(node.lineno, end, qual))+ self.spans.append(Span(first, end, qual))self.stack.append(qual.rsplit(".", 1)[-1])self.funcs.append(qual)self.generic_visit(node)@@ -136,7 +155,7 @@ def measure_structure(fm: FileMeasure, tree: ast.Module) -> ScopeIndex:# FUNC_LINES is a function's OWN lines: a nested def is its own unit, so editing a closure# never counts against the function that encloses it.for unit in collector.units.values():- if unit.parent is not None:+ if unit.parent is not None and unit.qualname in collector.total_lines:parent = collector.units[unit.parent]parent.metrics["FUNC_LINES"] -= collector.total_lines[unit.qualname]fm.units = collector.unitsdiff --git a/scripts/code_health/report.py b/scripts/code_health/report.pyindex 469976478c0..5afad1fedb0 100644--- a/scripts/code_health/report.py+++ b/scripts/code_health/report.py@@ -12,10 +12,13 @@ _ALLOW = re.compile(r"health:\s*allow\s+([A-Za-z0-9_,\- ]+?)\s*(?:--|—|:)\s*(\_ALLOW_BARE = re.compile(r"health:\s*allow\b")-def _allow_lines(finding: Finding) -> list[int]:+def _allow_lines(finding: Finding, fm: FileMeasure) -> list[int]:+ """Where an allow for this finding may sit: its own line, or a comment-only line right+ above it. A trailing allow on the previous statement waives only that statement."""if finding.rule == "FILE_LINES":return list(range(1, 6))- return [finding.line, finding.line - 1]+ above = finding.line - 1+ return [finding.line, above] if not fm.code_line(above) else [finding.line]def apply_allows(findings: list[Finding], head: dict[str, FileMeasure]) -> None:@@ -27,7 +30,7 @@ def apply_allows(findings: list[Finding], head: dict[str, FileMeasure]) -> None:fm = head.get(finding.path)if fm is None:continue- for line_no in _allow_lines(finding):+ for line_no in _allow_lines(finding, fm):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(",")}:diff --git a/scripts/code_health/ruff_runner.py b/scripts/code_health/ruff_runner.pyindex b53048dda6e..445af2c3bfd 100644--- a/scripts/code_health/ruff_runner.py+++ b/scripts/code_health/ruff_runner.py@@ -25,6 +25,8 @@ _CHUNK = 400class RuffFile:cc_by_line: dict[int, int] = field(default_factory=dict)hits: list[tuple[str, int]] = field(default_factory=list)+ # Ruff could not parse the file (code-less diagnostics): its CC and hits are missing.+ errors: list[str] = field(default_factory=list)def pinned_version(repo: Path) -> str:@@ -99,3 +101,5 @@ def _record(results: dict[str, RuffFile], root: Path, diag: dict) -> None:entry.cc_by_line[row] = int(match.group(1))elif code:entry.hits.append((code, row))+ else:+ entry.errors.append(f"line {row}: {diag.get('message', 'syntax error')}")diff --git a/scripts/code_health/ts_units.mjs b/scripts/code_health/ts_units.mjsindex b5552447268..4aa9eced4c4 100644--- a/scripts/code_health/ts_units.mjs+++ b/scripts/code_health/ts_units.mjs@@ -91,6 +91,37 @@ function ownName(node) {return bindingName(node)}+// The body's text with its own references to `name` removed (`name(...)`, `this.name(...)`),+// unless the body rebinds that name: renaming a recursive function together with its+// self-call is still the same code. Strings and other objects' `.name` members are untouched.+function bodyWithoutSelf(node, sf, name) {+ if (!node.body) return ''+ const start = node.body.getStart(sf)+ let text = node.body.getText(sf)+ if (!name) return text+ const cuts = []+ let rebound = node.parameters.some(p => ts.isIdentifier(p.name) && p.name.text === name)+ const visit = n => {+ const declares = ts.isVariableDeclaration(n) || ts.isParameter(n) ||+ ts.isFunctionDeclaration(n) || ts.isClassDeclaration(n)+ if (declares && n.name && ts.isIdentifier(n.name) && n.name.text === name) rebound = true+ if (ts.isIdentifier(n) && n.text === name) {+ const p = n.parent+ const member = p && ts.isPropertyAccessExpression(p) && p.name === n+ const key = p && (ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p) ||+ ts.isPropertyDeclaration(p)) && p.name === n+ if ((!member && !key) || (member && p.expression.kind === K.ThisKeyword)) {+ cuts.push(n.getStart(sf) - start)+ }+ }+ ts.forEachChild(n, visit)+ }+ visit(node.body)+ if (rebound) return text+ for (const at of cuts.sort((a, b) => b - a)) text = text.slice(0, at) + text.slice(at + name.length)+ return text+}+// Comment trivia (not string or template text) that carries a `health: allow` directive.function allowComments(sf, text) {const found = new Map()@@ -138,7 +169,8 @@ function measureFile(path) {const end = sf.getLineAndCharacterOfPosition(node.getEnd()).line + 1// Name-independent: parameters + body only, so a rename (or a move) keeps the cap.const params = node.parameters.map(p => p.getText(sf)).join(',')- const body = (params + '=>' + (node.body ? node.body.getText(sf) : '')).replace(/\s+/g, ' ')+ const selfName = propertyName(node.name) ?? bindingName(node)+ const body = (params + '=>' + bodyWithoutSelf(node, sf, selfName)).replace(/\s+/g, ' ')const unit = {q: qual, line: start, cc: complexity(node), nesting: nesting(node),hash: createHash('sha1').update(body).digest('hex').slice(0, 16)diff --git a/tests/scripts/test_code_health.py b/tests/scripts/test_code_health.pyindex 13c580a1953..8ee8cb4a7ca 100644--- a/tests/scripts/test_code_health.py+++ b/tests/scripts/test_code_health.py@@ -82,7 +82,8 @@ def test_moved_code_keeps_its_cap(tmp_path, capsys):_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"+_PROC = "import asyncio\n\n\nasync def f(cmd):\n proc = await asyncio.create_subprocess_exec(*cmd)\n{}\n"+_TWO_RUNS = "import subprocess\n\n\ndef f(a, b):\n subprocess.run(a){}\n subprocess.run(b){}\n"_ENV = "import os\n\n{}\n"_EXCEPT = " try:\n pass\n except Exception:\n pass\n"@@ -115,6 +116,32 @@ _STUB = {"pkg/b.py": "def legacy(x):\n return x\n"}({}, {"pkg/p.py": _PROC.format(" return await asyncio.wait_for(fut=proc.communicate(), timeout=1)")}, False),# a BOM reads the same from git and from disk, so a new BOM file's debt is still measured({}, {"pkg/bom.py": "\ufeff" + _LEGACY}, True),+ # rules see through import aliases and require the real asyncio deadline API+ ({}, {"pkg/c.py": "from subprocess import run as execute\n\n\ndef f(c):\n return execute(c)\n"}, True),+ ({}, {"pkg/c.py": "def run(c):\n return c\n\n\ndef f(c):\n return run(c)\n"}, False),+ ({}, {"pkg/p.py": "async def wait_for(aw, t):\n return await aw\n\n\n"+ + _PROC.format(" return await wait_for(proc.communicate(), 1)")}, True),+ ({}, {"pkg/c.py": "def f(client):\n return client.communicate()\n"}, False),+ ({}, {"pkg/p.py": _PROC.format(" return await asyncio.wait_for(proc.wait(), float('inf'))")}, True),+ # writes introduce a HERMES_* name too; bool() of a raw env string is HX010+ ({}, {"pkg/c.py": _ENV.format("os.environ['HERMES_BRAND_NEW'] = '1'")}, True),+ ({}, {"pkg/c.py": _ENV.format("FLAG = bool(os.environ['PATH'])")}, True),+ # an inline allow covers its own line only; removing an allow keeps the debt existing+ ({}, {"pkg/p.py": _TWO_RUNS.format(" # health: allow HX006 -- x", "")}, True),+ ({"pkg/p.py": _TWO_RUNS.format(" # health: allow HX006 -- x", " # health: allow HX006 -- y")},+ {"pkg/p.py": _TWO_RUNS.format("", "")}, False),+ # an identical violation moved past unrelated code is a new occurrence+ ({"pkg/a.py": _LEGACY + "\n\n" + _SWALLOW.replace("pass\n except", "a()\n except")+ + " b()\n c()\n d()\n"},+ {"pkg/a.py": _LEGACY + "\n\n" + "def other():\n a()\n b()\n c()\n d()\n"+ " try:\n pass\n except Exception:\n pass\n"}, True),+ # a recursive function renamed with its self-calls keeps its cap+ ({}, {"pkg/a.py": (_LEGACY + " return legacy(x - 1)\n").replace("legacy", "walk") + "\n\n" + _SWALLOW}, True),+ ({"pkg/a.py": _LEGACY + " return legacy(x - 1)\n\n\n" + _SWALLOW},+ {"pkg/a.py": (_LEGACY + " return legacy(x - 1)\n").replace("legacy", "walk") + "\n\n" + _SWALLOW}, False),+ # an over-cap file may not grow, and an unparseable file never passes+ ({"pkg/big.py": "V = 0\n" * 2001}, {"pkg/big.py": "V = 0\n" * 2002}, True),+ ({}, {"pkg/c.py": "def f(:\n pass\n"}, True),])def test_verdicts_follow_ownership_deadlines_and_import_execution(tmp_path, capsys, extra_base, files, blocks):repo, base = _repo(tmp_path)