Coverage for scripts/formal_inventory.py: 100%
77 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Every public function the trading path and the research path compute with, and how each is proved (V6.6.10). Imports nothing; reads the code with ast.
3 python scripts/formal_inventory.py # fails on an unclassified function, a spec that does not exist, or a backlog above its ceiling
4 python scripts/formal_inventory.py --report # the counts per status and per package
6`formal/inventory.json` classifies each function (`module:name`), or a whole module (`module`), as one of:
8- `spec:<Target>`: modelled in `formal/AetherFormal/<Target>.lean`, with theorems and a differential test;
9- `excluded:<reason>`: no arithmetic to prove: `io`, `orchestration`, `cli`, `plotting`, `torch-only`, `non-numeric`;
10- `backlog`: a pure numeric function without a spec yet.
12The backlog may only shrink: `BACKLOG_CEILING` is the count when it was last lowered, and a new pure numeric function has to come
13with its spec or be counted against it. A function entry wins over its module's.
14"""
16from __future__ import annotations
18import argparse
19import ast
20import json
21import subprocess
22import sys
23from collections import Counter
24from pathlib import Path
26ROOT = Path(__file__).resolve().parents[1]
27INVENTORY = ROOT / "formal" / "inventory.json"
28SCOPE = ("risk", "portfolio", "execution", "features", "evaluation", "retraining", "inference", "moe", "regime", "topology", "json_safety.py", "risk_controls.py")
29REASONS = frozenset({"io", "orchestration", "cli", "plotting", "torch-only", "non-numeric"})
30BACKLOG_CEILING = 881 # V6.6.10: the first inventory had 889 (1,252 functions, 48 with a spec); the phase's specs took it to 881
33def scope_files(root: Path = ROOT) -> list[str]:
34 # tracked and new (not yet added) files: a module written in this change is classified before its first commit
35 listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", *SCOPE], cwd=root, capture_output=True, text=True, check=True).stdout.split()
36 return sorted(path for path in listed if path.endswith(".py") and not path.endswith("__init__.py"))
39def module_name(path: str) -> str:
40 return path[:-3].replace("/", ".")
43def public_defs(root: Path = ROOT, files: list[str] | None = None) -> dict[str, list[str]]:
44 """{module: [public top-level function and class names]} for every file in scope."""
45 out = {}
46 for path in files if files is not None else scope_files(root):
47 tree = ast.parse((root / path).read_text(encoding="utf-8"))
48 names = [node.name for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and not node.name.startswith("_")]
49 if names:
50 out[module_name(path)] = names
51 return out
54def load_inventory(path: Path = INVENTORY) -> dict:
55 return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"modules": {}, "functions": {}}
58def status_of(module: str, name: str, inventory: dict) -> str | None:
59 return inventory.get("functions", {}).get(f"{module}:{name}") or inventory.get("modules", {}).get(module)
62def problems(defs: dict[str, list[str]], inventory: dict, *, specs: set[str], ceiling: int = BACKLOG_CEILING) -> list[str]:
63 """Everything wrong with the inventory: an unclassified function, an unknown status or reason, a spec file that does not exist,
64 an entry for a function that is gone, and a backlog above its ceiling."""
65 found: list[str] = []
66 backlog = 0
67 known = {f"{module}:{name}" for module, names in defs.items() for name in names}
68 for module, names in defs.items():
69 for name in names:
70 status = status_of(module, name, inventory)
71 if status is None:
72 found.append(f"{module}:{name} is not classified in formal/inventory.json")
73 elif status == "backlog":
74 backlog += 1
75 elif status.startswith("spec:"):
76 if status[5:] not in specs:
77 found.append(f"{module}:{name}: formal/AetherFormal/{status[5:]}.lean does not exist")
78 elif not (status.startswith("excluded:") and status[9:] in REASONS):
79 found.append(f"{module}:{name}: unknown status {status!r}")
80 found.extend(f"{entry} is in formal/inventory.json but no longer exists" for entry in sorted(set(inventory.get("functions", {})) - known))
81 found.extend(f"module {entry} is in formal/inventory.json but has no public function in scope" for entry in sorted(set(inventory.get("modules", {})) - set(defs)))
82 if backlog > ceiling:
83 found.append(f"the backlog is {backlog}, above its ceiling {ceiling}: write the spec, or classify the function")
84 return found
87def report(defs: dict[str, list[str]], inventory: dict) -> dict:
88 by_status: Counter = Counter()
89 by_package: dict[str, Counter] = {}
90 for module, names in defs.items():
91 for name in names:
92 status = status_of(module, name, inventory) or "unclassified"
93 kind = status.split(":")[0]
94 by_status[kind] += 1
95 by_package.setdefault(module.split(".")[0], Counter())[kind] += 1
96 return {"total": sum(by_status.values()), "by_status": dict(by_status), "by_package": {name: dict(counts) for name, counts in sorted(by_package.items())}}
99def spec_targets(root: Path = ROOT) -> set[str]:
100 return {path.stem for path in (root / "formal" / "AetherFormal").glob("*.lean")} - {"GenCases", "Real"}
103def main(argv: list[str] | None = None) -> int:
104 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
105 parser.add_argument("--report", action="store_true")
106 args = parser.parse_args(argv)
107 defs, inventory = public_defs(), load_inventory()
108 if args.report:
109 print(json.dumps(report(defs, inventory), indent=1))
110 return 0
111 found = problems(defs, inventory, specs=spec_targets())
112 for line in found:
113 print(f"formal inventory: {line}", file=sys.stderr)
114 return 1 if found else 0
117if __name__ == "__main__":
118 raise SystemExit(main())