The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(code-health): execution-scope-aware rule walks; BOM-stable git reads
teknium1f22ed1af5fe8
diff --git a/scripts/code_health/gitio.py b/scripts/code_health/gitio.pyindex afb8f83afb2..8175514b5c3 100644--- a/scripts/code_health/gitio.py+++ b/scripts/code_health/gitio.py@@ -106,7 +106,8 @@ def read_file(repo: Path, tree: str | None, path: str) -> str | None:)if proc.returncode != 0:return None- return proc.stdout.decode("utf-8", errors="replace")+ # Same decoding as the working-tree read: a BOM must not make the two sides disagree.+ return proc.stdout.decode("utf-8-sig", errors="replace")def tracked_files(repo: Path, tree: str | None) -> list[str]:diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.pyindex b09a2cd0961..0f85e85eda1 100644--- a/scripts/code_health/py_rules.py+++ b/scripts/code_health/py_rules.py@@ -86,15 +86,34 @@ def _env_read_name(node: ast.AST) -> str | None:return None-def _walk_skipping(node: ast.AST, skip: tuple[type, ...]) -> Iterator[ast.AST]:- """``ast.walk`` that does not descend into ``skip`` node types (except the root)."""+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.++ A lambda/def runs only its defaults and decorators when evaluated; a generator expression+ runs only its first iterable (the element, conditions and later loops run on consumption).+ Comprehensions and class bodies run immediately, so they are not deferred.+ """+ if isinstance(node, ast.Lambda):+ return [d for d in (*node.args.defaults, *node.args.kw_defaults) if d is not None]+ if isinstance(node, _FUNCS):+ defaults = [d for d in (*node.args.defaults, *node.args.kw_defaults) if d is not None]+ return [*node.decorator_list, *defaults]+ if isinstance(node, ast.GeneratorExp):+ return [node.generators[0].iter]+ return None+++def _eager(node: ast.AST) -> Iterator[ast.AST]:+ """Every node evaluated when ``node`` is evaluated (or a statement executes), root included."""stack = [node]while stack:current = stack.pop()+ parts = _deferred_parts(current)+ if parts is not None:+ stack.extend(parts)+ continueyield current- for child in ast.iter_child_nodes(current):- if not isinstance(child, skip):- stack.append(child)+ stack.extend(ast.iter_child_nodes(current))def hardcoded_home(tree: ast.Module, ctx: Ctx) -> Iterable[int]:@@ -150,9 +169,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)):+ # Deferred bodies (lambda, def, generator element) read at call time: that is the fix.+ for node in _eager(expr):if isinstance(node, ast.Call):name = _call_name(node)leaf = name.rsplit(".", 1)[-1]@@ -206,19 +224,23 @@ def _import_time_statements(body: list[ast.stmt]) -> Iterator[ast.stmt]: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+ """What a statement evaluates at import, besides its nested blocks (walked separately)."""+ if isinstance(stmt, ast.ClassDef):+ yield from (*stmt.decorator_list, *stmt.bases, *(kw.value for kw in stmt.keywords))+ elif isinstance(stmt, (ast.Assign, ast.AnnAssign, ast.AugAssign, *_FUNCS)):+ yield stmt # _eager keeps only a def's decorators and defaults+ elif isinstance(stmt, ast.Expr):+ # A bare call is an action, not a capture; a walrus inside it binds a module name.+ yield from (n for n in _eager(stmt.value) if isinstance(n, ast.NamedExpr))+ elif isinstance(stmt, (ast.If, ast.While)):+ yield stmt.test+ elif isinstance(stmt, ast.For):+ yield stmt.iter+ elif isinstance(stmt, ast.With):+ yield from (item.context_expr for item in stmt.items)elif isinstance(stmt, ast.Match):yield stmt.subject+ yield from (case.guard for case in stmt.cases if case.guard is not None)def import_time_capture(tree: ast.Module, ctx: Ctx) -> Iterable[int]:@@ -250,8 +272,9 @@ def _deadline(call: ast.Call, name: str = "timeout", position: int | None = Nonedef _awaited_calls(body: list[ast.stmt]) -> Iterator[ast.Call]:+ """Calls awaited while ``body`` runs; a coroutine defined there runs later, unbounded."""for stmt in body:- for node in _walk_skipping(stmt, (ast.Lambda, *_FUNCS)):+ for node in _eager(stmt):if isinstance(node, ast.Await) and isinstance(node.value, ast.Call):yield node.value@@ -262,8 +285,10 @@ def _bounded_calls(tree: ast.Module) -> set[int]:bounded: set[int] = set()for node in ast.walk(tree):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]))+ 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):+ bounded.add(id(awaitable))elif isinstance(node, ast.AsyncWith):for item in node.items:ctx_call = item.context_expr@@ -295,7 +320,7 @@ def sync_config_in_async(tree: ast.Module, ctx: Ctx) -> Iterable[int]:if not isinstance(func, ast.AsyncFunctionDef):continuefor stmt in func.body:- for node in _walk_skipping(stmt, (ast.Lambda, *_FUNCS)):+ for node in _eager(stmt):if isinstance(node, ast.Call):if _call_name(node).rsplit(".", 1)[-1] in _SYNC_CONFIG_CALLS:yield node.linenodiff --git a/tests/scripts/test_code_health.py b/tests/scripts/test_code_health.pyindex bf371fa02d5..13c580a1953 100644--- a/tests/scripts/test_code_health.py+++ b/tests/scripts/test_code_health.py@@ -106,6 +106,15 @@ _STUB = {"pkg/b.py": "def legacy(x):\n return x\n"}({}, {"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+ ({}, {"pkg/c.py": _ENV.format("current = lambda p=os.getenv('PATH'): p")}, True), # eager default+ ({}, {"pkg/c.py": _ENV.format("with open(os.getenv('PATH', 'x'), encoding='utf-8') as fh:\n pass")}, True),+ ({}, {"pkg/c.py": _ENV.format("current = (os.getenv('PATH') for _ in range(1))")}, False),+ # a coroutine defined inside the deadline runs after it, so it is not bounded by it+ ({}, {"pkg/p.py": _PROC.format(" async with asyncio.timeout(1):\n async def later():\n"+ " return await proc.communicate()\n return later")}, True),+ ({}, {"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),])def test_verdicts_follow_ownership_deadlines_and_import_execution(tmp_path, capsys, extra_base, files, blocks):repo, base = _repo(tmp_path)