The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(code-health): hits follow proven moves only; stable TS identity; show advisories
teknium1add45e775ec3
diff --git a/AGENTS.md b/AGENTS.mdindex 118185946f0..a8e50ad377e 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. Split along `<stem>_<topic>` first, in its own commit; behaviour goes in a sibling,+ 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,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 4d1bd3166b9..78e2fe97f96 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. 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). 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`.### Fail loud at integration boundariesdiff --git a/scripts/check b/scripts/checkindex a81d4c23de1..97de6528d9b 100755--- a/scripts/check+++ b/scripts/check@@ -93,8 +93,12 @@ def main(argv: list[str] | None = None) -> int: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]- for name in failed:- print(f"\n=== {name} (failed) ===\n{results[name][1]}")+ # A passing health run still carries advisories and comment-allowed findings that the+ # reviewer must see, so its report is always shown.+ for name, (code, output) in results.items():+ if code != 0 or name == "health":+ label = "failed" if code != 0 else "ok"+ print(f"\n=== {name} ({label}) ===\n{output.rstrip()}")status = "FAILED: " + ", ".join(failed) if failed else "ok"print(f"\nscripts/check: {len(results)} checks, {status}")return 1 if failed else 0diff --git a/scripts/code_health/compare.py b/scripts/code_health/compare.pyindex a03100e41e5..c3e2cafd0d7 100644--- a/scripts/code_health/compare.py+++ b/scripts/code_health/compare.py@@ -4,9 +4,11 @@ Every unit has its own cap: a function or file already over target may not growit has on the base revision; anything new must meet the target. Pattern rules compare multisetsof fingerprints per file, so fixing one violation and adding another still fails.-Code that moves keeps its cap and its existing violations, matched by content: a function by-its name-independent body hash, a pattern hit by (rule, line text) once its enclosing function-has vanished from the old place. Nothing else crosses units.+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."""from __future__ import annotations@@ -18,44 +20,49 @@ from scripts.code_health.config import ADVISORY_GROWTH, RULES_BY_ID, TARGETSfrom scripts.code_health.gitio import Changefrom 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 _Pool:- """Units and hits that disappeared from their base location in this diff."""+class _Moved:+ """Base units absent from their own file at head: candidates for a cross-file move."""- units: dict[str, list[Unit]] = field(default_factory=lambda: defaultdict(list))- hits: Counter[tuple[str, str]] = field(default_factory=Counter)+ units: dict[str, list[tuple[str, Unit]]] = field(default_factory=lambda: defaultdict(list))- def take_unit(self, body_hash: str) -> Unit | None:+ def take(self, body_hash: str) -> tuple[str, Unit] | None:bucket = self.units.get(body_hash)return bucket.pop() if bucket else None- def take_hit(self, rule: str, text: str) -> bool:- key = (rule, text)- if self.hits[key] > 0:- self.hits[key] -= 1- return True- return False--def _build_pool(base: dict[str, FileMeasure], head: dict[str, FileMeasure],- head_of: dict[str, str | None]) -> _Pool:- pool = _Pool()+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 = set(hf.units) if hf else set()- for qual, unit in bf.units.items():- if qual not in live:- pool.units[unit.body_hash].append(unit)- for hit, count in bf.hits.items():- gone = hf is None or (hit.scope != MODULE_SCOPE and hit.scope not in live)- if gone:- pool.hits[(hit.rule, hit.text)] += count- return pool---def _metric_findings(path: str, hf: FileMeasure, bf: FileMeasure | None, pool: _Pool) -> list[Finding]:+ 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]]:findings: list[Finding] = []lines = hf.metrics.get("FILE_LINES", 0)if lines > TARGETS["FILE_LINES"]:@@ -66,10 +73,12 @@ def _metric_findings(path: str, hf: FileMeasure, bf: FileMeasure | None, pool: _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():- prior = bf.units.get(qual) if bf else None- if prior is None:- prior = pool.take_unit(unit.body_hash)+ matched = _prior(qual, unit, bpath, bf, moved)+ prior = matched[0] if matched else None+ if matched:+ origins[qual] = matched[1]for metric, value in unit.metrics.items():target = TARGETS[metric]if value <= target:@@ -79,7 +88,7 @@ def _metric_findings(path: str, hf: FileMeasure, bf: FileMeasure | None, pool: _if value > cap:findings.append(Finding(path, metric, qual, unit.line,_detail(value, target, was, metric)))- return findings+ return findings, originsdef _detail(value: int, target: int, was: int | None, what: str) -> str:@@ -90,13 +99,24 @@ 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 _hit_findings(path: str, hf: FileMeasure, bf: FileMeasure | None, pool: _Pool) -> list[Finding]:+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 _hit_findings(path: str, hf: FileMeasure, base_hits: Counter[Hit]) -> list[Finding]:findings: list[Finding] = []- base_hits: Counter[Hit] = bf.hits if bf else Counter()for hit, count in sorted(hf.hits.items(), key=lambda kv: hf.hit_lines[kv[0]][0]):extra = count - base_hits.get(hit, 0)- while extra > 0 and pool.take_hit(hit.rule, hit.text):- extra -= 1if extra <= 0:continuerule = RULES_BY_ID[hit.rule]@@ -110,12 +130,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}- pool = _build_pool(base, head, head_of)+ moved = _vanished(base, head, head_of)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- findings += _metric_findings(path, hf, bf, pool)- findings += _hit_findings(path, hf, bf, pool)+ metric, origins = _metric_findings(path, hf, bpath, bf, moved)+ findings += metric+ findings += _hit_findings(path, hf, _base_hits(path, bf, origins, base))return findingsdiff --git a/scripts/code_health/config.py b/scripts/code_health/config.pyindex 115549046ae..ba7b95f9919 100644--- a/scripts/code_health/config.py+++ b/scripts/code_health/config.py@@ -74,8 +74,9 @@ RULES: tuple[Rule, ...] = (Rule("ASYNC240", "blocking path call in async def", "`await asyncio.to_thread(...)`","ruff"),Rule("S113", "HTTP request without timeout", "pass `timeout=`", "ruff"),- Rule("HX006", "subprocess/urlopen without timeout", "pass `timeout=` (a child or socket"- " that never answers hangs this thread forever)", "ast"),+ Rule("HX006", "subprocess/urlopen without timeout", "pass `timeout=`; an asyncio"+ " `proc.communicate()` goes inside `asyncio.wait_for(..., timeout=...)` (a child or"+ " socket that never answers hangs forever)", "ast"),Rule("HX007", "sync config I/O inside async def", "`await asyncio.to_thread(load_config)`"" or read it before entering the event loop", "ast"),Rule("HX008", "asyncio.get_event_loop()", "`asyncio.get_running_loop()` inside a"diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.pyindex 95bbc15d4f0..e2e0b0d3300 100644--- a/scripts/code_health/py_rules.py+++ b/scripts/code_health/py_rules.py@@ -195,9 +195,19 @@ def import_time_capture(tree: ast.Module, ctx: Ctx) -> Iterable[int]:yield from _capture_lines(default)+def _bounded_by_wait_for(tree: ast.Module) -> set[int]:+ """ids of calls passed to ``asyncio.wait_for``/``timeout`` (already bounded by the wrapper)."""+ 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)+ return bounded++def missing_timeout(tree: ast.Module, ctx: Ctx) -> Iterable[int]:+ bounded = _bounded_by_wait_for(tree)for node in ast.walk(tree):- if not isinstance(node, ast.Call) or _has_kw(node, "timeout"):+ if not isinstance(node, ast.Call) or _has_kw(node, "timeout") or id(node) in bounded:continuename = _call_name(node)head, _, leaf = name.rpartition(".")diff --git a/scripts/code_health/ts_units.mjs b/scripts/code_health/ts_units.mjsindex caed121c428..f7e75c3adf7 100644--- a/scripts/code_health/ts_units.mjs+++ b/scripts/code_health/ts_units.mjs@@ -113,7 +113,9 @@ function measureFile(path) {const qual = unique([...stack, ownName(node) ?? '<anon>'].join('.'))const start = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1const end = sf.getLineAndCharacterOfPosition(node.getEnd()).line + 1- const body = node.getText(sf).replace(/\s+/g, ' ')+ // 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 unit = {q: qual, line: start, lines: end - start + 1, 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 29fc800252b..40b2568b8c0 100644--- a/tests/scripts/test_code_health.py+++ b/tests/scripts/test_code_health.py@@ -14,8 +14,8 @@ _SWALLOW = "def other():\n try:\n pass\n except Exception:\ndef _git(repo: Path, *args: str) -> str:- return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True,- encoding="utf-8", timeout=60).stdout.strip()+ return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True,+ text=True, encoding="utf-8", timeout=60).stdout.strip()def _commit(repo: Path, files: dict[str, str | None]) -> str:@@ -55,20 +55,25 @@ def test_ratchet_blocks_growth_new_and_swapped_violations(tmp_path, capsys):legacy_plus = _LEGACY + " if x == 99:\n return 99\n"ok = _LEGACY + "\n\n" + _SWALLOW + "\n\ndef added():\n return 1\n"grown = legacy_plus + "\n\n" + _SWALLOW- swapped = _LEGACY + "\n\ndef other():\n return 1\n\n\n" + _SWALLOW.replace("other", "fresh")+ fresh = _SWALLOW.replace("pass\n", "return 2\n", 1).replace("other", "fresh")+ swapped = _LEGACY + "\n\ndef other():\n return 1\n\n\n" + freshassert _verdict(repo, base, {"pkg/a.py": ok}, capsys)[0] == 0 # legacy debt never blockscode, out = _verdict(repo, base, {"pkg/a.py": grown}, capsys)assert code == 1 and "legacy" in out and "CC 23 > 22" in outcode, out = _verdict(repo, base, {"pkg/a.py": swapped}, capsys)assert code == 1 and "BLE001" in out and "fresh" in out # fixing one doesn't buy another+ traded = {"pkg/a.py": _LEGACY, "pkg/b.py": fresh}+ code, out = _verdict(repo, base, traded, capsys)+ assert code == 1 and "fresh" in out # deleting a violation never pays for an unrelated onedef test_moved_code_keeps_its_cap(tmp_path, capsys):repo, base = _repo(tmp_path)- split: dict[str, str | None] = {"pkg/a.py": _SWALLOW, "pkg/a_legacy.py": _LEGACY}- code, out = _verdict(repo, base, split, capsys)- assert code == 0, out+ for split in ({"pkg/a.py": _SWALLOW, "pkg/a_legacy.py": _LEGACY},+ {"pkg/a.py": _LEGACY, "pkg/a_swallow.py": _SWALLOW}): # hits move with their unit+ code, out = _verdict(repo, base, dict(split), capsys)+ assert code == 0, outrenamed: 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