import ast import dataclasses import hashlib from failure import Failure from metric_bench.python_units import FUNCTION, Unit Key = tuple[str, str] @dataclasses.dataclass(frozen=True) class Code: """What the questions' answers rest on: for each measured unit, the names its calls end in, and for each test file, the names its code refers to.""" calls: list[tuple[Key, set[str]]] tests: dict[str, set[str]] @dataclasses.dataclass(frozen=True) class Question: unit: Key text: str truth: frozenset[str] # The rules each answer follows, given to the agent as they are applied here. RULES = """A unit is a module-level function, or a method of a module-level class, in a Python file git tracks outside the tests; a nested function belongs to the unit around it. A test file is a tracked `test_*.py` or `*_test.py`, or a `.py` under a `tests/` folder. A unit calls a name when its body holds a call `name(…)` or `anything.name(…)`. Write a unit as `path:name`, the path from the repository's root and the name without its class.""" def calls(path: str, source: str) -> list[tuple[Key, set[str]]] | Failure: """Each unit in source, with the last name of each call in its body; a method and a function may share a key.""" try: tree = ast.parse(source) except (SyntaxError, ValueError) as failure: return Failure(f"{path} does not parse: {failure}") nodes = [node for node in tree.body if isinstance(node, FUNCTION)] nodes += [method for node in tree.body if isinstance(node, ast.ClassDef) for method in node.body if isinstance(method, FUNCTION)] return [((path, node.name), {name for call in ast.walk(node) if (name := called(call))}) for node in nodes] def called(node: ast.AST) -> str | None: if not isinstance(node, ast.Call): return None if isinstance(node.func, ast.Name): return node.func.id return node.func.attr if isinstance(node.func, ast.Attribute) else None def referred(path: str, source: str) -> set[str] | Failure: """The names a test file's code refers to: names, attributes and imported names, not strings or comments.""" try: tree = ast.parse(source) except (SyntaxError, ValueError) as failure: return Failure(f"{path} does not parse: {failure}") names = set() for node in ast.walk(tree): if isinstance(node, ast.Name): names.add(node.id) elif isinstance(node, ast.Attribute): names.add(node.attr) elif isinstance(node, ast.alias): names.add(node.name.rpartition(".")[2]) return names def askable(code: Code) -> list[Key]: """The units whose name no other unit shares, so a call by that name means that unit; dunder methods, which Python calls implicitly, are left out.""" names = [name for (_, name), _ in code.calls] return sorted(key for key, _ in code.calls if names.count(key[1]) == 1 and not key[1].startswith("__")) def sampled(units: list[Key], named: set[Key], commit: str) -> list[Key]: """Each askable unit the seats named, and as many others, picked by a hash of the commit so a rerun asks the same.""" asked = [unit for unit in units if unit in named] others = sorted((unit for unit in units if unit not in named), key=lambda unit: digest(commit, *unit)) return asked + others[:len(asked)] def questions(code: Code, units: list[Key], commit: str) -> list[Question]: """Three questions on each unit, in an order hashed from the commit, so the named units do not come first.""" defined = {name for (_, name), _ in code.calls} called_by = dict(code.calls) asked = [] for unit in units: path, name = unit asked += [ Question(unit, f"Which units call `{name}`, defined in `{path}`?", frozenset(f"{caller}:{other}" for (caller, other), names in code.calls if name in names)), Question(unit, f"Which unit names does `{path}:{name}` call? Answer each as the bare name.", frozenset(called_by[unit] & defined)), Question(unit, f"Which test files refer to `{name}` in their code, not only in a string or comment?", frozenset(test for test, names in code.tests.items() if name in names)), ] return sorted(asked, key=lambda question: digest(commit, question.text)) def digest(*parts: str) -> str: return hashlib.sha256(" ".join(parts).encode()).hexdigest() def prompt(asked: list[Question]) -> str: listed = "\n".join(f"{number}. {question.text}" for number, question in enumerate(asked, 1)) return f"Answer each question about the code in this repository. {RULES} Answer each question with every item it asks for, and an empty list when there is none; answer question n in the nth entry of `answers`.\n\n{listed}" def answer_schema(count: int) -> dict: answer = {"type": "array", "items": {"type": "string"}} return {"type": "object", "properties": {"answers": {"type": "array", "items": answer, "minItems": count, "maxItems": count}}, "required": ["answers"]} def agreement(truth: frozenset[str], given: list[str], root: str) -> float: """The Jaccard index of the answer and the truth, 1.0 when both are empty; a path is read from the repository's root whether given absolute or relative.""" answer = {normal(item, root) for item in given} return len(answer & truth) / len(answer | truth) if answer | truth else 1.0 def normal(item: str, root: str) -> str: item = item.strip().strip("`").strip() for prefix in (root.rstrip("/") + "/", "./"): item = item.removeprefix(prefix) return item def misses(asked: list[Question], given: list[list[str]], root: str) -> dict[Key, float]: """For each unit asked about, how far its answers fall short: 1 less the mean agreement of its questions.""" agreements: dict[Key, list[float]] = {} for question, answer in zip(asked, given): agreements.setdefault(question.unit, []).append(agreement(question.truth, answer, root)) return {unit: 1 - sum(values) / len(values) for unit, values in agreements.items()} def sample_units(units: list[Unit], asked: list[Key]) -> list[Unit]: keys = set(asked) return [unit for unit in units if (unit.path, unit.name) in keys]