# Select lean2zig Lean-Workbook units for ingot-lean-zig (Opus ยท Smelter, 2026-10-29). # Input : out/lean2zig/units_full.jsonl (1,900 units that passed the differential check) # Steps : (1) drop constant-only units (no parameters: e.g. `2 % 2 = 0`), (2) drop tautologies (both sides identical), # (3) calibrated near-duplicate cap: twin rate <= 25% (ID/N/T-normalised 5-gram Jaccard >= 0.90, measured on the # theorem functions only, as in results/cloud/lean-v2-review/shape_audit.py), most distinct first, # (4) re-verify each shipped file with `zig test`, lean.zig beside it. # Output: out/lean2zig/ingot_workbook.jsonl + selection stats (printed and written to results/cloud/lean2zig/select_stats.json) import json, os, re, sys, subprocess, tempfile, shutil, itertools, collections from concurrent.futures import ThreadPoolExecutor R = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) ZIG = os.environ.get('ZIG_BIN', 'zig'); LEANZIG = os.path.join(R, 'tools', 'lean2zig', 'lean.zig') U = [json.loads(l) for l in open(os.path.join(R, 'out', 'lean2zig', 'units_full.jsonl'))] KW = set('const var pub fn return if else while for switch struct and or orelse try comptime inline break continue true false undefined'.split()) TY = re.compile(r'^(u|i)\d+$|^usize$|^isize$|^bool$|^type$') def fns(t): return '\n'.join(re.findall(r'^pub fn .*?^}', t, re.M | re.S)) def shape(t): toks = re.findall(r'@\w+|[A-Za-z_]\w*|0x[0-9a-fA-F]+|\d+|\+%|-%|\*%|<<|>>|==|!=|<=|>=|\S', t) return [x if (x in KW or x.startswith('@')) else 'T' if TY.match(x) else 'N' if x[0].isdigit() else 'ID' if re.match(r'[A-Za-z_]', x) else x for x in toks] def body(t, side): m = re.search(r'pub fn \w+%s\([^)]*\)[^{]*\{(.*?)^}' % side, t, re.M | re.S); return re.sub(r'\s+', ' ', m.group(1)).strip() if m else None st = collections.OrderedDict(units_in=len(U)) c1 = [u for u in U if re.search(r'pub fn \w+\([^)]', u['text'])]; st['drop_constant_only'] = len(U) - len(c1) c2 = [u for u in c1 if not (body(u['text'], 'Lhs') is not None and body(u['text'], 'Lhs') == body(u['text'], 'Rhs'))]; st['drop_tautology'] = len(c1) - len(c2) G = [{tuple(s[i:i + 5]) for i in range(max(len(s) - 4, 1))} for s in (shape(fns(u['text'])) for u in c2)] nb = collections.defaultdict(set) for a, b in itertools.combinations(range(len(c2)), 2): if len(G[a] & G[b]) / len(G[a] | G[b]) >= 0.90: nb[a].add(b); nb[b].add(a) st['twin_rate_before'] = round(sum(1 for i in range(len(c2)) if nb[i]) / max(len(c2), 1), 4) kept, has_twin = [], set() for i in sorted(range(len(c2)), key=lambda i: (len(nb[i]), i)): new = {j for j in nb[i] if j in kept}; tw = has_twin | new | ({i} if new else set()) if len(tw) / (len(kept) + 1) <= 0.25: kept.append(i); has_twin = tw kept.sort(); st['drop_twin_cap'] = len(c2) - len(kept); st['twin_rate_after'] = round(len(has_twin) / max(len(kept), 1), 4) def ztest(u): d = tempfile.mkdtemp(prefix='l2z_') try: shutil.copy(LEANZIG, os.path.join(d, 'lean.zig')); open(os.path.join(d, 'unit.zig'), 'w').write(u['ship']) q = subprocess.run([ZIG, 'test', 'unit.zig', '--cache-dir', os.path.join(d, '.zc')], cwd=d, capture_output=True, text=True, timeout=300) return q.returncode == 0 except subprocess.TimeoutExpired: return False finally: shutil.rmtree(d, ignore_errors=True) sel = [c2[i] for i in kept] for u in sel: u['ship'] = 'const std = @import("std");\nconst lean = @import("lean.zig");\n\n' + u['text'].strip() + '\n' with ThreadPoolExecutor(2) as ex: ok = list(ex.map(ztest, sel)) final = [u for u, o in zip(sel, ok) if o]; st['drop_reverify'] = len(sel) - len(final); st['units_out'] = len(final) st['bytes'] = sum(len(u['ship'].encode()) for u in final); st['est_tokens'] = round(st['bytes'] / 3.27) with open(os.path.join(R, 'out', 'lean2zig', 'ingot_workbook.jsonl'), 'w') as o: for u in final: o.write(json.dumps(dict(id=u['id'], fn=u.get('fn'), text=u['ship'])) + '\n') os.makedirs(os.path.join(R, 'results', 'cloud', 'lean2zig'), exist_ok=True) json.dump(st, open(os.path.join(R, 'results', 'cloud', 'lean2zig', 'select_stats.json'), 'w'), indent=1) print(json.dumps(st))