"""One folder a pull request, from plan.json: what an agent's session needs to open it. python3 -I units.py //unit.json wave, family, branch, title, the declarations (name, file, first and last line on main 5baf4fe) //change.patch the deletions as a patch against main once the waves before it are in (absent for whole files) //PR.md the description's first draft /index.json the units by wave, in the order to open them Checks itself: applying a wave's patches to the tree before it gives the tree mktree.py makes.""" import collections, difflib, json, os, re, subprocess, sys, tempfile plan, site, out = json.load(open(sys.argv[1])), sys.argv[2], sys.argv[3] ISSUE = 10 # S-1: Delete declarations that nothing uses orig = {} def lines(f): if f not in orig: orig[f] = open(f"{site}/{f}", encoding="utf-8").read().split("\n") return orig[f] def cut(f, ranges): t, drop = lines(f), set() for a, b in ranges: drop.update(range(a, b + 1)) if a >= 2 and b < len(t) and not t[a - 2].strip() and not t[b].strip(): drop.add(b + 1) return drop def content(f, drop): return "\n".join(l for i, l in enumerate(lines(f), 1) if i not in drop) def slug(F): d, _, w = F.partition("/") # the folder NavierStokes/R3/ and the files NavierStokes/R3*.lean are two families return ("ns" if d == "NavierStokes" else d.lower()) + "-" + re.sub(r"[^a-z0-9]+", "-", w.lower()).strip("-") + ("" if w.endswith("*") else "-folder") def fam(f): parts = f[:-5].split("/"); d = parts[0] if f.startswith("NavierStokes/R3/"): return "NavierStokes/R3" w = re.match(r"([A-Z][a-z0-9]+)", parts[-1]); return d + "/" + (w.group(1) if w else parts[-1]) + "*" os.makedirs(out, exist_ok=True) index = [] SOURCE = ("How these were found. Treant (TitiSkywalker/NavierStokesAndEuler, the run of 2026-12-03 at upstream `f9e8bc5`) found them unreachable from the four " "Comparator theorems. On this project's main (`5baf4fe`) the declaration graph, exported from the compiled tree, was read again under this " "project's rule: a declaration that Treant deleted stays when one of the paper's results reaches it (the files `NavierStokes/PaperResults.lean` " "imports, `NavierStokes/R3/Theorem.lean`, `NavierStokes/LocalPaperTheorem.lean`), when its docstring cites the paper, or when the text of a " "declaration that stays names it. 640 of Treant's deletions stay for that; none of them is in this pull request.") # wave 0: files nothing imports byfam = collections.defaultdict(list) for f in plan["whole_files"]: byfam[fam(f)].append(f) wave0 = [] for F, files in sorted(byfam.items()): uid = f"s1-{slug(F)}-files"; d = f"{out}/{uid}"; os.makedirs(d, exist_ok=True) # lines() keeps the empty string after a file's last newline, which cut and content need; a whole # file's lines are wc -l's count, one fewer per file. n = sum(len(lines(f)) - 1 for f in files) title = f"chore({F.rstrip('*')}): delete {len(files)} file{'s' if len(files) != 1 else ''} nothing imports" json.dump({"id": uid, "wave": 0, "family": F, "issue": ISSUE, "branch": uid, "title": title, "kind": "files", "files": files, "lines": n}, open(f"{d}/unit.json", "w"), indent=1) open(f"{d}/PR.md", "w").write(f"Part of #{ISSUE} (its first step: the files).\n\nDeletes {len(files)} file{'s' if len(files) != 1 else ''} of the family `{F}`, {n} lines:\n\n" + "\n".join(f"- `{f}`" for f in files) + "\n\nHow these were found. Nothing reachable from `NavierStokes/ComparatorSolution.lean`, `NavierStokes/PaperResults.lean` or `Euler/Solution.lean` imports them " "(the graph of `import` lines on main `5baf4fe`): 61 files in all, the same 61 that Treant's run of 2026-12-03 deleted as dead modules " "(TitiSkywalker/NavierStokesAndEuler, branch `treant/01-dead_modules`) and that are still on this main.\n\n" "What it does not show: that every remaining file is needed.\n") wave0.append(uid) index.append(wave0) # waves 1..: declarations done = collections.defaultdict(set) for k, w in enumerate(plan["waves"], 1): ids, after_all = [], collections.defaultdict(set) for F, items in sorted(w.items()): uid = f"s1-{slug(F)}-{k}"; d = f"{out}/{uid}"; os.makedirs(d, exist_ok=True) byfile = collections.defaultdict(list) for m, a, b, name in items: byfile[m.replace(".", "/") + ".lean"].append((a, b, name)) patch, removed = [], 0 for f, rs in sorted(byfile.items()): drop = cut(f, [(a, b) for a, b, _ in rs]) - done[f] before, after = content(f, done[f]), content(f, done[f] | drop) patch += difflib.unified_diff(before.splitlines(keepends=True), after.splitlines(keepends=True), f"a/{f}", f"b/{f}", n=3) removed += len(drop); after_all[f] |= drop open(f"{d}/change.patch", "w", encoding="utf-8").write("".join(patch)) decls = [{"name": re.sub(r"^_private\..*?\.0\.", "", name), "file": f, "lines": [a, b]} for f, rs in sorted(byfile.items()) for a, b, name in sorted(rs)] title = f"chore({F.rstrip('*')}): delete {len(decls)} declaration{'s' if len(decls) != 1 else ''} nothing uses" json.dump({"id": uid, "wave": k, "family": F, "issue": ISSUE, "branch": uid, "title": title, "kind": "declarations", "files": sorted(byfile), "lines": removed, "declarations": decls}, open(f"{d}/unit.json", "w"), indent=1, ensure_ascii=False) shown = decls if len(decls) <= 60 else decls[:60] open(f"{d}/PR.md", "w", encoding="utf-8").write(f"Part of #{ISSUE}.\n\nDeletes {len(decls)} declaration{'s' if len(decls) != 1 else ''} of the family `{F}` that nothing uses, {removed} lines in {len(byfile)} file{'s' if len(byfile) != 1 else ''}. " "No statement and no proof that stays is changed: the diff is deletions only.\n\n" + "\n".join(f"- `{x['name']}` (`{x['file']}`)" for x in shown) + (f"\n- and {len(decls) - 60} more: the diff lists them\n" if len(decls) > 60 else "\n") + f"\n{SOURCE}\n\nOrder. In this wave ({k}) every declaration deleted here has no user left on main: what used them went in earlier waves or goes in this same pull request.\n\n" "What it does not show: that every remaining declaration is needed.\n") ids.append(uid) for f, drop in after_all.items(): done[f] |= drop index.append(ids) flat = [u for w in index for u in w] assert len(flat) == len(set(flat)), "two units share a name" json.dump(index, open(f"{out}/index.json", "w")) print("units by wave:", [len(x) for x in index], "=", sum(len(x) for x in index)) # self-check: git apply of every wave's patches, in order, on one tree gives the tree mktree.py makes for that wave with tempfile.TemporaryDirectory() as tmp: subprocess.run(f"git -C {site} archive HEAD | tar -x -C {tmp}", shell=True, check=True) subprocess.run(["git", "init", "-q", tmp], check=True) for k in range(1, len(index)): bad = 0 for uid in index[k]: r = subprocess.run(["git", "-C", tmp, "apply", "--whitespace=nowarn", os.path.abspath(f"{out}/{uid}/change.patch")], capture_output=True, text=True) bad += r.returncode != 0 if r.returncode: print(" does not apply:", uid, r.stderr.strip()[:160]) diff = n = 0 if os.path.isdir(f"trees/w{k}"): for d, _, names in os.walk(f"trees/w{k}"): for name in names: if name == "REMOVED": continue f = os.path.relpath(os.path.join(d, name), f"trees/w{k}"); n += 1 diff += open(f"{tmp}/{f}", encoding="utf-8").read() != open(f"trees/w{k}/{f}", encoding="utf-8").read() print(f"self-check, wave {k}: {bad} of {len(index[k])} patches did not apply; {diff} of {n} files differ from mktree's tree" + ("" if n else " (no tree to compare)"))