A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
feat(bench): add Wave 4 marathon long-plateau Google Colab autoresearch suite (#90)
Nebula65b7916ee76e
diff --git a/bench/colab_autoresearch_w4.py b/bench/colab_autoresearch_w4.pynew file mode 100644index 0000000..cd990a7--- /dev/null+++ b/bench/colab_autoresearch_w4.py@@ -0,0 +1,2600 @@+#!/usr/bin/env python3+"""+Forma Wave 4 Marathon Long-Plateau Multi-Track Autoresearch Engine (Google Colab & Local).++Designed for very long unattended marathon runs (`--max-minutes 1440` or `0` for unlimited,+long plateau patience 50-60, high round caps 300-500, round-robin track interleaving so all+3 tracks advance together, incremental JSONL checkpointing, `--resume` across Colab disconnects,+Google Drive mirroring via `--drive-dir`, and automatic transactional rollback on any gate failure).++Orchestrates 3 tracks in round-robin slices (default `--schedule round-robin --slice-rounds 10`)+or sequentially (`--schedule sequential`), or individually via `--tracks 1,2,3`:++ Track 1 — Kernel Speed & Multi-Part Session Autoresearch (`--t1-plateau 60 --t1-max-rounds 500`)+ - Benchmarks BOTH `cargo run --release -p forma-core --example perf_bench`+ (`TOTAL SUITE SCORE` ms) AND a stateful 10-part assembly session+ (`forma eval --strict --scene --out ... --render ...`) measuring eval ++ observe + multi-part GLB/PNG export latency.+ - Enforces a strict byte-exact GLB & PNG determinism gate + invariant & volume parity.+ - Runs evolutionary parameter/threshold search across tunable kernel knobs+ (BVH leaf thresholds, batch sizes `MAX_BATCH_TOOLS`/`MAX_BATCH_FACES`, LSCM CG+ tolerances/iters, remesh Taubin lambda/mu/passes, QEM pad/penalty weights,+ render edge thresholds) PLUS optional LLM-guided `<<<SEARCH / === / >>>REPLACE`+ structural mutations across `boolean.rs`, `uv.rs`, `remesh.rs`, `ops.rs`,+ `render.rs`, and `scene.rs` when `OPENROUTER_API_KEY` is set.+ - Strictly keeps ONLY verified speedups (>= 1.5% faster, confirmed on repeat run,+ 0 invariant regressions, byte-identical GLB/PNG replay).++ Track 2 — Adversarial Geometry Soundness & Fuzz Autoresearch (`--t2-plateau 60 --t2-max-rounds 500`)+ - Runs an evolutionary adversarial geometry stress suite via `forma eval --strict`:+ 1. Balanced ±45 deg diagonal fins+ 2. 3+ radial fin arrays+ 3. Micro-scale 1e-4 m nested/overlapping parts+ 4. Curved-tool CSG cuts (`torus`, `sphere`, `arc_tube`, `cone`)+ 5. Twisted lofts + `shell` + `bevel` + `remesh` + `bisect` + `deform` + `nurbs`/`sweep` chains+ 6. High-chart UV unwraps (`unwrap` with strict `inv == 0` & non-overlap check)+ - Tracks `failures`, `unverified_count`, `panics`, and `p99_ms`.+ - CEGAR-style counterexample bank: delta-minimizes every failing script and logs it+ to `counterexamples/`. When `OPENROUTER_API_KEY` is set, rotates across active+ counterexamples to propose targeted patches against `boolean.rs`, `invariants.rs`,+ `ops.rs`, and `remesh.rs`, verified against BOTH the counterexample bank AND+ `cargo test --release -p forma-core`.++ Track 3 — Agent-Pilot Token Efficiency & 1-Shot Accuracy Autoresearch (`--t3-plateau 50 --t3-max-rounds 300`)+ - Offline deterministic token-budget & error-scent scoring: `forma spec` token count,+ progressive `--topic` tokens, `Scene::observe` multi-part verbosity, GBNF grammar+ size/rules/states, CLI/MCP latency, and an 8-case error-scent quality battery.+ - Online 1-shot accuracy hill-climbing (when `OPENROUTER_API_KEY` is set): evaluates+ `bench/eval_complex_abc.py` tasks and hill-climbs on `SPEC_PIPE` / error hints /+ progressive topics maximizing `1-shot WT=ok + IoU` per token, gated by+ `cargo test --release -p forma-lang`.++Usage:+ python3 bench/colab_autoresearch_w4.py --dry-run --tracks 1,2,3+ python3 bench/colab_autoresearch_w4.py --tracks 1,2,3 --max-minutes 1440 --schedule round-robin \+ --slice-rounds 10 --resume --drive-dir /content/drive/MyDrive/forma_w4_autoresearch+"""+from __future__ import annotations++import argparse+import dataclasses+import hashlib+import json+import math+import os+import random+import re+import shutil+import statistics+import struct+import subprocess+import sys+import tarfile+import tempfile+import time+import urllib.error+import urllib.request+import zlib+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Dict, List, Optional, Sequence, Tuple+++ROOT = Path(__file__).resolve().parent.parent+TARGET_DIR = Path(os.environ.get("CARGO_TARGET_DIR") or (ROOT / "target"))+FORMA_BIN = TARGET_DIR / "release" / "forma"+FORMA_MCP_BIN = TARGET_DIR / "release" / "forma-mcp"+DEFAULT_LOG_PATH = ROOT / "bench" / "results" / "w4_autoresearch_log.jsonl"+DEFAULT_PATCHES_DIR = ROOT / "bench" / "results" / "w4_patches"++# Track 1 speedup gate: strictly >= 1.5% faster composite latency+MIN_SPEEDUP_RATIO = 0.015++# Optional tiktoken encoder for exact o200k_base token counting+_TIKTOKEN_ENC = None+try:+ import tiktoken # type: ignore++ _TIKTOKEN_ENC = tiktoken.get_encoding("o200k_base")+except Exception:+ _TIKTOKEN_ENC = None+++def count_tokens(text: str) -> int:+ """Count o200k_base tokens if tiktoken is installed, else deterministic BPE-like estimate."""+ if not text:+ return 0+ if _TIKTOKEN_ENC is not None:+ return len(_TIKTOKEN_ENC.encode(text))+ # Calibrated fallback matching o200k_base within ~5% on DSL/spec text+ parts = re.findall(r"[A-Za-z_][A-Za-z0-9_]*|[0-9]+(?:\.[0-9]+)?|[^\sA-Za-z0-9_]", text)+ return max(1, int(round(len(parts) * 0.92)))+++def utc_now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def cargo_env() -> Dict[str, str]:+ env = os.environ.copy()+ cargo_bin = os.path.expanduser("~/.cargo/bin")+ if cargo_bin not in env.get("PATH", ""):+ env["PATH"] = f"{cargo_bin}:{env.get('PATH', '')}"+ ncpu = os.cpu_count() or 2+ env.setdefault("CARGO_BUILD_JOBS", str(min(ncpu, 8)))+ if Path("/Library/Developer/CommandLineTools").exists():+ env.setdefault("DEVELOPER_DIR", "/Library/Developer/CommandLineTools")+ return env+++def get_openrouter_key(drive_dir: Optional[Path] = None) -> Optional[str]:+ key = os.environ.get("OPENROUTER_API_KEY", "").strip()+ if key:+ return key+ try:+ from google.colab import userdata # type: ignore++ key = (userdata.get("OPENROUTER_API_KEY") or "").strip()+ if key:+ return key+ except Exception:+ pass+ # Private Google Drive key file fallback (never stored in git)+ candidates: List[Path] = []+ if drive_dir:+ candidates.extend([drive_dir / ".openrouter_key", drive_dir.parent / ".openrouter_key"])+ candidates.append(Path("/content/drive/MyDrive/forma_w4_autoresearch/.openrouter_key"))+ for p in candidates:+ try:+ if p.exists():+ k = p.read_text().strip()+ if k:+ return k+ except Exception:+ pass+ return None+++def sha256_bytes(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def slugify(label: str, max_len: int = 36) -> str:+ s = re.sub(r"[^a-zA-Z0-9]+", "_", label).strip("_").lower()+ return (s[:max_len] or "patch").strip("_")+++# ---------------------------------------------------------------------------+# Transactional File Rollback Guard+# ---------------------------------------------------------------------------++class FileTransaction:+ """Snapshots one or more files and guarantees automatic rollback unless committed."""++ def __init__(self, paths: Sequence[Path]):+ self.paths = [Path(p) for p in paths]+ self._backups: Dict[Path, Optional[bytes]] = {}+ self._committed = False++ def __enter__(self) -> "FileTransaction":+ for p in self.paths:+ self._backups[p] = p.read_bytes() if p.exists() else None+ return self++ def commit(self) -> None:+ self._committed = True++ def rollback(self) -> None:+ for p, raw in self._backups.items():+ if raw is None:+ if p.exists():+ p.unlink()+ else:+ p.write_bytes(raw)+ self._committed = False++ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> bool:+ if not self._committed:+ self.rollback()+ return False+++# ---------------------------------------------------------------------------+# Build, Test & Perf Bench Runners+# ---------------------------------------------------------------------------++def build_forma(include_mcp: bool = False) -> Tuple[bool, str]:+ pkgs = ["-p", "forma-cli"]+ if include_mcp:+ pkgs.extend(["-p", "forma-mcp"])+ p = subprocess.run(+ ["cargo", "build", "--release", *pkgs],+ cwd=str(ROOT),+ env=cargo_env(),+ text=True,+ capture_output=True,+ timeout=360,+ )+ return (p.returncode == 0), p.stderr[-1500:]+++def run_rust_tests(package: str = "forma-core") -> Tuple[bool, str]:+ p = subprocess.run(+ ["cargo", "test", "--release", "-p", package, "--", "--test-threads=1"],+ cwd=str(ROOT),+ env=cargo_env(),+ text=True,+ capture_output=True,+ timeout=360,+ )+ return (p.returncode == 0), (p.stdout + "\n" + p.stderr)[-1800:]+++def run_perf_bench() -> Tuple[bool, Dict[str, float], str]:+ p = subprocess.run(+ ["cargo", "run", "--release", "-p", "forma-core", "--example", "perf_bench"],+ cwd=str(ROOT),+ env=cargo_env(),+ text=True,+ capture_output=True,+ timeout=240,+ )+ if p.returncode != 0:+ return False, {}, (p.stdout + "\n" + p.stderr)[-1200:]+ out: Dict[str, float] = {}+ m_tot = re.search(r"TOTAL SUITE SCORE \(lower is better\):\s*([0-9.]+)\s*ms", p.stdout)+ m_ren = re.search(r"render_512px:\s*([0-9.]+)\s*us", p.stdout)+ m_glb = re.search(r"write_glb:\s*([0-9.]+)\s*us", p.stdout)+ m_inv = re.search(r"invariants:\s*([0-9.]+)\s*us", p.stdout)+ m_shl = re.search(r"shell_solid:\s*([0-9.]+)\s*us", p.stdout)+ m_bat = re.search(r"flange_batch_5h\s+([0-9.]+)\s*ms", p.stdout)+ if not m_tot:+ return False, {}, p.stdout[-800:]+ out["suite_ms"] = float(m_tot.group(1))+ if m_ren:+ out["render_us"] = float(m_ren.group(1))+ if m_glb:+ out["write_glb_us"] = float(m_glb.group(1))+ if m_inv:+ out["invariants_us"] = float(m_inv.group(1))+ if m_shl:+ out["shell_solid_us"] = float(m_shl.group(1))+ if m_bat:+ out["flange_batch_ms"] = float(m_bat.group(1))+ return True, out, p.stdout+++def decode_png_rgb(png_bytes: bytes) -> Tuple[int, int, bytes]:+ """Pure-Python PNG decoder (filter types 0 & 1) for strict PNG validity & pixel checks."""+ if png_bytes[:8] != b"\x89PNG\r\n\x1a\n":+ raise ValueError("Invalid PNG magic header")+ pos = 8+ w = h = 0+ idat = bytearray()+ while pos < len(png_bytes):+ length = struct.unpack_from(">I", png_bytes, pos)[0]+ ctype = png_bytes[pos + 4 : pos + 8]+ cdata = png_bytes[pos + 8 : pos + 8 + length]+ crc_got = struct.unpack_from(">I", png_bytes, pos + 8 + length)[0]+ crc_exp = zlib.crc32(ctype + cdata) & 0xFFFFFFFF+ if crc_got != crc_exp:+ raise ValueError(f"Bad PNG CRC on {ctype!r}")+ if ctype == b"IHDR":+ w, h = struct.unpack_from(">II", cdata, 0)+ elif ctype == b"IDAT":+ idat.extend(cdata)+ elif ctype == b"IEND":+ break+ pos += 12 + length+ raw = zlib.decompress(bytes(idat))+ row_len = w * 3+ stride = 1 + row_len+ out = bytearray(h * row_len)+ for y in range(h):+ ftype = raw[y * stride]+ src_off = y * stride + 1+ dst_off = y * row_len+ if ftype == 0:+ out[dst_off : dst_off + row_len] = raw[src_off : src_off + row_len]+ elif ftype == 1:+ for x in range(row_len):+ left = out[dst_off + x - 3] if x >= 3 else 0+ out[dst_off + x] = (raw[src_off + x] + left) & 0xFF+ else:+ raise ValueError(f"Unexpected PNG filter {ftype}")+ return w, h, bytes(out)+++def verify_glb_uvs_and_nonoverlap(glb_path: Path, reported_util_pct: float) -> Tuple[bool, str]:+ """Verify TEXCOORD_0 finiteness, [0,1]^2 bounds, and 128x128 UV non-overlap in exported GLB."""+ raw = glb_path.read_bytes()+ if len(raw) < 28 or raw[:4] != b"glTF":+ return False, "invalid GLB header"+ jlen = int.from_bytes(raw[12:16], "little")+ gltf = json.loads(raw[20 : 20 + jlen].decode())+ bin_start = 20 + jlen + 8+ prim = gltf["meshes"][0]["primitives"][0]+ if "TEXCOORD_0" not in prim["attributes"]:+ return False, "missing TEXCOORD_0"+ uv_acc = gltf["accessors"][prim["attributes"]["TEXCOORD_0"]]+ uv_bv = gltf["bufferViews"][uv_acc["bufferView"]]+ uv_off = bin_start + uv_bv.get("byteOffset", 0) + uv_acc.get("byteOffset", 0)+ n_verts = uv_acc["count"]+ uvs = struct.unpack_from(f"<{n_verts * 2}f", raw, uv_off)+ if not all(math.isfinite(x) for x in uvs):+ return False, "non-finite UV"+ if min(uvs) < -1e-4 or max(uvs) > 1.0 + 1e-4:+ return False, f"UV OOB [{min(uvs):.4f}, {max(uvs):.4f}]"+ if "indices" in prim:+ idx_acc = gltf["accessors"][prim["indices"]]+ idx_bv = gltf["bufferViews"][idx_acc["bufferView"]]+ idx_off = bin_start + idx_bv.get("byteOffset", 0) + idx_acc.get("byteOffset", 0)+ fmt = "H" if idx_acc["componentType"] == 5123 else "I"+ indices = struct.unpack_from(f"<{idx_acc['count']}{fmt}", raw, idx_off)+ else:+ indices = tuple(range(n_verts))+ grid = 128+ covered = bytearray(grid * grid)+ sum_tri_area = 0.0+ for t in range(0, len(indices) - 2, 3):+ i0, i1, i2 = indices[t], indices[t + 1], indices[t + 2]+ ax, ay = uvs[2 * i0], uvs[2 * i0 + 1]+ bx, by = uvs[2 * i1], uvs[2 * i1 + 1]+ cx, cy = uvs[2 * i2], uvs[2 * i2 + 1]+ det = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay)+ a2 = abs(det)+ sum_tri_area += 0.5 * a2+ if a2 < 1e-10:+ continue+ x0 = max(0, min(grid - 1, int(min(ax, bx, cx) * grid)))+ x1 = max(0, min(grid - 1, int(max(ax, bx, cx) * grid)))+ y0 = max(0, min(grid - 1, int(min(ay, by, cy) * grid)))+ y1 = max(0, min(grid - 1, int(max(ay, by, cy) * grid)))+ inv_a = 1.0 / det+ for py in range(y0, y1 + 1):+ y = (py + 0.5) / grid+ row = py * grid+ for px in range(x0, x1 + 1):+ x = (px + 0.5) / grid+ u = ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) * inv_a+ if u < -1e-4:+ continue+ v = ((cx - bx) * (y - by) - (cy - by) * (x - bx)) * inv_a+ if v < -1e-4:+ continue+ if 1.0 - u - v >= -1e-4:+ covered[row + px] = 1+ unique_cov_pct = sum(covered) / (grid * grid) * 100.0+ sum_area_pct = sum_tri_area * 100.0+ if sum_area_pct - unique_cov_pct > 5.0:+ return False, f"UV overlap: sum={sum_area_pct:.1f}% vs cov={unique_cov_pct:.1f}%"+ if abs(sum_area_pct - reported_util_pct) > 2.5:+ return False, f"UV util mismatch: {reported_util_pct:.1f}% vs {sum_area_pct:.1f}%"+ return True, "ok"+++# ---------------------------------------------------------------------------+# LLM Patch Helper (OpenRouter `<<<SEARCH / === / >>>REPLACE`)+# ---------------------------------------------------------------------------++def extract_focused_slice(src: str, max_chars: int = 26000, focus_hint: str = "") -> str:+ """Keep prompt sizes bounded for large Rust files while preserving exact line text."""+ if len(src) <= max_chars:+ return src+ if focus_hint:+ idx = src.find(focus_hint)+ if idx != -1:+ half = max_chars // 2+ lo = max(0, idx - half)+ hi = min(len(src), lo + max_chars)+ return src[lo:hi]+ # Include top + bottom hot regions separated by a clear marker+ head = max_chars // 2+ tail = max_chars - head+ return src[:head] + "\n// ... [middle omitted] ...\n" + src[-tail:]+++def propose_llm_patch(+ api_key: str,+ model: str,+ rel_file: str,+ src: str,+ objective: str,+ metrics_summary: str,+ history: List[str],+ focus_hint: str = "",+) -> Tuple[str, Optional[str]]:+ focused = extract_focused_slice(src, max_chars=26000, focus_hint=focus_hint)+ prompt = (+ f"You are an elite Rust computational geometry, systems performance, and DSL engineer.\n"+ f"Target file: `{rel_file}` (pure Rust, zero new crates, 100% deterministic!).\n\n"+ f"Objective:\n{objective}\n\n"+ f"Current verified metrics:\n{metrics_summary}\n\n"+ f"Recent autoresearch history:\n" + ("\n".join(history[-10:]) or "(none)") + "\n\n"+ f"Propose ONE high-impact, surgical patch to `{rel_file}`.\n"+ f"Line 1: concise 1-sentence hypothesis.\n"+ f"Then emit 1 to 3 exact search-and-replace blocks:\n"+ f"<<<SEARCH\n<exact existing lines>\n===\n<replacement Rust lines>\n>>>REPLACE\n\n"+ f"Target source (`{rel_file}`):\n```rust\n{focused}\n```"+ )+ body = json.dumps(+ {+ "model": model,+ "messages": [{"role": "user", "content": prompt}],+ "temperature": 0.28,+ "max_tokens": 3500,+ }+ ).encode()+ req = urllib.request.Request(+ "https://openrouter.ai/api/v1/chat/completions",+ data=body,+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/wrong-nebula/forma",+ "X-Title": "forma-w4-autoresearch",+ },+ method="POST",+ )+ with urllib.request.urlopen(req, timeout=120) as resp:+ data = json.loads(resp.read().decode())+ reply = data["choices"][0]["message"]["content"] or ""+ hyp = reply.splitlines()[0].strip()[:180] if reply.strip() else "llm patch"+ blocks = re.findall(r"<<<SEARCH\s*\n(.*?)\n===\s*\n(.*?)\n>>>REPLACE", reply, re.DOTALL)+ if not blocks:+ return hyp, None+ out = src+ applied = 0+ for tgt, rep in blocks:+ if tgt and tgt in out:+ out = out.replace(tgt, rep, 1)+ applied += 1+ return hyp, (out if applied > 0 and out != src else None)+++# ===========================================================================+# TRACK 1: Kernel Speed & Multi-Part Stateful Session Autoresearch+# ===========================================================================++SESSION_10_PART_SCRIPT = """# Wave 4 Track 1: 10-Part Industrial Actuator Assembly (stateful session + queries + multi-part export)+m_gear = 0.05+z1 = 18+z2 = 12+cd = m_gear * (z1 + z2) / 2++base_plate = box(4.2, 2.6, 0.28, z0=0.0)+ | bevel(vertical, 0.22, segs=3)+ | cut(cyl(0.14, 0.6, segs=20), at=[(-1.75,-0.95,0.14), (-1.75,0.95,0.14), (1.75,-0.95,0.14), (1.75,0.95,0.14)])+ | mat("steel_base", color=(0.45, 0.50, 0.56), metallic=0.88, roughness=0.32)++housing = cyl(0.92, 1.15, segs=36, z0=0.28)+ | cut(cyl(0.58, 1.35, segs=32, z0=0.18))+ | cut(cyl(0.24, 2.2, segs=24, axis=y), at=(0, 0, 0.85))+ | mat("cast_alu", color=(0.74, 0.77, 0.80), metallic=0.85, roughness=0.28)++flange_top = cyl(1.08, 0.16, segs=36, z0=1.43)+ | cut(cyl(0.58, 0.40, segs=32, z0=1.35))+ | cut(cyl(0.08, 0.40, segs=16), at=[(0.86*cos(2*pi*i/6), 0.86*sin(2*pi*i/6), 1.51) for i in range(6)])+ | mat("anodized_blue", color=(0.20, 0.45, 0.78), metallic=0.75, roughness=0.30)++drive_gear = gear(z1, m=m_gear, h=0.24, bore=0.14)+ | move(0, 0, 0.72)+ | mat("brass", color=(0.82, 0.64, 0.28), metallic=0.92, roughness=0.24)++pinion_gear = gear(z2, m=m_gear, h=0.24, bore=0.10)+ | rot(0, 0, 180 / z2)+ | move(cd, 0, 0.72)+ | mat("bronze", color=(0.74, 0.48, 0.26), metallic=0.90, roughness=0.26)++main_shaft = cyl(0.13, 1.95, segs=24, z0=0.20)+ | mat("chrome", color=(0.88, 0.90, 0.92), metallic=0.96, roughness=0.14)++pinion_shaft = cyl(0.09, 1.45, segs=24, z0=0.28)+ | move(cd, 0, 0)+ | mat("chrome", color=(0.88, 0.90, 0.92), metallic=0.96, roughness=0.14)++side_bracket = box(0.75, 0.55, 0.16, center=(-1.35, 0, 0.36))+ | add(box(0.16, 0.55, 0.95, center=(-1.645, 0, 0.755)))+ | cut(cyl(0.10, 0.50, segs=20, axis=x), at=(-1.645, 0, 0.95))+ | mat("powder_dark", color=(0.22, 0.24, 0.28), metallic=0.40, roughness=0.55)++end_cap = cyl(0.56, 0.42, segs=28, z0=1.59)+ | shell(0.06, open_top=false)+ | mat("polymer_orange", color=(0.90, 0.42, 0.14), metallic=0.10, roughness=0.42)++conduit_arc = arc_tube(center=(0.95, 0.0, 0.85), rx=0.42, rz=0.38, start=-90, end=90, r=0.065)+ | mat("copper", color=(0.84, 0.46, 0.30), metallic=0.92, roughness=0.24)++clearance(drive_gear, housing)+section(base_plate, 0.14)+"""+++@dataclass(frozen=True)+class KernelKnob:+ name: str+ rel_file: str+ pattern: str+ lo: float+ hi: float+ is_int: bool+ sci: bool = False+++TRACK1_KNOBS: List[KernelKnob] = [+ # boolean.rs BVH & batch parameters+ KernelKnob(+ "tri_bvh_max_leaf",+ "crates/forma-core/src/boolean.rs",+ r"(if count <= )(\d+)(\s*\{\s*\n\s*return node_idx;)",+ 2, 16, True,+ ),+ KernelKnob(+ "pt_bvh_max_leaf",+ "crates/forma-core/src/boolean.rs",+ r"(if count <= )(\d+)(\s*\{\s*\n\s*nodes\.push\(PtBvhNode)",+ 4, 24, True,+ ),+ KernelKnob(+ "max_batch_tools",+ "crates/forma-core/src/boolean.rs",+ r"(const MAX_BATCH_TOOLS:\s*usize\s*=\s*)(\d+)(;)",+ 2, 12, True,+ ),+ KernelKnob(+ "max_batch_faces",+ "crates/forma-core/src/boolean.rs",+ r"(const MAX_BATCH_FACES:\s*usize\s*=\s*)(\d+)(;)",+ 96, 768, True,+ ),+ # uv.rs LSCM CG & packer knobs+ KernelKnob(+ "lscm_cg_max_iters_hi",+ "crates/forma-core/src/uv.rs",+ r"(let max_iters = \(nf_dof \* 3\)\.clamp\(\d+,\s*)(\d+)(\);)",+ 160, 640, True,+ ),+ KernelKnob(+ "lscm_cg_max_iters_lo",+ "crates/forma-core/src/uv.rs",+ r"(let max_iters = \(nf_dof \* 3\)\.clamp\()(\d+)(,\s*\d+\);)",+ 32, 120, True,+ ),+ KernelKnob(+ "uv_perm_trials",+ "crates/forma-core/src/uv.rs",+ r"(let perm_trials:\s*usize\s*=\s*)(\d+)(;)",+ 6, 40, True,+ ),+ KernelKnob(+ "uv_split_fill_thresh",+ "crates/forma-core/src/uv.rs",+ r"(let split_fill_thresh:\s*f64\s*=\s*)([0-9.]+)(;)",+ 0.68, 0.92, False,+ ),+ KernelKnob(+ "uv_split_gain_ratio",+ "crates/forma-core/src/uv.rs",+ r"(let split_gain_ratio:\s*f64\s*=\s*)([0-9.]+)(;)",+ 0.84, 0.98, False,+ ),+ # remesh.rs Taubin & volume calibration knobs+ KernelKnob(+ "taubin_lambda",+ "crates/forma-core/src/remesh.rs",+ r"(let taubin_lambda:\s*f64\s*=\s*)([0-9.]+)(;)",+ 0.12, 0.48, False,+ ),+ KernelKnob(+ "taubin_mu",+ "crates/forma-core/src/remesh.rs",+ r"(let taubin_mu:\s*f64\s*=\s*-)([0-9.]+)(;)",+ 0.14, 0.52, False,+ ),+ KernelKnob(+ "taubin_passes",+ "crates/forma-core/src/remesh.rs",+ r"(let taubin_passes:\s*usize\s*=\s*)(\d+)(;)",+ 1, 3, True,+ ),+ KernelKnob(+ "vol_cal_gain",+ "crates/forma-core/src/remesh.rs",+ r"(let vol_cal_gain:\s*f64\s*=\s*)([0-9.]+)(;)",+ 0.75, 1.10, False,+ ),+ # ops.rs QEM decimation knobs+ KernelKnob(+ "qem_aabb_pad",+ "crates/forma-core/src/ops.rs",+ r"(let qem_aabb_pad:\s*f64\s*=\s*)([0-9.]+)(;)",+ 0.08, 0.80, False,+ ),+ KernelKnob(+ "qem_len_pen",+ "crates/forma-core/src/ops.rs",+ r"(let len_pen = \(pu - pv\)\.len_sq\(\) \* )([0-9.eE-]+)(;)",+ 1e-12, 1e-8, False, True,+ ),+ # render.rs edge angle threshold+ KernelKnob(+ "render_edge_cos_deg",+ "crates/forma-core/src/render.rs",+ r"(let cos_thresh = )([0-9.]+)(f64\.to_radians\(\)\.cos\(\);)",+ 18.0, 32.0, False,+ ),+]++TRACK1_LLM_FILES = [+ "crates/forma-core/src/boolean.rs",+ "crates/forma-core/src/uv.rs",+ "crates/forma-core/src/remesh.rs",+ "crates/forma-core/src/ops.rs",+ "crates/forma-core/src/render.rs",+ "crates/forma-core/src/scene.rs",+]+++def parse_eval_parts(stdout: str) -> List[Dict[str, Any]]:+ parts: List[Dict[str, Any]] = []+ for line in stdout.splitlines():+ m = re.match(+ r"^\s*-\s+([A-Za-z0-9_]+):\s+V=(\d+)\s+F=(\d+)\s+WT=(\S+)\s+NM=(\d+)\s+B=(\d+)\s+g=(-?\d+)\s+vol=([0-9.eE+-]+)",+ line,+ )+ if m:+ parts.append(+ {+ "name": m.group(1),+ "V": int(m.group(2)),+ "F": int(m.group(3)),+ "WT": m.group(4),+ "NM": int(m.group(5)),+ "B": int(m.group(6)),+ "g": int(m.group(7)),+ "vol": float(m.group(8)),+ }+ )+ return parts+++def eval_session_10_part(repeats: int = 2, check_determinism: bool = True) -> Tuple[bool, Dict[str, Any]]:+ times_ms: List[float] = []+ last_stdout = ""+ glb_hash_1 = ""+ png_hash_1 = ""+ glb_bytes_len = 0+ png_bytes_len = 0+ png_dims = (0, 0)++ with tempfile.TemporaryDirectory() as td:+ tdp = Path(td)+ out_glb = tdp / "session_10.glb"+ out_png = tdp / "session_10.png"+ for idx in range(repeats):+ t0 = time.perf_counter()+ r = subprocess.run(+ [+ str(FORMA_BIN),+ "eval",+ "--strict",+ "--scene",+ "--out",+ str(out_glb),+ "--render",+ str(out_png),+ ],+ input=SESSION_10_PART_SCRIPT,+ text=True,+ capture_output=True,+ timeout=60,+ )+ ms = (time.perf_counter() - t0) * 1000.0+ if r.returncode != 0:+ return False, {"error": f"10-part session rc={r.returncode}: {r.stderr[:240]}"}+ last_stdout = r.stdout+ times_ms.append(ms)+ if idx == 0:+ glb_raw = out_glb.read_bytes()+ png_raw = out_png.read_bytes()+ glb_hash_1 = sha256_bytes(glb_raw)+ png_hash_1 = sha256_bytes(png_raw)+ glb_bytes_len = len(glb_raw)+ png_bytes_len = len(png_raw)+ try:+ w, h, _ = decode_png_rgb(png_raw)+ png_dims = (w, h)+ except Exception as exc:+ return False, {"error": f"PNG decode failed: {exc}"}++ det_ok = True+ if check_determinism:+ out_glb2 = tdp / "session_10_replay.glb"+ out_png2 = tdp / "session_10_replay.png"+ r2 = subprocess.run(+ [+ str(FORMA_BIN),+ "eval",+ "--strict",+ "--scene",+ "--out",+ str(out_glb2),+ "--render",+ str(out_png2),+ ],+ input=SESSION_10_PART_SCRIPT,+ text=True,+ capture_output=True,+ timeout=60,+ )+ if r2.returncode != 0:+ return False, {"error": f"Determinism replay rc={r2.returncode}: {r2.stderr[:200]}"}+ glb_hash_2 = sha256_bytes(out_glb2.read_bytes())+ png_hash_2 = sha256_bytes(out_png2.read_bytes())+ if glb_hash_1 != glb_hash_2:+ return False, {"error": f"GLB nondeterministic! {glb_hash_1[:12]} != {glb_hash_2[:12]}"}+ if png_hash_1 != png_hash_2:+ return False, {"error": f"PNG nondeterministic! {png_hash_1[:12]} != {png_hash_2[:12]}"}++ parts = parse_eval_parts(last_stdout)+ if len(parts) != 10:+ return False, {"error": f"expected 10 parts, got {len(parts)}"}+ for p in parts:+ if p["WT"] != "ok" or p["NM"] != 0 or p["B"] != 0:+ return False, {"error": f"invariant fail on {p['name']}: WT={p['WT']} NM={p['NM']} B={p['B']}"}+ total_vol = sum(p["vol"] for p in parts)+ med_ms = sorted(times_ms)[len(times_ms) // 2]+ return True, {+ "session_ms": round(med_ms, 2),+ "parts": len(parts),+ "total_vol": round(total_vol, 6),+ "glb_sha256": glb_hash_1,+ "png_sha256": png_hash_1,+ "glb_bytes": glb_bytes_len,+ "png_bytes": png_bytes_len,+ "png_dims": list(png_dims),+ "determinism_ok": det_ok,+ "observe_tokens": count_tokens(last_stdout),+ }+++def eval_track1(+ repeats: int = 2,+ baseline: Optional[Dict[str, Any]] = None,+ require_exact_glb_vs_base: bool = False,+) -> Tuple[bool, Dict[str, Any]]:+ ok_pb, pb, pb_raw = run_perf_bench()+ if not ok_pb:+ return False, {"error": f"perf_bench failed: {pb_raw[:240]}"}+ ok_sess, sess = eval_session_10_part(repeats=repeats, check_determinism=True)+ if not ok_sess:+ return False, sess++ if baseline is not None:+ base_vol = baseline["session"]["total_vol"]+ cand_vol = sess["total_vol"]+ rel_err = abs(cand_vol - base_vol) / max(abs(base_vol), 1e-9)+ if rel_err > 0.002:+ return False, {"error": f"10-part volume drift {rel_err * 100:.3f}% ({cand_vol:.5f} vs {base_vol:.5f})"}+ if require_exact_glb_vs_base and sess["glb_sha256"] != baseline["session"]["glb_sha256"]:+ return False, {"error": "GLB hash diverged from baseline"}++ suite_ms = pb["suite_ms"]+ session_ms = sess["session_ms"]+ composite_ms = round(0.65 * suite_ms + 0.35 * session_ms, 3)+ return True, {+ "composite_ms": composite_ms,+ "suite_ms": round(suite_ms, 2),+ "session_ms": round(session_ms, 2),+ "perf_bench": pb,+ "session": sess,+ }+++def mutate_track1_knob(rng: random.Random, scale: float) -> Tuple[Optional[Path], Optional[str], str]:+ """Randomly pick an active Track 1 knob and propose a bounded mutation."""+ candidates: List[Tuple[KernelKnob, Path, str, re.Match[str]]] = []+ for k in TRACK1_KNOBS:+ p = ROOT / k.rel_file+ if not p.exists():+ continue+ src = p.read_text()+ m = re.search(k.pattern, src)+ if m:+ candidates.append((k, p, src, m))+ if not candidates:+ return None, None, ""+ knob, path, src, m = rng.choice(candidates)+ cur_val = float(m.group(2))+ span = knob.hi - knob.lo+ if knob.is_int:+ step = max(1, int(round(span * 0.30 * scale)))+ cand = int(round(cur_val + rng.choice([-1, 1]) * rng.randint(1, step)))+ cand = max(int(knob.lo), min(int(knob.hi), cand))+ if cand == int(round(cur_val)):+ cand = max(int(knob.lo), min(int(knob.hi), int(round(cur_val)) + rng.choice([-1, 1])))+ rep = f"{m.group(1)}{cand}{m.group(3)}"+ desc = f"{knob.name}:{int(cur_val)}->{cand}"+ elif knob.sci:+ log_lo = math.log10(max(knob.lo, 1e-18))+ log_hi = math.log10(max(knob.hi, 1e-18))+ log_cur = math.log10(max(cur_val, 1e-18))+ delta = rng.gauss(0.0, (log_hi - log_lo) * 0.25 * scale)+ if abs(delta) < 0.15:+ delta = rng.choice([-1.0, 1.0]) * 0.35 * scale+ cand = 10.0 ** max(log_lo, min(log_hi, log_cur + delta))+ rep = f"{m.group(1)}{cand:.2e}{m.group(3)}"+ desc = f"{knob.name}:{cur_val:.1e}->{cand:.1e}"+ else:+ delta = rng.gauss(0.0, span * 0.20 * scale)+ if abs(delta) < span * 0.015:+ delta = rng.choice([-1.0, 1.0]) * span * 0.05 * scale+ cand = max(knob.lo, min(knob.hi, cur_val + delta))+ rep = f"{m.group(1)}{cand:.4f}{m.group(3)}"+ desc = f"{knob.name}:{cur_val:.4f}->{cand:.4f}"+ new_src = src[: m.start()] + rep + src[m.end() :]+ if new_src == src:+ return None, None, ""+ return path, new_src, desc+++# ===========================================================================+# TRACK 2: Adversarial Geometry Soundness & Fuzz Autoresearch (CEGAR)+# ===========================================================================++@dataclass+class AdversarialCase:+ case_id: str+ category: str+ script: str+ expect_uv: bool = False+++CANONICAL_ADVERSARIAL_SUITE: List[AdversarialCase] = [+ # 1. Balanced ±45° diagonal fins+ AdversarialCase(+ "diag_fins_45_cross",+ "diagonal_45_fins",+ """hub = cyl(0.45, 1.6, segs=24, z0=0)+fin_pos = box(2.2, 0.14, 1.4, z0=0.1) | rot(0, 0, 45)+fin_neg = box(2.2, 0.14, 1.4, z0=0.1) | rot(0, 0, -45)+part = hub | add(fin_pos) | add(fin_neg) | cut(cyl(0.22, 2.0, segs=24, z0=-0.2))""",+ ),+ AdversarialCase(+ "diag_fins_45_tilted",+ "diagonal_45_fins",+ """body = box(1.8, 1.2, 1.2)+rib_a = box(1.9, 0.18, 0.9) | rot(0, 45, 0)+rib_b = box(1.9, 0.18, 0.9) | rot(0, -45, 0)+part = body | add(rib_a) | add(rib_b) | cut(cyl(0.28, 2.4, segs=24, axis=y))""",+ ),+ # 2. 3+ radial fin arrays+ AdversarialCase(+ "radial_fins_5",+ "radial_fin_arrays",+ """core = cyl(0.40, 1.5, segs=28, z0=0)+fins = box(0.95, 0.10, 1.2, center=(0.55, 0, 0.75)) | radial(5, r=0.0, axis=z)+part = core | add(fins) | cut(cyl(0.20, 1.9, segs=24, z0=-0.2))""",+ ),+ AdversarialCase(+ "radial_fins_7_taper",+ "radial_fin_arrays",+ """core = cone(0.55, 0.35, 1.4, segs=28, z0=0)+fins = box(0.75, 0.08, 1.0, center=(0.52, 0, 0.65)) | radial(7, r=0.0, axis=z)+part = core | add(fins) | cut(cyl(0.18, 1.8, segs=24, z0=-0.2))""",+ ),+ # 3. Micro-scale 1e-4 m nested/overlapping parts+ AdversarialCase(+ "micro_1e4_nested_bore",+ "micro_scale_1e4",+ """s = 0.0001+outer = box(4.0*s, 2.5*s, 1.2*s, z0=0)+boss = cyl(0.9*s, 1.6*s, segs=20, z0=0.4*s)+part = outer | add(boss) | cut(cyl(0.45*s, 3.0*s, segs=20, z0=-0.3*s))""",+ ),+ AdversarialCase(+ "micro_2e4_shell_overlap",+ "micro_scale_1e4",+ """s = 0.0002+a = box(3.0*s, 2.0*s, 1.5*s, z0=0) | shell(0.25*s)+b = box(1.2*s, 2.4*s, 0.6*s, center=(0, 0, 0.45*s))+part = a | add(b)""",+ ),+ # 4. Curved-tool CSG cuts+ AdversarialCase(+ "curved_torus_cut",+ "curved_tool_csg",+ """blk = box(2.6, 2.6, 1.0) | bevel(vertical, 0.25, segs=3)+ring = torus(0.95, 0.24)+part = blk | cut(ring) | cut(sphere(0.42))""",+ ),+ AdversarialCase(+ "curved_arc_tube_union_cut",+ "curved_tool_csg",+ """body = cyl(0.65, 1.8, segs=28, z0=0)+handle = arc_tube(center=(0.60, 0, 0.90), rx=0.42, rz=0.40, start=-90, end=90, r=0.10)+part = body | add(handle) | cut(cyl(0.48, 1.7, segs=28, z0=0.18))""",+ ),+ # 5. Twisted loft + shell + bevel + remesh + bisect + deform + nurbs chains+ AdversarialCase(+ "chain_loft_twist_bisect",+ "complex_op_chains",+ """part = loft([(0.0, [(-0.7,-0.5),(0.7,-0.5),(0.7,0.5),(-0.7,0.5)]), (1.2, [(-0.4,-0.6),(0.6,-0.3),(0.4,0.6),(-0.6,0.3)]), (2.4, [(-0.5,-0.5),(0.5,-0.5),(0.5,0.5),(-0.5,0.5)])])+ | deform("twist", axis=z, angle=60)+ | bisect(normal=(0, 0, 1), offset=2.1)""",+ ),+ AdversarialCase(+ "chain_nurbs_sweep_remesh",+ "complex_op_chains",+ """rail = nurbs([(0,0,0), (0,0,0.9), (0.8,0.4,1.6), (1.6,0,2.1)], degree=3, segs=20)+part = sweep([(-0.22,-0.16),(0.22,-0.16),(0.22,0.16),(-0.22,0.16)], rail, scale_end=0.6, twist=75)+ | remesh(0.10)+ | bisect(normal=(1, 0, 0), offset=1.2)""",+ ),+ AdversarialCase(+ "chain_bevel_shell_deform",+ "complex_op_chains",+ """part = box(2.0, 1.4, 1.2, z0=0)+ | bevel(vertical, 0.20, segs=3)+ | shell(0.14)+ | deform("taper", axis=z, factor=0.20)""",+ ),+ # 6. High-chart UV unwraps+ AdversarialCase(+ "high_chart_uv_manifold",+ "high_chart_uv",+ """part = box(3.6, 2.2, 0.5)+ | bevel(vertical, 0.22, segs=3)+ | cut(cyl(0.42, 1.0, segs=28))+ | cut(cyl(0.20, 1.0, segs=20), at=[(-1.2,-0.6,0),(-1.2,0.6,0),(1.2,-0.6,0),(1.2,0.6,0),(0,-0.72,0),(0,0.72,0)])+ | unwrap(35, 0.01)""",+ expect_uv=True,+ ),+]+++def generate_mutated_adversarial_cases(rng: random.Random, round_idx: int, count: int = 6) -> List[AdversarialCase]:+ """Generate randomized adversarial stress cases across all 6 failure-prone families."""+ cases: List[AdversarialCase] = []+ # Family 1: ±45° / near-45° diagonal fins+ ang = rng.choice([45.0, 44.5, 45.5, 30.0, 60.0])+ fin_t = round(rng.uniform(0.06, 0.22), 3)+ bore_r = round(rng.uniform(0.14, 0.34), 3)+ cases.append(+ AdversarialCase(+ f"fuzz_r{round_idx:03d}_diag",+ "diagonal_45_fins",+ f"""hub = cyl(0.45, 1.5, segs={rng.choice([16,24,32])}, z0=0)+f1 = box(2.1, {fin_t}, 1.3, z0=0.1) | rot(0, 0, {ang})+f2 = box(2.1, {fin_t}, 1.3, z0=0.1) | rot(0, 0, {-ang})+part = hub | add(f1) | add(f2) | cut(cyl({bore_r}, 2.0, segs=24, z0=-0.2))""",+ )+ )+ # Family 2: 3..9 radial fin arrays+ n_fins = rng.choice([3, 4, 5, 6, 7, 8, 9])+ fin_w = round(rng.uniform(0.06, 0.14), 3)+ cases.append(+ AdversarialCase(+ f"fuzz_r{round_idx:03d}_radial_{n_fins}",+ "radial_fin_arrays",+ f"""core = cyl(0.42, 1.4, segs={rng.choice([20,28,36])}, z0=0)+fins = box(0.85, {fin_w}, 1.1, center=(0.50, 0, 0.70)) | radial({n_fins}, r=0.0, axis=z)+part = core | add(fins) | cut(cyl(0.20, 1.8, segs=24, z0=-0.2))""",+ )+ )+ # Family 3: Micro-scale 1e-4 .. 5e-4 m+ sc = rng.choice([1e-4, 1.5e-4, 2.5e-4, 5e-4])+ off_x = round(rng.uniform(0.0, 0.8), 2)+ cases.append(+ AdversarialCase(+ f"fuzz_r{round_idx:03d}_micro",+ "micro_scale_1e4",+ f"""s = {sc:.6f}+a = box(3.2*s, 2.2*s, 1.2*s, z0=0)+b = cyl(0.8*s, 1.4*s, segs=20, center=({off_x}*s, 0, 0.6*s))+part = a | add(b) | cut(cyl(0.35*s, 2.6*s, segs=20, center=({off_x}*s, 0, 0.6*s)))""",+ )+ )+ # Family 4: Curved-tool CSG+ tr = round(rng.uniform(0.75, 1.15), 3)+ mr = round(rng.uniform(0.16, 0.30), 3)+ sp_r = round(rng.uniform(0.30, 0.55), 3)+ cases.append(+ AdversarialCase(+ f"fuzz_r{round_idx:03d}_curved",+ "curved_tool_csg",+ f"""blk = box(2.5, 2.5, 1.1) | bevel(vertical, 0.22, segs=2)+part = blk | cut(torus({tr}, {mr})) | add(sphere({sp_r}, at=(0, 0, 0.50)))""",+ )+ )+ # Family 5: Complex op chain+ tw = rng.choice([45, 75, 90, 120])+ vx = round(rng.uniform(0.09, 0.14), 3)+ cases.append(+ AdversarialCase(+ f"fuzz_r{round_idx:03d}_chain",+ "complex_op_chains",+ f"""rail = nurbs([(0,0,0),(0,0,0.8),({round(rng.uniform(0.5,1.1),2)},0.4,1.5),(1.5,0,2.0)], degree=3, segs=18)+part = sweep([(-0.20,-0.15),(0.20,-0.15),(0.20,0.15),(-0.20,0.15)], rail, scale_end=0.55, twist={tw})+ | remesh({vx})+ | bisect(normal=(0, 0, 1), offset=1.7)""",+ )+ )+ # Family 6: High-chart UV unwrap+ uv_ang = rng.choice([30, 35, 42, 48])+ cases.append(+ AdversarialCase(+ f"fuzz_r{round_idx:03d}_uv",+ "high_chart_uv",+ f"""core = cyl(0.50, 1.2, segs=24, z0=0) | bevel(top_rim, 0.10, segs=2)+fins = box(0.75, 0.12, 0.85, center=(0.55, 0, 0.55)) | radial({rng.choice([3,4,5])}, r=0.0, axis=z)+part = core | add(fins) | cut(cyl(0.22, 1.6, segs=20, z0=-0.2)) | unwrap({uv_ang}, 0.01)""",+ expect_uv=True,+ )+ )+ return cases[:count]+++def run_adversarial_case(case: AdversarialCase, timeout_s: float = 30.0) -> Dict[str, Any]:+ with tempfile.TemporaryDirectory() as td:+ out_glb = Path(td) / f"{case.case_id}.glb"+ cmd = [str(FORMA_BIN), "eval", "--strict"]+ if case.expect_uv:+ cmd.extend(["--out", str(out_glb)])+ t0 = time.perf_counter()+ try:+ r = subprocess.run(cmd, input=case.script, text=True, capture_output=True, timeout=timeout_s)+ ms = (time.perf_counter() - t0) * 1000.0+ except subprocess.TimeoutExpired:+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": False,+ "unverified": True,+ "ms": timeout_s * 1000.0,+ "error": f"timeout>{timeout_s}s",+ }+ combined = (r.stdout + "\n" + r.stderr)+ is_panic = (+ r.returncode == 101+ or r.returncode < 0+ or "panicked at" in combined+ or "RUST_BACKTRACE" in combined+ )+ if r.returncode != 0:+ err_line = (r.stderr.strip() or r.stdout.strip() or f"rc={r.returncode}").splitlines()[-1][:220]+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": is_panic,+ "unverified": True,+ "ms": round(ms, 2),+ "error": err_line,+ }+ parts = parse_eval_parts(r.stdout)+ if not parts:+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": is_panic,+ "unverified": True,+ "ms": round(ms, 2),+ "error": "no parts reported in stdout",+ }+ for p in parts:+ if p["WT"] != "ok" or p["NM"] != 0 or p["B"] != 0:+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": is_panic,+ "unverified": True,+ "ms": round(ms, 2),+ "error": f"unverified {p['name']}: WT={p['WT']} NM={p['NM']} B={p['B']}",+ }+ if case.expect_uv:+ m = re.search(r"uv: charts=(\d+) util=([\d.]+)% stretch=([\d.]+) inv=(\d+)", r.stdout)+ if not m:+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": False,+ "unverified": True,+ "ms": round(ms, 2),+ "error": "missing UV diagnostics",+ }+ inv = int(m.group(4))+ util = float(m.group(2))+ if inv != 0:+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": False,+ "unverified": True,+ "ms": round(ms, 2),+ "error": f"UV inverted triangles inv={inv}",+ }+ if out_glb.exists():+ ok_ov, msg_ov = verify_glb_uvs_and_nonoverlap(out_glb, util)+ if not ok_ov:+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": False,+ "panic": False,+ "unverified": True,+ "ms": round(ms, 2),+ "error": f"UV check failed: {msg_ov}",+ }+ return {+ "case_id": case.case_id,+ "category": case.category,+ "ok": True,+ "panic": False,+ "unverified": False,+ "ms": round(ms, 2),+ "error": "",+ }+++def minimize_counterexample(case: AdversarialCase) -> AdversarialCase:+ """Delta-minimize a failing Forma-Pipe script by dropping trailing pipe stages if still failing."""+ lines = [l for l in case.script.splitlines() if l.strip()]+ best_script = case.script+ # Try removing trailing `| op(...)` lines from the final statement+ for k in range(len(lines) - 1, 0, -1):+ if lines[k].lstrip().startswith("|"):+ cand_lines = lines[:k] + lines[k + 1 :]+ cand_case = AdversarialCase(+ case_id=case.case_id,+ category=case.category,+ script="\n".join(cand_lines),+ expect_uv=case.expect_uv and ("unwrap(" in "\n".join(cand_lines)),+ )+ res = run_adversarial_case(cand_case, timeout_s=15.0)+ if not res["ok"]:+ lines = cand_lines+ best_script = cand_case.script+ return AdversarialCase(+ case_id=case.case_id,+ category=case.category,+ script=best_script,+ expect_uv=case.expect_uv and ("unwrap(" in best_script),+ )+++def eval_adversarial_suite(cases: Sequence[AdversarialCase]) -> Dict[str, Any]:+ results = [run_adversarial_case(c) for c in cases]+ latencies = sorted(r["ms"] for r in results)+ p99_idx = min(len(latencies) - 1, max(0, int(math.ceil(0.99 * len(latencies))) - 1)) if latencies else 0+ p99_ms = latencies[p99_idx] if latencies else 0.0+ failures = [r for r in results if not r["ok"]]+ unverified = sum(1 for r in results if r["unverified"])+ panics = sum(1 for r in results if r["panic"])+ return {+ "total": len(results),+ "passed": len(results) - len(failures),+ "failures": len(failures),+ "unverified_count": unverified,+ "panics": panics,+ "p99_ms": round(p99_ms, 2),+ "mean_ms": round(statistics.mean(latencies), 2) if latencies else 0.0,+ "failed_cases": failures,+ "results": results,+ }+++def save_counterexample(ce_dir: Path, case: AdversarialCase, result: Dict[str, Any]) -> Path:+ ce_dir.mkdir(parents=True, exist_ok=True)+ sig = sha256_bytes(case.script.encode())[:10]+ stem = f"{case.category}_{case.case_id}_{sig}"+ forma_path = ce_dir / f"{stem}.forma"+ meta_path = ce_dir / f"{stem}.json"+ if not forma_path.exists():+ forma_path.write_text(case.script.rstrip() + "\n")+ meta = {+ "case_id": case.case_id,+ "category": case.category,+ "expect_uv": case.expect_uv,+ "error": result.get("error", ""),+ "panic": result.get("panic", False),+ "unverified": result.get("unverified", True),+ "ms": result.get("ms", 0.0),+ "recorded_at": utc_now_iso(),+ }+ meta_path.write_text(json.dumps(meta, indent=2))+ return forma_path+++def load_counterexample_bank(ce_dir: Path) -> List[AdversarialCase]:+ if not ce_dir.exists():+ return []+ bank: List[AdversarialCase] = []+ for fp in sorted(ce_dir.glob("*.forma")):+ mp = fp.with_suffix(".json")+ meta = json.loads(mp.read_text()) if mp.exists() else {}+ bank.append(+ AdversarialCase(+ case_id=meta.get("case_id", fp.stem),+ category=meta.get("category", "counterexample"),+ script=fp.read_text(),+ expect_uv=bool(meta.get("expect_uv", "unwrap(" in fp.read_text())),+ )+ )+ return bank+++def pick_t2_target_file(category: str, error_msg: str) -> str:+ err_l = error_msg.lower()+ if "remesh" in err_l or "voxel" in err_l:+ return "crates/forma-core/src/remesh.rs"+ if "non-manifold" in err_l or "watertight" in err_l or "invariant" in err_l:+ if "boolean" in err_l or category in ("diagonal_45_fins", "radial_fin_arrays", "micro_scale_1e4", "curved_tool_csg"):+ return "crates/forma-core/src/boolean.rs"+ return "crates/forma-core/src/invariants.rs"+ if "bevel" in err_l or "shell" in err_l or "bisect" in err_l or "loft" in err_l:+ return "crates/forma-core/src/ops.rs"+ return "crates/forma-core/src/boolean.rs"+++# ===========================================================================+# TRACK 3: Agent-Pilot Token Efficiency & 1-Shot Accuracy Autoresearch+# ===========================================================================++TRACK3_OBSERVE_SCRIPTS: List[Tuple[str, str]] = [+ (+ "flange_3op",+ """flange = box(4, 2, 0.4)+ | cut(cyl(0.5, 1))+ | cut(cyl(0.25, 1), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])+section(flange, 0.0)""",+ ),+ (+ "assembly_4part",+ """plate = box(3.0, 2.0, 0.2, z0=0)+post_l = cyl(0.2, 1.0, segs=20, center=(-1.0, 0, 0.7))+post_r = cyl(0.2, 1.0, segs=20, center=(1.0, 0, 0.7))+bar = box(2.4, 0.3, 0.15, center=(0, 0, 1.25))+clearance(post_l, post_r)""",+ ),+ (+ "gears_2part",+ """g1 = gear(16, m=0.05, h=0.2, bore=0.12)+g2 = gear(12, m=0.05, h=0.2, bore=0.10) | rot(0, 0, 15) | move(0.70, 0, 0)""",+ ),+]++ERROR_SCENT_BATTERY: List[Tuple[str, List[str], Optional[str], Tuple[str, ...]]] = [+ # (name, cli_args, stdin_or_None, expected_hint_keywords)+ ("unknown_op", ["eval", "--strict"], "a = box(1,1,1) | chamfer(all, 0.1)", ("unknown", "chamfer", "bevel")),+ ("bad_selector", ["eval", "--strict"], "a = box(1,1,1) | bevel(corners, 0.1)", ("selector", "vertical", "top_rim", "all")),+ ("bad_axis", ["eval", "--strict"], "a = cyl(1, 2, axis=w)", ("axis", "x", "y", "z")),+ ("missing_paren", ["eval", "--strict"], "a = box(1, 1, 1", ("paren", ")", "expected", "syntax", "line")),+ ("undef_var", ["eval", "--strict"], "a = foo | add(box(1,1,1))", ("unknown", "foo", "undefined", "part")),+ ("bad_topic", ["spec", "--topic", "mesh"], None, ("deform", "curves", "uv", "remesh", "scene")),+ ("zero_dim", ["eval", "--strict"], "a = box(0, 1, 1)", ("positive", "> 0", "zero", "size", "dim", "sx")),+ ("bad_kwarg", ["eval", "--strict"], "a = cyl(1, 2, radius=3)", ("radius", "unknown", "kwarg", "arg", "expected")),+]+++def probe_mcp_latency() -> Optional[float]:+ """Measure forma-mcp JSON-RPC initialize + tools/list latency if binary exists."""+ if not FORMA_MCP_BIN.exists():+ return None+ req1 = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "w4", "version": "1"}}})+ req2 = json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}})+ payload = req1 + "\n" + req2 + "\n"+ t0 = time.perf_counter()+ try:+ r = subprocess.run([str(FORMA_MCP_BIN)], input=payload, text=True, capture_output=True, timeout=10)+ ms = (time.perf_counter() - t0) * 1000.0+ if r.returncode == 0 and '"eval"' in r.stdout:+ return round(ms, 2)+ except Exception:+ pass+ return None+++def eval_track3_offline() -> Tuple[bool, Dict[str, Any]]:+ # 1. Main spec token count + latency+ t0 = time.perf_counter()+ r_spec = subprocess.run([str(FORMA_BIN), "spec"], text=True, capture_output=True, timeout=15)+ spec_ms = (time.perf_counter() - t0) * 1000.0+ if r_spec.returncode != 0:+ return False, {"error": f"forma spec failed: {r_spec.stderr[:200]}"}+ spec_text = r_spec.stdout.strip()+ spec_tokens = count_tokens(spec_text)++ # 2. Progressive topic token counts+ topic_tokens: Dict[str, int] = {}+ for topic in ("deform", "curves", "uv", "remesh", "scene"):+ rt = subprocess.run([str(FORMA_BIN), "spec", "--topic", topic], text=True, capture_output=True, timeout=15)+ if rt.returncode != 0:+ return False, {"error": f"forma spec --topic {topic} failed: {rt.stderr[:160]}"}+ topic_tokens[topic] = count_tokens(rt.stdout.strip())++ # 3. GBNF grammar size / rules / production states+ r_gbnf = subprocess.run([str(FORMA_BIN), "spec", "--gbnf"], text=True, capture_output=True, timeout=15)+ if r_gbnf.returncode != 0:+ return False, {"error": f"forma spec --gbnf failed: {r_gbnf.stderr[:160]}"}+ gbnf_text = r_gbnf.stdout+ gbnf_rules = len(re.findall(r"^[a-zA-Z0-9_-]+\s*::=", gbnf_text, re.MULTILINE))+ gbnf_alts = gbnf_text.count(" | ") + gbnf_rules++ # 4. Scene::observe verbosity & CLI eval latency+ obs_tokens_list: List[int] = []+ obs_chars_list: List[int] = []+ eval_ms_list: List[float] = []+ for name, code in TRACK3_OBSERVE_SCRIPTS:+ te0 = time.perf_counter()+ reval = subprocess.run([str(FORMA_BIN), "eval", "--strict"], input=code, text=True, capture_output=True, timeout=20)+ ems = (time.perf_counter() - te0) * 1000.0+ if reval.returncode != 0 or "WT=ok" not in reval.stdout:+ return False, {"error": f"observe probe '{name}' failed: {reval.stderr[:180]}"}+ obs_tokens_list.append(count_tokens(reval.stdout))+ obs_chars_list.append(len(reval.stdout))+ eval_ms_list.append(ems)++ # 5. Error-scent quality battery+ scent_hits = 0+ scent_concise = 0+ scent_details: Dict[str, Any] = {}+ for ename, cli_args, stdin_src, keywords in ERROR_SCENT_BATTERY:+ re_err = subprocess.run(+ [str(FORMA_BIN), *cli_args],+ input=stdin_src,+ text=True,+ capture_output=True,+ timeout=15,+ )+ msg = (re_err.stderr or re_err.stdout or "").strip()+ low = msg.lower()+ rejected = re_err.returncode != 0+ matched = rejected and any(kw in low for kw in keywords)+ toks = count_tokens(msg)+ concise = rejected and (3 <= toks <= 55)+ if matched:+ scent_hits += 1+ if concise:+ scent_concise += 1+ scent_details[ename] = {"rejected": rejected, "matched": matched, "tokens": toks}++ n_bat = len(ERROR_SCENT_BATTERY)+ error_scent_score = round(100.0 * (0.7 * (scent_hits / n_bat) + 0.3 * (scent_concise / n_bat)), 2)++ mcp_ms = probe_mcp_latency()+ mean_obs_toks = statistics.mean(obs_tokens_list)+ med_eval_ms = statistics.median(eval_ms_list)++ # Higher is better: rewards high error-scent, compact spec (~400-520 tok), concise observe, low latency+ spec_pen = max(0.0, (spec_tokens - 450) * 0.08)+ obs_pen = max(0.0, (mean_obs_toks - 120) * 0.05)+ lat_pen = 0.05 * med_eval_ms+ offline_score = round(error_scent_score + 40.0 - spec_pen - obs_pen - lat_pen, 3)++ return True, {+ "offline_score": offline_score,+ "spec_tokens": spec_tokens,+ "spec_bytes": len(spec_text.encode()),+ "spec_ms": round(spec_ms, 2),+ "topic_tokens": topic_tokens,+ "topics_total_tokens": sum(topic_tokens.values()),+ "gbnf_bytes": len(gbnf_text.encode()),+ "gbnf_rules": gbnf_rules,+ "gbnf_states": gbnf_alts,+ "observe_mean_tokens": round(mean_obs_toks, 1),+ "observe_mean_chars": round(statistics.mean(obs_chars_list), 1),+ "cli_eval_median_ms": round(med_eval_ms, 2),+ "mcp_probe_ms": mcp_ms,+ "error_scent_score": error_scent_score,+ "error_scent_hits": f"{scent_hits}/{n_bat}",+ "error_scent_details": scent_details,+ }+++def eval_track3_online_1shot(api_key: str, model: str, max_tasks: int = 5) -> Tuple[bool, Dict[str, Any]]:+ """Evaluate 1-shot Forma-Pipe accuracy (WT=ok + IoU) per spec token on eval_complex_abc tasks."""+ sys.path.insert(0, str(ROOT / "bench"))+ try:+ import eval_complex_abc as abc_mod # type: ignore+ except Exception as exc:+ return False, {"error": f"could not import eval_complex_abc: {exc}"}++ r_spec = subprocess.run([str(FORMA_BIN), "spec"], text=True, capture_output=True, timeout=15)+ if r_spec.returncode != 0:+ return False, {"error": "forma spec failed"}+ spec_text = r_spec.stdout.strip()+ spec_tokens = count_tokens(spec_text)++ tasks = abc_mod.COMPLEX_TASKS[:max_tasks]+ wt_hits = 0+ ious: List[float] = []+ comp_tokens: List[int] = []+ per_task: Dict[str, Any] = {}++ with tempfile.TemporaryDirectory() as td:+ tdp = Path(td)+ for task in tasks:+ # Build reference mesh on the fly+ ref_glb = tdp / f"{task.id}_ref.glb"+ r_ref = subprocess.run(+ [str(FORMA_BIN), "eval", "--strict", "--out", str(ref_glb)],+ input=task.ref_forma,+ text=True,+ capture_output=True,+ timeout=30,+ )+ if r_ref.returncode != 0:+ continue++ sys_prompt = (+ "You are an expert 3D CAD modeling agent using Forma-Pipe.\n"+ "Output ONLY a single fenced ```forma code block that builds the requested watertight solid.\n\n"+ + spec_text+ )+ body = json.dumps(+ {+ "model": model,+ "messages": [+ {"role": "system", "content": sys_prompt},+ {"role": "user", "content": task.prompt},+ ],+ "temperature": 0.0,+ "max_tokens": 1200,+ }+ ).encode()+ req = urllib.request.Request(+ "https://openrouter.ai/api/v1/chat/completions",+ data=body,+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/wrong-nebula/forma",+ "X-Title": "forma-w4-track3",+ },+ method="POST",+ )+ try:+ with urllib.request.urlopen(req, timeout=90) as resp:+ data = json.loads(resp.read().decode())+ reply = data["choices"][0]["message"]["content"] or ""+ except Exception as exc:+ per_task[task.id] = {"wt_ok": False, "iou": 0.0, "error": str(exc)[:120]}+ ious.append(0.0)+ continue++ comp_tokens.append(count_tokens(reply))+ m_code = re.search(r"```(?:forma|forma-pipe|pipe)?\s*\n(.*?)```", reply, re.DOTALL)+ code = (m_code.group(1) if m_code else reply).strip()++ cand_glb = tdp / f"{task.id}_cand.glb"+ r_c = subprocess.run(+ [str(FORMA_BIN), "eval", "--strict", "--out", str(cand_glb)],+ input=code,+ text=True,+ capture_output=True,+ timeout=30,+ )+ wt_ok = r_c.returncode == 0 and "WT=ok" in r_c.stdout and "NM=0" in r_c.stdout+ iou = 0.0+ if wt_ok:+ wt_hits += 1+ try:+ vr = abc_mod.verify_mesh(str(cand_glb), str(ref_glb), task.expected_bbox)+ iou = float(getattr(vr, "iou", 0.0) or 0.0)+ except Exception:+ # Fallback volume similarity proxy if trimesh/scipy missing+ ref_parts = parse_eval_parts(r_ref.stdout)+ cand_parts = parse_eval_parts(r_c.stdout)+ if ref_parts and cand_parts:+ rv = ref_parts[-1]["vol"]+ cv = cand_parts[-1]["vol"]+ iou = max(0.0, min(rv, cv) / max(rv, cv, 1e-9))+ ious.append(iou)+ per_task[task.id] = {"wt_ok": wt_ok, "iou": round(iou, 4)}++ n = max(1, len(tasks))+ wt_rate = wt_hits / n+ mean_iou = statistics.mean(ious) if ious else 0.0+ # Objective: 1-shot (WT=ok + IoU) per 500 spec tokens+ quality = 0.40 * wt_rate + 0.60 * mean_iou+ eff_score = round((quality * 100.0) / max(spec_tokens / 500.0, 0.5), 3)+ return True, {+ "online_score": eff_score,+ "wt_rate": round(wt_rate, 3),+ "mean_iou": round(mean_iou, 4),+ "spec_tokens": spec_tokens,+ "mean_completion_tokens": round(statistics.mean(comp_tokens), 1) if comp_tokens else 0.0,+ "per_task": per_task,+ }+++# ===========================================================================+# Checkpointing, Patch Archiving, Reporting, Charts & Google Drive Mirror+# ===========================================================================++class CheckpointManager:+ def __init__(+ self,+ out_dir: Path,+ log_path: Path,+ patches_dir: Path,+ drive_dir: Optional[Path],+ dry_run: bool = False,+ ):+ self.out_dir = out_dir+ self.log_path = log_path+ self.patches_dir = patches_dir+ self.drive_dir = drive_dir+ self.dry_run = dry_run+ self.state_path = out_dir / "w4_state.json"+ self.summary_path = out_dir / "w4_summary.json"+ self.report_path = out_dir / "w4_report.md"+ self.chart_path = out_dir / "w4_progression.png"+ self.ce_dir = out_dir / "counterexamples"+ self.tar_path = out_dir.parent / "forma_w4_winners.tar.gz"+ self.log_rows: List[Dict[str, Any]] = []+ self.state: Dict[str, Any] = {+ "started_at": utc_now_iso(),+ "updated_at": utc_now_iso(),+ "completed_tracks": [],+ "track1": {"round": 0, "plateau": 0, "kept_count": 0, "baseline": None, "best": None},+ "track2": {"round": 0, "plateau": 0, "kept_count": 0, "baseline": None, "best": None, "known_ce_sigs": []},+ "track3": {"round": 0, "plateau": 0, "kept_count": 0, "baseline": None, "best": None},+ "final_gate": {},+ }++ def restore_if_resume(self) -> bool:+ """Restore checkpoint state & winning patches from out_dir or drive_dir."""+ src_dir = None+ if self.state_path.exists():+ src_dir = self.out_dir+ elif self.drive_dir and (self.drive_dir / "w4_state.json").exists():+ src_dir = self.drive_dir+ self.out_dir.mkdir(parents=True, exist_ok=True)+ for fname in ("w4_state.json", "w4_summary.json", "w4_autoresearch_log.jsonl", "w4_report.md"):+ sp = src_dir / fname+ if sp.exists():+ shutil.copy2(sp, self.out_dir / fname)+ if (src_dir / "counterexamples").exists():+ shutil.copytree(src_dir / "counterexamples", self.ce_dir, dirs_exist_ok=True)+ if (src_dir / "w4_patches").exists():+ shutil.copytree(src_dir / "w4_patches", self.out_dir / "w4_patches", dirs_exist_ok=True)+ self.patches_dir.mkdir(parents=True, exist_ok=True)+ shutil.copytree(src_dir / "w4_patches", self.patches_dir, dirs_exist_ok=True)++ if src_dir is None or not self.state_path.exists():+ return False++ self.state = json.loads(self.state_path.read_text())+ local_log = self.out_dir / "w4_autoresearch_log.jsonl"+ if local_log.exists():+ self.log_rows = [json.loads(l) for l in local_log.read_text().splitlines() if l.strip()]+ elif self.log_path.exists():+ self.log_rows = [json.loads(l) for l in self.log_path.read_text().splitlines() if l.strip()]++ # If workspace is clean (e.g. fresh Colab VM after disconnect), re-apply cumulative winning patch+ cur_diff = subprocess.run(["git", "diff"], cwd=str(ROOT), text=True, capture_output=True).stdout+ cum_patch = self.out_dir / "w4_patches" / "w4_all_winners.patch"+ if not cur_diff.strip() and cum_patch.exists() and cum_patch.read_text().strip():+ ap = subprocess.run(+ ["git", "apply", "--whitespace=nowarn", str(cum_patch)],+ cwd=str(ROOT),+ text=True,+ capture_output=True,+ )+ if ap.returncode == 0:+ print(f"[RESUME] Re-applied winning cumulative patch from {cum_patch}", flush=True)+ else:+ print(f"[RESUME] Warning: could not re-apply cumulative patch cleanly: {ap.stderr[:180]}", flush=True)+ return True++ def append_log(self, row: Dict[str, Any]) -> None:+ row.setdefault("ts", utc_now_iso())+ self.log_rows.append(row)+ if self.dry_run:+ return+ self.out_dir.mkdir(parents=True, exist_ok=True)+ line = json.dumps(row) + "\n"+ with (self.out_dir / "w4_autoresearch_log.jsonl").open("a") as f:+ f.write(line)+ self.log_path.parent.mkdir(parents=True, exist_ok=True)+ with self.log_path.open("a") as f:+ f.write(line)++ def save_winning_patch(self, track: int, round_idx: int, label: str) -> None:+ if self.dry_run:+ return+ diff = subprocess.run(["git", "diff"], cwd=str(ROOT), text=True, capture_output=True).stdout+ if not diff.strip():+ return+ for pdir in (self.patches_dir, self.out_dir / "w4_patches"):+ pdir.mkdir(parents=True, exist_ok=True)+ (pdir / "w4_all_winners.patch").write_text(diff)+ fname = f"t{track}_r{round_idx:03d}_{slugify(label)}.patch"+ (pdir / fname).write_text(diff)++ def save_and_mirror(self, build_tar: bool = False) -> None:+ if self.dry_run:+ return+ self.out_dir.mkdir(parents=True, exist_ok=True)+ self.state["updated_at"] = utc_now_iso()+ self.state_path.write_text(json.dumps(self.state, indent=2))+ self.summary_path.write_text(json.dumps(self.build_summary(), indent=2))+ self.report_path.write_text(self.build_markdown_report())+ if build_tar:+ self.write_tarball()+ self.mirror_to_drive()++ def build_summary(self) -> Dict[str, Any]:+ return {+ "wave": 4,+ "started_at": self.state["started_at"],+ "updated_at": self.state["updated_at"],+ "completed_tracks": self.state["completed_tracks"],+ "track1": self.state["track1"],+ "track2": {k: v for k, v in self.state["track2"].items() if k != "known_ce_sigs"},+ "track3": self.state["track3"],+ "counterexample_count": len(list(self.ce_dir.glob("*.forma"))) if self.ce_dir.exists() else 0,+ "final_gate": self.state.get("final_gate", {}),+ "total_logged_rounds": len(self.log_rows),+ }++ def build_markdown_report(self) -> str:+ s = self.build_summary()+ lines = [+ "# Forma Wave 4 Long-Plateau Autoresearch Report",+ "",+ f"- **Started:** `{s['started_at']}`",+ f"- **Updated:** `{s['updated_at']}`",+ f"- **Logged rounds:** `{s['total_logged_rounds']}`",+ f"- **Counterexamples recorded:** `{s['counterexample_count']}`",+ "",+ "## Track Summaries",+ "",+ "| Track | Metric | Baseline | Final Best | Kept Wins | Rounds |",+ "|---|---|---:|---:|---:|---:|",+ ]+ t1 = s["track1"]+ if t1["baseline"]:+ b1 = t1["baseline"]+ f1 = t1["best"] or b1+ lines.append(+ f"| Track 1 (Kernel Speed + 10-Part Session) | Composite ms (suite / 10-part) "+ f"| `{b1['composite_ms']:.2f}` (`{b1['suite_ms']:.1f}` / `{b1['session_ms']:.1f}`) "+ f"| `{f1['composite_ms']:.2f}` (`{f1['suite_ms']:.1f}` / `{f1['session_ms']:.1f}`) "+ f"| {t1['kept_count']} | {t1['round']} |"+ )+ t2 = s["track2"]+ if t2["baseline"]:+ b2 = t2["baseline"]+ f2 = t2["best"] or b2+ lines.append(+ f"| Track 2 (Adversarial Soundness & Fuzz) | Failures / Unverified / Panics / p99 ms "+ f"| `{b2['failures']}/{b2['unverified_count']}/{b2['panics']}` (`{b2['p99_ms']:.1f}ms`) "+ f"| `{f2['failures']}/{f2['unverified_count']}/{f2['panics']}` (`{f2['p99_ms']:.1f}ms`) "+ f"| {t2['kept_count']} | {t2['round']} |"+ )+ t3 = s["track3"]+ if t3["baseline"]:+ b3 = t3["baseline"]+ f3 = t3["best"] or b3+ lines.append(+ f"| Track 3 (Agent Token Efficiency & 1-Shot) | Score / Spec Tok / Error-Scent "+ f"| `{b3.get('score', 0):.2f}` (`{b3['offline']['spec_tokens']}t`, `{b3['offline']['error_scent_score']:.1f}`) "+ f"| `{f3.get('score', 0):.2f}` (`{f3['offline']['spec_tokens']}t`, `{f3['offline']['error_scent_score']:.1f}`) "+ f"| {t3['kept_count']} | {t3['round']} |"+ )++ kept = [r for r in self.log_rows if r.get("kept")]+ lines.extend(["", "## Verified Kept Improvements", ""])+ if not kept:+ lines.append("_No mutations beat the strict verification gates yet._")+ else:+ for r in kept:+ lines.append(f"- **[T{r['track']} R{r['round']:03d}]** `{r['label']}` — {r['reason']}")++ fg = s.get("final_gate", {})+ if fg:+ lines.extend(["", "## Final Verification Gate", ""])+ for k, v in fg.items():+ lines.append(f"- **{k}:** `{v}`")+ lines.append("")+ return "\n".join(lines)++ def render_charts(self) -> Optional[Path]:+ if self.dry_run or not self.log_rows:+ return None+ try:+ import matplotlib # type: ignore++ matplotlib.use("Agg")+ import matplotlib.pyplot as plt # type: ignore+ except Exception:+ return None++ t1_rows = [r for r in self.log_rows if r.get("track") == 1]+ t2_rows = [r for r in self.log_rows if r.get("track") == 2]+ t3_rows = [r for r in self.log_rows if r.get("track") == 3]++ fig, axes = plt.subplots(1, 3, figsize=(16, 4.6), dpi=130)+ fig.suptitle("Forma Wave 4 Long-Plateau Autoresearch Progression", fontsize=13, fontweight="bold")++ # Track 1+ ax = axes[0]+ if t1_rows:+ xs = [r["round"] for r in t1_rows]+ ys = [r["best"] for r in t1_rows]+ kx = [r["round"] for r in t1_rows if r.get("kept")]+ ky = [r["best"] for r in t1_rows if r.get("kept")]+ ax.plot(xs, ys, color="#2563eb", lw=2, label="Best Composite ms")+ if kx:+ ax.scatter(kx, ky, color="#10b981", s=45, zorder=5, label="Kept Speedups")+ ax.set_title("Track 1: Kernel + 10-Part Speed (lower=better)")+ ax.set_xlabel("Round")+ ax.set_ylabel("Composite ms")+ ax.grid(alpha=0.3)+ ax.legend(loc="best", fontsize=8)++ # Track 2+ ax = axes[1]+ if t2_rows:+ xs = [r["round"] for r in t2_rows]+ ys = [r.get("bank_failures", r.get("best", 0)) for r in t2_rows]+ kx = [r["round"] for r in t2_rows if r.get("kept")]+ ky = [r.get("bank_failures", r.get("best", 0)) for r in t2_rows if r.get("kept")]+ ax.plot(xs, ys, color="#dc2626", lw=2, label="Counterexample Bank Failures")+ if kx:+ ax.scatter(kx, ky, color="#10b981", s=45, zorder=5, label="Verified Fixes")+ ax.set_title("Track 2: Adversarial Soundness (lower=better)")+ ax.set_xlabel("Round")+ ax.set_ylabel("Active Failures")+ ax.grid(alpha=0.3)+ ax.legend(loc="best", fontsize=8)++ # Track 3+ ax = axes[2]+ if t3_rows:+ xs = [r["round"] for r in t3_rows]+ ys = [r["best"] for r in t3_rows]+ kx = [r["round"] for r in t3_rows if r.get("kept")]+ ky = [r["best"] for r in t3_rows if r.get("kept")]+ ax.plot(xs, ys, color="#7c3aed", lw=2, label="Best Agent Score")+ if kx:+ ax.scatter(kx, ky, color="#10b981", s=45, zorder=5, label="Kept Improvements")+ ax.set_title("Track 3: Token Eff & 1-Shot (higher=better)")+ ax.set_xlabel("Round")+ ax.set_ylabel("Score")+ ax.grid(alpha=0.3)+ ax.legend(loc="best", fontsize=8)++ plt.tight_layout()+ self.out_dir.mkdir(parents=True, exist_ok=True)+ fig.savefig(self.chart_path)+ plt.close(fig)+ return self.chart_path++ def write_tarball(self) -> Path:+ self.out_dir.mkdir(parents=True, exist_ok=True)+ with tarfile.open(self.tar_path, "w:gz") as tf:+ tf.add(self.out_dir, arcname="forma_w4_out")+ return self.tar_path++ def mirror_to_drive(self) -> None:+ if self.dry_run or not self.drive_dir:+ return+ try:+ self.drive_dir.mkdir(parents=True, exist_ok=True)+ for fname in (+ "w4_state.json",+ "w4_summary.json",+ "w4_autoresearch_log.jsonl",+ "w4_report.md",+ "w4_progression.png",+ ):+ sp = self.out_dir / fname+ if sp.exists():+ shutil.copy2(sp, self.drive_dir / fname)+ if (self.out_dir / "w4_patches").exists():+ shutil.copytree(self.out_dir / "w4_patches", self.drive_dir / "w4_patches", dirs_exist_ok=True)+ if self.ce_dir.exists():+ shutil.copytree(self.ce_dir, self.drive_dir / "counterexamples", dirs_exist_ok=True)+ if self.tar_path.exists():+ shutil.copy2(self.tar_path, self.drive_dir / self.tar_path.name)+ except Exception as exc:+ print(f"[DRIVE] Warning: mirror failed: {exc}", flush=True)+++# ===========================================================================+# Track Orchestrators+# ===========================================================================++def run_track1(+ args: argparse.Namespace,+ ckpt: CheckpointManager,+ rng: random.Random,+ api_key: Optional[str],+ deadline: float,+ slice_rounds: Optional[int] = None,+) -> bool:+ t1 = ckpt.state["track1"]+ # Auto-reopen if resumed with higher round/plateau limits+ if 1 in ckpt.state["completed_tracks"] and t1["plateau"] < args.t1_plateau and t1["round"] < args.t1_max_rounds:+ ckpt.state["completed_tracks"] = [x for x in ckpt.state["completed_tracks"] if x != 1]+ print(+ f"[T1 RESUME] Re-opening Track 1 for extended run "+ f"(round {t1['round']}/{args.t1_max_rounds}, plateau {t1['plateau']}/{args.t1_plateau}).",+ flush=True,+ )++ if 1 in ckpt.state["completed_tracks"] and not args.dry_run:+ return False++ slice_tag = f" | Slice={slice_rounds}" if slice_rounds else ""+ print("\n======================================================================", flush=True)+ print(" TRACK 1: KERNEL SPEED & 10-PART SESSION AUTORESEARCH", flush=True)+ print(+ f" Round={t1['round']}/{args.t1_max_rounds} | Plateau={t1['plateau']}/{args.t1_plateau} "+ f"| MinSpeedup={MIN_SPEEDUP_RATIO*100:.1f}%{slice_tag}",+ flush=True,+ )+ print("======================================================================", flush=True)++ if t1["baseline"] is None:+ ok, base = eval_track1(repeats=2)+ if not ok:+ raise RuntimeError(f"Track 1 baseline failed: {base}")+ t1["baseline"] = base+ t1["best"] = base+ ckpt.save_and_mirror()+ else:+ base = t1["baseline"]++ best = t1["best"] or base+ print(+ f"[T1 BASE] composite={base['composite_ms']:.2f}ms | perf_bench={base['suite_ms']:.2f}ms | "+ f"10-part={base['session_ms']:.2f}ms | GLB={base['session']['glb_sha256'][:10]} (det=OK)",+ flush=True,+ )++ if args.dry_run:+ matched = 0+ for knob in TRACK1_KNOBS:+ p = ROOT / knob.rel_file+ if p.exists() and re.search(knob.pattern, p.read_text()):+ matched += 1+ else:+ print(f" [WARN] Knob regex missed: {knob.name} in {knob.rel_file}", flush=True)+ print(f"[T1 DRY-RUN] Matched {matched}/{len(TRACK1_KNOBS)} tunable kernel knobs.", flush=True)+ return False++ history: List[str] = list(t1.get("history", []))[-24:]+ slice_done = 0+ while (+ t1["plateau"] < args.t1_plateau+ and t1["round"] < args.t1_max_rounds+ and time.perf_counter() < deadline+ and (slice_rounds is None or slice_done < slice_rounds)+ ):+ t1["round"] += 1+ slice_done += 1+ r_idx = t1["round"]+ # Escalate LLM cadence during long plateaus to escape local optima+ llm_period = 2 if t1["plateau"] >= 10 else 3+ use_llm = bool(api_key) and (r_idx % llm_period == 0)+ target_path: Optional[Path] = None+ new_src: Optional[str] = None+ label = ""++ if use_llm and api_key:+ rel_file = TRACK1_LLM_FILES[(r_idx // llm_period - 1) % len(TRACK1_LLM_FILES)]+ target_path = ROOT / rel_file+ metrics_str = (+ f"composite_ms={best['composite_ms']:.2f}ms, perf_bench={best['suite_ms']:.2f}ms, "+ f"session_10part={best['session_ms']:.2f}ms, render_512px={best['perf_bench'].get('render_us', 0):.1f}us"+ )+ try:+ hyp, new_src = propose_llm_patch(+ api_key=api_key,+ model=args.model,+ rel_file=rel_file,+ src=target_path.read_text(),+ objective=(+ "Reduce perf_bench TOTAL SUITE SCORE and/or 10-part session export latency by >= 1.5% "+ "while preserving 100% deterministic, watertight (WT=ok NM=0), exact geometry."+ ),+ metrics_summary=metrics_str,+ history=history,+ )+ label = f"llm({Path(rel_file).stem}): {hyp[:42]}"+ except Exception as exc:+ label = f"llm_err({Path(rel_file).stem})"+ reason = f"LLM API error: {str(exc)[:120]}"+ t1["plateau"] += 1+ ckpt.append_log({"track": 1, "round": r_idx, "label": label, "kept": False, "best": best["composite_ms"], "reason": reason})+ ckpt.save_and_mirror()+ print(f"[T1 R{r_idx:03d}] SKIP | {label:32s} | {reason}", flush=True)+ continue+ else:+ if t1["plateau"] < 10:+ scale = 0.65+ elif t1["plateau"] < 25:+ scale = 1.25+ elif t1["plateau"] < 40:+ scale = 1.85+ else:+ scale = 2.40+ target_path, new_src, desc = mutate_track1_knob(rng, scale)+ label = f"evo({desc[:32]})"++ if not target_path or not new_src:+ t1["plateau"] += 1+ ckpt.append_log({"track": 1, "round": r_idx, "label": label or "noop", "kept": False, "best": best["composite_ms"], "reason": "no valid mutation"})+ ckpt.save_and_mirror()+ continue++ kept = False+ reason = ""+ with FileTransaction([target_path]) as tx:+ target_path.write_text(new_src)+ ok_b, err_b = build_forma()+ if not ok_b:+ reason = f"compile err: {(err_b.splitlines()[-1] if err_b else 'build failed')[:100]}"+ else:+ ok_e, cand = eval_track1(repeats=2, baseline=base)+ if not ok_e:+ reason = f"gate failed: {cand.get('error', 'unknown')[:120]}"+ elif cand["composite_ms"] <= best["composite_ms"] * (1.0 - MIN_SPEEDUP_RATIO):+ # Confirmation run to eliminate timing noise!+ ok_e2, cand2 = eval_track1(repeats=3, baseline=base)+ if ok_e2 and cand2["composite_ms"] <= best["composite_ms"] * (1.0 - MIN_SPEEDUP_RATIO):+ gain_pct = (1.0 - cand2["composite_ms"] / best["composite_ms"]) * 100.0+ kept = True+ tx.commit()+ reason = (+ f"KEEP! {best['composite_ms']:.2f}ms -> {cand2['composite_ms']:.2f}ms "+ f"(-{gain_pct:.2f}% | suite {cand2['suite_ms']:.1f}ms | 10p {cand2['session_ms']:.1f}ms | det=OK)"+ )+ best = cand2+ t1["best"] = best+ t1["kept_count"] += 1+ t1["plateau"] = 0+ ckpt.save_winning_patch(1, r_idx, label)+ else:+ c2_ms = cand2.get("composite_ms", -1) if ok_e2 else -1+ reason = f"unconfirmed 3x ({c2_ms}ms vs {best['composite_ms']:.2f}ms)"+ else:+ reason = (+ f"no >=1.5% gain ({cand['composite_ms']:.2f}ms vs {best['composite_ms']:.2f}ms; "+ f"suite {cand['suite_ms']:.1f}ms, 10p {cand['session_ms']:.1f}ms)"+ )++ if not kept:+ t1["plateau"] += 1+ history.append(f"R{r_idx} {'KEEP' if kept else 'REVERT'} {label}: {reason}")+ t1["history"] = history[-24:]+ ckpt.append_log(+ {+ "track": 1,+ "round": r_idx,+ "label": label,+ "kept": kept,+ "best": best["composite_ms"],+ "plateau": t1["plateau"],+ "reason": reason,+ }+ )+ ckpt.save_and_mirror()+ print(+ f"[T1 R{r_idx:03d}] {'KEEP ' if kept else 'REVRT'} | {label:34s} | {reason} "+ f"(plateau {t1['plateau']}/{args.t1_plateau})",+ flush=True,+ )++ finished = t1["plateau"] >= args.t1_plateau or t1["round"] >= args.t1_max_rounds+ if finished and 1 not in ckpt.state["completed_tracks"]:+ ckpt.state["completed_tracks"].append(1)+ ckpt.save_and_mirror()+ return not finished and time.perf_counter() < deadline+++def run_track2(+ args: argparse.Namespace,+ ckpt: CheckpointManager,+ rng: random.Random,+ api_key: Optional[str],+ deadline: float,+ slice_rounds: Optional[int] = None,+) -> bool:+ t2 = ckpt.state["track2"]+ if 2 in ckpt.state["completed_tracks"] and t2["plateau"] < args.t2_plateau and t2["round"] < args.t2_max_rounds:+ ckpt.state["completed_tracks"] = [x for x in ckpt.state["completed_tracks"] if x != 2]+ print(+ f"[T2 RESUME] Re-opening Track 2 for extended run "+ f"(round {t2['round']}/{args.t2_max_rounds}, plateau {t2['plateau']}/{args.t2_plateau}).",+ flush=True,+ )++ if 2 in ckpt.state["completed_tracks"] and not args.dry_run:+ return False++ slice_tag = f" | Slice={slice_rounds}" if slice_rounds else ""+ print("\n======================================================================", flush=True)+ print(" TRACK 2: ADVERSARIAL GEOMETRY SOUNDNESS & FUZZ AUTORESEARCH (CEGAR)", flush=True)+ print(+ f" Round={t2['round']}/{args.t2_max_rounds} | Plateau={t2['plateau']}/{args.t2_plateau} "+ f"| FuzzPerRound={args.t2_fuzz_per_round}{slice_tag}",+ flush=True,+ )+ print("======================================================================", flush=True)++ known_sigs = set(t2.get("known_ce_sigs", []))++ if t2["baseline"] is None:+ base_res = eval_adversarial_suite(CANONICAL_ADVERSARIAL_SUITE)+ # Compact baseline snapshot+ base_snap = {k: v for k, v in base_res.items() if k != "results"}+ t2["baseline"] = base_snap+ t2["best"] = base_snap+ if not args.dry_run:+ for fc in base_res["failed_cases"]:+ orig = next((c for c in CANONICAL_ADVERSARIAL_SUITE if c.case_id == fc["case_id"]), None)+ if orig:+ mini = minimize_counterexample(orig)+ sig = sha256_bytes(mini.script.encode())[:10]+ known_sigs.add(sig)+ save_counterexample(ckpt.ce_dir, mini, fc)+ t2["known_ce_sigs"] = sorted(known_sigs)+ ckpt.save_and_mirror()+ else:+ base_snap = t2["baseline"]++ best_snap = t2["best"] or base_snap+ print(+ f"[T2 BASE] passed={base_snap['passed']}/{base_snap['total']} | failures={base_snap['failures']} | "+ f"unverified={base_snap['unverified_count']} | panics={base_snap['panics']} | p99={base_snap['p99_ms']:.1f}ms",+ flush=True,+ )++ if args.dry_run:+ if base_snap["failed_cases"]:+ for fc in base_snap["failed_cases"]:+ print(f" [T2 FAIL] {fc['case_id']} ({fc['category']}): {fc['error']}", flush=True)+ print("[T2 DRY-RUN] Canonical 6-family adversarial suite verified.", flush=True)+ return False++ history: List[str] = list(t2.get("history", []))[-24:]+ slice_done = 0+ while (+ t2["plateau"] < args.t2_plateau+ and t2["round"] < args.t2_max_rounds+ and time.perf_counter() < deadline+ and (slice_rounds is None or slice_done < slice_rounds)+ ):+ t2["round"] += 1+ slice_done += 1+ r_idx = t2["round"]++ # Step A: Evolutionary fuzz generation to hunt new counterexamples+ fuzz_cases = generate_mutated_adversarial_cases(rng, r_idx, count=args.t2_fuzz_per_round)+ fuzz_res = eval_adversarial_suite(fuzz_cases)+ new_ces = 0+ for fc in fuzz_res["failed_cases"]:+ orig = next((c for c in fuzz_cases if c.case_id == fc["case_id"]), None)+ if not orig:+ continue+ mini = minimize_counterexample(orig)+ sig = sha256_bytes(mini.script.encode())[:10]+ if sig not in known_sigs:+ known_sigs.add(sig)+ save_counterexample(ckpt.ce_dir, mini, fc)+ new_ces += 1+ print(+ f" [CEGAR NEW] {mini.category}/{mini.case_id} ({sig}): {fc['error'][:110]}",+ flush=True,+ )+ t2["known_ce_sigs"] = sorted(known_sigs)++ # Evaluate active counterexample bank+ ce_bank = load_counterexample_bank(ckpt.ce_dir)+ bank_res = eval_adversarial_suite(ce_bank) if ce_bank else {"failures": 0, "unverified_count": 0, "panics": 0, "p99_ms": fuzz_res["p99_ms"], "failed_cases": []}+ active_failures = bank_res["failures"]++ kept = False+ label = f"fuzz_batch(new_ce={new_ces}, bank={active_failures})"+ reason = (+ f"fuzz {fuzz_res['passed']}/{fuzz_res['total']} ok, p99={fuzz_res['p99_ms']:.1f}ms, "+ f"bank_fail={active_failures}, new_ce={new_ces}"+ )++ # Step B: CEGAR LLM patch repair when OPENROUTER_API_KEY is set and active counterexamples exist+ if api_key and bank_res["failed_cases"]:+ # Rotate across all active counterexamples instead of getting stuck on failed_cases[0]+ top_fail = bank_res["failed_cases"][(r_idx - 1) % len(bank_res["failed_cases"])]+ top_case = next((c for c in ce_bank if c.case_id == top_fail["case_id"]), ce_bank[0])+ rel_file = pick_t2_target_file(top_case.category, top_fail.get("error", ""))+ target_path = ROOT / rel_file+ label = f"cegar_fix({Path(rel_file).stem}:{top_case.category[:14]})"+ metrics_str = (+ f"Active counterexample failures={active_failures}/{len(ce_bank)}, "+ f"target failure: {top_case.case_id} ({top_case.category}) -> {top_fail.get('error')}\n"+ f"Minimal failing Forma-Pipe script:\n{top_case.script}"+ )+ try:+ hyp, new_src = propose_llm_patch(+ api_key=api_key,+ model=args.model,+ rel_file=rel_file,+ src=target_path.read_text(),+ objective=(+ "Fix the geometry/manifold soundness failure on the minimal counterexample "+ "without breaking any existing tests or introducing non-determinism."+ ),+ metrics_summary=metrics_str,+ history=history,+ )+ except Exception as exc:+ hyp, new_src = "llm_err", None+ reason = f"LLM API error: {str(exc)[:110]}"++ if new_src:+ with FileTransaction([target_path]) as tx:+ target_path.write_text(new_src)+ ok_b, err_b = build_forma()+ if not ok_b:+ reason = f"compile err: {(err_b.splitlines()[-1] if err_b else 'err')[:95]}"+ else:+ new_bank_res = eval_adversarial_suite(ce_bank)+ new_canon_res = eval_adversarial_suite(CANONICAL_ADVERSARIAL_SUITE)+ if (+ new_bank_res["failures"] < active_failures+ and new_canon_res["failures"] <= best_snap["failures"]+ and new_canon_res["panics"] == 0+ ):+ ok_t, out_t = run_rust_tests("forma-core")+ if ok_t:+ kept = True+ tx.commit()+ reason = (+ f"KEEP CEGAR FIX! bank {active_failures}->{new_bank_res['failures']} | "+ f"canon {new_canon_res['passed']}/{new_canon_res['total']} | "+ f"forma-core tests PASS ({hyp[:55]})"+ )+ active_failures = new_bank_res["failures"]+ best_snap = {k: v for k, v in new_canon_res.items() if k != "results"}+ t2["best"] = best_snap+ t2["kept_count"] += 1+ t2["plateau"] = 0+ ckpt.save_winning_patch(2, r_idx, label)+ else:+ reason = f"forma-core test gate failed: {out_t.splitlines()[-1][:90]}"+ else:+ reason = (+ f"fix did not strictly reduce failures "+ f"(bank {new_bank_res['failures']} vs {active_failures}, canon_fail={new_canon_res['failures']})"+ )++ if kept or new_ces > 0:+ t2["plateau"] = 0+ else:+ t2["plateau"] += 1++ history.append(f"R{r_idx} {'KEEP' if kept else 'SCAN'} {label}: {reason}")+ t2["history"] = history[-24:]+ ckpt.append_log(+ {+ "track": 2,+ "round": r_idx,+ "label": label,+ "kept": kept,+ "best": best_snap["failures"],+ "bank_failures": active_failures,+ "new_counterexamples": new_ces,+ "p99_ms": fuzz_res["p99_ms"],+ "plateau": t2["plateau"],+ "reason": reason,+ }+ )+ ckpt.save_and_mirror()+ print(+ f"[T2 R{r_idx:03d}] {'KEEP ' if kept else ('NEWCE' if new_ces > 0 else 'CLEAN')} | "+ f"{label:34s} | {reason} (plateau {t2['plateau']}/{args.t2_plateau})",+ flush=True,+ )++ finished = t2["plateau"] >= args.t2_plateau or t2["round"] >= args.t2_max_rounds+ if finished and 2 not in ckpt.state["completed_tracks"]:+ ckpt.state["completed_tracks"].append(2)+ ckpt.save_and_mirror()+ return not finished and time.perf_counter() < deadline+++def run_track3(+ args: argparse.Namespace,+ ckpt: CheckpointManager,+ rng: random.Random,+ api_key: Optional[str],+ deadline: float,+ slice_rounds: Optional[int] = None,+) -> bool:+ t3 = ckpt.state["track3"]+ if 3 in ckpt.state["completed_tracks"] and api_key and t3["plateau"] < args.t3_plateau and t3["round"] < args.t3_max_rounds:+ ckpt.state["completed_tracks"] = [x for x in ckpt.state["completed_tracks"] if x != 3]+ print(+ f"[T3 RESUME] Re-opening Track 3 for extended run "+ f"(round {t3['round']}/{args.t3_max_rounds}, plateau {t3['plateau']}/{args.t3_plateau}).",+ flush=True,+ )++ if 3 in ckpt.state["completed_tracks"] and not args.dry_run:+ return False++ slice_tag = f" | Slice={slice_rounds}" if slice_rounds else ""+ print("\n======================================================================", flush=True)+ print(" TRACK 3: AGENT-PILOT TOKEN EFFICIENCY & 1-SHOT ACCURACY AUTORESEARCH", flush=True)+ print(+ f" Round={t3['round']}/{args.t3_max_rounds} | Plateau={t3['plateau']}/{args.t3_plateau}{slice_tag}",+ flush=True,+ )+ print("======================================================================", flush=True)++ if t3["baseline"] is None:+ ok_off, off = eval_track3_offline()+ if not ok_off:+ raise RuntimeError(f"Track 3 offline baseline failed: {off}")+ online = None+ if api_key and not args.dry_run:+ ok_on, on_res = eval_track3_online_1shot(api_key, args.model, max_tasks=5)+ if ok_on:+ online = on_res+ score = (online["online_score"] + 0.25 * off["offline_score"]) if online else off["offline_score"]+ base = {"score": round(score, 3), "offline": off, "online": online}+ t3["baseline"] = base+ t3["best"] = base+ ckpt.save_and_mirror()+ else:+ base = t3["baseline"]++ best = t3["best"] or base+ bo = base["offline"]+ print(+ f"[T3 BASE] score={base['score']:.2f} | spec={bo['spec_tokens']}tok ({bo['spec_bytes']}B) | "+ f"topics={bo['topics_total_tokens']}tok | observe={bo['observe_mean_tokens']:.1f}tok | "+ f"gbnf={bo['gbnf_rules']} rules/{bo['gbnf_states']} states | "+ f"err_scent={bo['error_scent_score']:.1f} ({bo['error_scent_hits']}) | eval={bo['cli_eval_median_ms']:.1f}ms",+ flush=True,+ )+ if base.get("online"):+ bon = base["online"]+ print(+ f"[T3 BASE ONLINE] 1-shot WT={bon['wt_rate']*100:.1f}% | mean_IoU={bon['mean_iou']:.3f} | "+ f"eff_score={bon['online_score']:.2f}",+ flush=True,+ )++ if args.dry_run:+ print("[T3 DRY-RUN] Offline token-budget, GBNF, observe verbosity & error-scent battery verified.", flush=True)+ return False++ if not api_key:+ print(+ "[T3 INFO] OPENROUTER_API_KEY not set — offline baseline recorded; "+ "set OPENROUTER_API_KEY in Colab Secrets to enable live 1-shot SPEC_PIPE / error-hint hill-climbing.",+ flush=True,+ )+ if 3 not in ckpt.state["completed_tracks"]:+ ckpt.state["completed_tracks"].append(3)+ ckpt.save_and_mirror()+ return False++ t3_targets = [+ "crates/forma-lang/src/lib.rs",+ "crates/forma-lang/src/pipeline.rs",+ ]+ history: List[str] = list(t3.get("history", []))[-24:]+ slice_done = 0+ while (+ t3["plateau"] < args.t3_plateau+ and t3["round"] < args.t3_max_rounds+ and time.perf_counter() < deadline+ and (slice_rounds is None or slice_done < slice_rounds)+ ):+ t3["round"] += 1+ slice_done += 1+ r_idx = t3["round"]+ rel_file = t3_targets[(r_idx - 1) % len(t3_targets)]+ target_path = ROOT / rel_file+ cur_off = best["offline"]+ cur_on = best.get("online") or {}+ metrics_str = (+ f"composite_score={best['score']:.2f}, spec_tokens={cur_off['spec_tokens']} (budget<=620), "+ f"error_scent={cur_off['error_scent_score']:.1f} ({cur_off['error_scent_hits']}), "+ f"1-shot WT={cur_on.get('wt_rate', 0)*100:.1f}%, mean_IoU={cur_on.get('mean_iou', 0):.3f}"+ )+ try:+ hyp, new_src = propose_llm_patch(+ api_key=api_key,+ model=args.model,+ rel_file=rel_file,+ src=target_path.read_text(),+ objective=(+ "Improve Forma-Pipe SPEC_PIPE clarity/compactness, progressive spec_topic docs, "+ "or actionable error-hint diagnostics to maximize 1-shot WT=ok + IoU per token "+ "while keeping SPEC_PIPE <= 620 o200k tokens and all `forma-lang` tests passing."+ ),+ metrics_summary=metrics_str,+ history=history,+ focus_hint="pub const SPEC_PIPE" if rel_file.endswith("lib.rs") else "unknown",+ )+ label = f"t3({Path(rel_file).stem}): {hyp[:38]}"+ except Exception as exc:+ t3["plateau"] += 1+ reason = f"LLM API error: {str(exc)[:110]}"+ ckpt.append_log({"track": 3, "round": r_idx, "label": "llm_err", "kept": False, "best": best["score"], "reason": reason})+ ckpt.save_and_mirror()+ print(f"[T3 R{r_idx:03d}] SKIP | llm_err | {reason}", flush=True)+ continue++ if not new_src:+ t3["plateau"] += 1+ ckpt.append_log({"track": 3, "round": r_idx, "label": label, "kept": False, "best": best["score"], "reason": "no valid patch block"})+ ckpt.save_and_mirror()+ continue++ kept = False+ reason = ""+ with FileTransaction([target_path]) as tx:+ target_path.write_text(new_src)+ ok_b, err_b = build_forma()+ if not ok_b:+ reason = f"compile err: {(err_b.splitlines()[-1] if err_b else 'err')[:95]}"+ else:+ ok_lt, out_lt = run_rust_tests("forma-lang")+ if not ok_lt:+ reason = f"forma-lang test fail: {(out_lt.splitlines()[-1] if out_lt else 'fail')[:95]}"+ else:+ ok_off, cand_off = eval_track3_offline()+ if not ok_off:+ reason = f"offline eval fail: {cand_off.get('error', '')[:95]}"+ elif cand_off["spec_tokens"] > 620:+ reason = f"spec_tokens {cand_off['spec_tokens']} exceeded 620 budget"+ else:+ ok_on, cand_on = eval_track3_online_1shot(api_key, args.model, max_tasks=5)+ if not ok_on:+ reason = f"online eval fail: {cand_on.get('error', '')[:95]}"+ else:+ cand_score = round(cand_on["online_score"] + 0.25 * cand_off["offline_score"], 3)+ if cand_score > best["score"] + 0.25:+ kept = True+ tx.commit()+ reason = (+ f"KEEP! score {best['score']:.2f}->{cand_score:.2f} | "+ f"WT={cand_on['wt_rate']*100:.0f}% IoU={cand_on['mean_iou']:.3f} | "+ f"spec={cand_off['spec_tokens']}tok | scent={cand_off['error_scent_score']:.1f}"+ )+ best = {"score": cand_score, "offline": cand_off, "online": cand_on}+ t3["best"] = best+ t3["kept_count"] += 1+ t3["plateau"] = 0+ ckpt.save_winning_patch(3, r_idx, label)+ else:+ reason = (+ f"no gain ({cand_score:.2f} vs {best['score']:.2f}; "+ f"WT={cand_on['wt_rate']*100:.0f}% IoU={cand_on['mean_iou']:.3f} spec={cand_off['spec_tokens']}t)"+ )++ if not kept:+ t3["plateau"] += 1+ history.append(f"R{r_idx} {'KEEP' if kept else 'REVERT'} {label}: {reason}")+ t3["history"] = history[-24:]+ ckpt.append_log(+ {+ "track": 3,+ "round": r_idx,+ "label": label,+ "kept": kept,+ "best": best["score"],+ "spec_tokens": best["offline"]["spec_tokens"],+ "plateau": t3["plateau"],+ "reason": reason,+ }+ )+ ckpt.save_and_mirror()+ print(+ f"[T3 R{r_idx:03d}] {'KEEP ' if kept else 'REVRT'} | {label:34s} | {reason} "+ f"(plateau {t3['plateau']}/{args.t3_plateau})",+ flush=True,+ )++ finished = t3["plateau"] >= args.t3_plateau or t3["round"] >= args.t3_max_rounds+ if finished and 3 not in ckpt.state["completed_tracks"]:+ ckpt.state["completed_tracks"].append(3)+ ckpt.save_and_mirror()+ return not finished and time.perf_counter() < deadline+++# ===========================================================================+# CLI Entry Point+# ===========================================================================++def parse_tracks(spec: str) -> List[int]:+ tracks: List[int] = []+ for part in spec.split(","):+ p = part.strip()+ if not p:+ continue+ t = int(p)+ if t not in (1, 2, 3):+ raise ValueError(f"Invalid track '{t}'; expected 1, 2, or 3")+ if t not in tracks:+ tracks.append(t)+ if not tracks:+ raise ValueError("No tracks specified")+ return tracks+++def build_arg_parser() -> argparse.ArgumentParser:+ ap = argparse.ArgumentParser(+ description="Forma Wave 4 Marathon Long-Plateau Multi-Track Autoresearch Engine (Colab & Local).",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ ap.add_argument("--tracks", default="1,2,3", help="Comma-separated tracks to execute (subset of 1,2,3).")+ ap.add_argument(+ "--max-minutes",+ type=float,+ default=1440.0,+ help="Global wall-clock safety budget in minutes (default 1440 = 24h; set 0 for unlimited until plateau/max-rounds).",+ )+ ap.add_argument(+ "--schedule",+ choices=("round-robin", "sequential"),+ default="round-robin",+ help="Track scheduling mode: round-robin interleaves all selected tracks in slices so no track starves.",+ )+ ap.add_argument(+ "--slice-rounds",+ type=int,+ default=10,+ help="Rounds per track per cycle when --schedule round-robin is active.",+ )+ ap.add_argument("--t1-plateau", type=int, default=60, help="Track 1 consecutive non-improving rounds before stopping.")+ ap.add_argument("--t1-max-rounds", type=int, default=500, help="Track 1 maximum rounds.")+ ap.add_argument("--t2-plateau", type=int, default=60, help="Track 2 consecutive non-improving rounds before stopping.")+ ap.add_argument("--t2-max-rounds", type=int, default=500, help="Track 2 maximum rounds.")+ ap.add_argument("--t2-fuzz-per-round", type=int, default=10, help="Track 2 mutated adversarial scripts evaluated per round.")+ ap.add_argument("--t3-plateau", type=int, default=50, help="Track 3 consecutive non-improving rounds before stopping.")+ ap.add_argument("--t3-max-rounds", type=int, default=300, help="Track 3 maximum rounds.")+ ap.add_argument("--resume", action="store_true", help="Resume from checkpoint JSONL/state (local or --drive-dir).")+ ap.add_argument("--drive-dir", default="", help="Optional Google Drive directory to mirror checkpoints/patches every round.")+ ap.add_argument("--out-dir", default="", help="Output directory for state, report, charts, counterexamples, and tarball.")+ ap.add_argument("--model", default="anthropic/claude-sonnet-4", help="OpenRouter model ID when OPENROUTER_API_KEY is set.")+ ap.add_argument("--seed", type=int, default=4040, help="Deterministic PRNG seed.")+ ap.add_argument("--dry-run", action="store_true", help="Verify baselines for selected tracks without mutating repo files.")+ return ap+++def main() -> None:+ ap = build_arg_parser()+ args = ap.parse_args()+ tracks = parse_tracks(args.tracks)++ t0_all = time.perf_counter()+ deadline = float("inf") if args.max_minutes <= 0 else (t0_all + args.max_minutes * 60.0)+ rng = random.Random(args.seed)+ if args.out_dir:+ out_dir = Path(args.out_dir)+ elif Path("/content").exists():+ out_dir = Path("/content/forma_w4_out")+ else:+ out_dir = ROOT / "bench" / "results" / "w4_out"++ drive_dir = Path(args.drive_dir) if args.drive_dir else None+ api_key = get_openrouter_key(drive_dir)++ ckpt = CheckpointManager(+ out_dir=out_dir,+ log_path=DEFAULT_LOG_PATH,+ patches_dir=DEFAULT_PATCHES_DIR,+ drive_dir=drive_dir,+ dry_run=args.dry_run,+ )++ budget_str = "UNLIMITED" if args.max_minutes <= 0 else f"{args.max_minutes:.0f}m ({args.max_minutes/60.0:.1f}h)"+ print("======================================================================", flush=True)+ print(" FORMA WAVE 4 MARATHON LONG-PLATEAU MULTI-TRACK AUTORESEARCH ENGINE", flush=True)+ print(+ f" Tracks={tracks} | Schedule={args.schedule} (slice={args.slice_rounds}) | Budget={budget_str} "+ f"| CPUs={os.cpu_count()} | DryRun={args.dry_run}",+ flush=True,+ )+ print(+ f" Limits: T1({args.t1_max_rounds}r/p{args.t1_plateau}) "+ f"T2({args.t2_max_rounds}r/p{args.t2_plateau}) "+ f"T3({args.t3_max_rounds}r/p{args.t3_plateau})",+ flush=True,+ )+ print(f" LLM Mode={'ENABLED (' + args.model + ')' if api_key else 'OFFLINE (deterministic evolutionary + CEGAR)'}", flush=True)+ print(f" OutDir={out_dir} | DriveMirror={drive_dir or 'disabled'}", flush=True)+ print("======================================================================", flush=True)++ if args.resume and not args.dry_run:+ resumed = ckpt.restore_if_resume()+ print(f"[RESUME] {'Restored previous checkpoint state' if resumed else 'No existing checkpoint found; starting fresh'}", flush=True)++ # Initial release build+ print("\n[BUILD] Building release `forma-cli`...", flush=True)+ ok_b, err_b = build_forma(include_mcp=False)+ if not ok_b:+ raise SystemExit(f"Initial release build failed:\n{err_b}")++ runners = {1: run_track1, 2: run_track2, 3: run_track3}++ if args.dry_run or args.schedule == "sequential" or len(tracks) == 1:+ for tid in tracks:+ if time.perf_counter() >= deadline:+ break+ runners[tid](args, ckpt, rng, api_key, deadline, slice_rounds=None)+ else:+ cycle = 0+ active = list(tracks)+ while active and time.perf_counter() < deadline:+ cycle += 1+ print(f"\n******************** MARATHON CYCLE {cycle} (active tracks: {active}) ********************", flush=True)+ still_active: List[int] = []+ for tid in active:+ if time.perf_counter() >= deadline:+ break+ more = runners[tid](args, ckpt, rng, api_key, deadline, slice_rounds=max(1, args.slice_rounds))+ if more:+ still_active.append(tid)+ active = still_active+ # Refresh progression chart & tarball after every full cycle so Drive always has live artifacts+ ckpt.render_charts()+ ckpt.save_and_mirror(build_tar=True)++ elapsed_s = round(time.perf_counter() - t0_all, 1)++ if args.dry_run:+ print("\n======================================================================", flush=True)+ print(f" WAVE 4 DRY-RUN VERIFICATION COMPLETE in {elapsed_s}s (0 files mutated!)", flush=True)+ print("======================================================================", flush=True)+ return++ # Final verification gate across crates+ print("\n--- FINAL GATE: cargo test --release -p forma-core & forma-lang ---", flush=True)+ ok_core, out_core = run_rust_tests("forma-core")+ ok_lang, out_lang = run_rust_tests("forma-lang")+ ckpt.state["final_gate"] = {+ "forma_core_tests": "PASS" if ok_core else "FAIL",+ "forma_lang_tests": "PASS" if ok_lang else "FAIL",+ "total_elapsed_s": elapsed_s,+ }+ chart_p = ckpt.render_charts()+ ckpt.save_and_mirror(build_tar=True)++ print("\n======================================================================", flush=True)+ print(f" FORMA WAVE 4 AUTORESEARCH COMPLETE in {elapsed_s}s", flush=True)+ print(f" forma-core tests : {'PASS' if ok_core else 'FAIL'}", flush=True)+ print(f" forma-lang tests : {'PASS' if ok_lang else 'FAIL'}", flush=True)+ print(f" Report : {ckpt.report_path}", flush=True)+ print(f" Charts : {chart_p or 'skipped (matplotlib not installed)'}", flush=True)+ print(f" Tarball : {ckpt.tar_path}", flush=True)+ if drive_dir:+ print(f" Drive Mirror : {drive_dir}", flush=True)+ print("======================================================================", flush=True)+ if not ok_core or not ok_lang:+ if not ok_core:+ print("forma-core test output:\n" + out_core, flush=True)+ if not ok_lang:+ print("forma-lang test output:\n" + out_lang, flush=True)+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/notebooks/forma_autoresearch_w4_colab.ipynb b/notebooks/forma_autoresearch_w4_colab.ipynbnew file mode 100644index 0000000..8cd0b32--- /dev/null+++ b/notebooks/forma_autoresearch_w4_colab.ipynb@@ -0,0 +1,274 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# `forma` Wave 4 Marathon Multi-Track Autoresearch (Google Colab)\n",+ "\n",+ "Runs an unattended, **24-hour marathon**, long-plateau, round-robin checkpointed **Wave 4 Multi-Track Autoresearch Engine** (`bench/colab_autoresearch_w4.py`) across all 3 tracks on Colab's multi-core Linux VM, with automatic Google Drive mirroring every round and seamless `--resume` across Colab disconnects:\n",+ "\n",+ "- **Round-Robin Interleaving (`SCHEDULE = 'round-robin'`, `SLICE_ROUNDS = 10`)**: All 3 tracks advance together in 10-round slices so no track starves, speed wins from Track 1 immediately accelerate Track 2 & 3, and Drive always has live charts + winning patches.\n",+ "- **Unlimited Multi-Session Chaining**: Default `MAX_MINUTES = 1440` (24h; set `0` for unlimited until all tracks exhaust plateau/max-rounds). If Colab disconnects, simply re-run Cells 1–3 with `RESUME = True` and it picks up from Drive right where it stopped.\n",+ "- **Optional 3× Parallel VMs**: To run all 3 tracks concurrently on 3 separate Colab tabs, set `TRACKS = '1'`, `'2'`, or `'3'` in each tab (Drive automatically namespaces single-track runs into `forma_w4_autoresearch/track_1` etc.).\n",+ "\n",+ "1. **Track 1 — Kernel Speed & 10-Part Session Autoresearch (`T1_PLATEAU = 60`, `T1_MAX_ROUNDS = 500`):**\n",+ " - Optimizes BOTH `perf_bench` (`TOTAL SUITE SCORE` ms) AND a stateful 10-part industrial assembly session (`forma eval --strict --scene --out ... --render ...`).\n",+ " - Enforces a strict **>= 1.5% verified speedup** gate (confirmed on 3× repeat run), **0 invariant regressions**, and **byte-exact GLB & PNG determinism**.\n",+ " - Escalates exploration scale & LLM structural mutation cadence automatically during long plateaus.\n",+ "2. **Track 2 — Adversarial Geometry Soundness & Fuzz Autoresearch (`T2_PLATEAU = 60`, `T2_MAX_ROUNDS = 500`, `T2_FUZZ_PER_ROUND = 10`):**\n",+ " - Runs an evolutionary adversarial geometry stress suite (balanced `±45°` diagonal fins, 3+ radial fin arrays, `1e-4` m micro-scale overlaps, curved-tool CSG cuts, twisted loft/nurbs/sweep/shell/bevel/remesh/bisect chains, high-chart UV unwraps).\n",+ " - Delta-minimizes every failing script into a persistent CEGAR `counterexamples/` bank and rotates across all active counterexamples when `OPENROUTER_API_KEY` is set.\n",+ "3. **Track 3 — Agent-Pilot Token Efficiency & 1-Shot Accuracy (`T3_PLATEAU = 50`, `T3_MAX_ROUNDS = 300`):**\n",+ " - Measures `forma spec` tokens, progressive `--topic` tokens, `Scene::observe` verbosity, GBNF grammar size/states, CLI/MCP latency, and an 8-case error-scent battery.\n",+ " - When `OPENROUTER_API_KEY` is set, runs 1-shot accuracy hill-climbing on `bench/eval_complex_abc.py` tasks maximizing `1-shot WT=ok + IoU` per token."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# 1. Install Rust toolchain, optional Python analysis deps, and clone/update `wrong-nebula/forma`\n",+ "import os, subprocess, sys\n",+ "\n",+ "os.environ['PATH'] = os.path.expanduser('~/.cargo/bin') + ':' + os.environ['PATH']\n",+ "if subprocess.run(['which', 'cargo'], capture_output=True).returncode != 0:\n",+ " print('Installing Rust toolchain via rustup...', flush=True)\n",+ " subprocess.run(\"curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y\", shell=True, check=True)\n",+ " os.environ['PATH'] = os.path.expanduser('~/.cargo/bin') + ':' + os.environ['PATH']\n",+ "\n",+ "!rustc --version && cargo --version && nproc\n",+ "\n",+ "# Optional Python packages for exact o200k token counts, IoU verification, and progression charts\n",+ "!pip -q install tiktoken matplotlib trimesh scipy numpy\n",+ "\n",+ "FORMA_DIR = '/content/forma'\n",+ "FORMA_BRANCH = 'main' # Change to 'feat/colab-autoresearch-w4' if testing before PR merge\n",+ "if not os.path.exists(f'{FORMA_DIR}/.git'):\n",+ " !git clone --depth 1 --branch {FORMA_BRANCH} https://github.com/wrong-nebula/forma.git {FORMA_DIR}\n",+ "else:\n",+ " !cd {FORMA_DIR} && git fetch origin {FORMA_BRANCH} && git reset --hard origin/{FORMA_BRANCH}\n",+ "\n",+ "!cd {FORMA_DIR} && git log -1 --oneline"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# 2. Mount Google Drive (recommended for 24h+ marathon runs & automatic resume after disconnect)\n",+ "MOUNT_DRIVE = True\n",+ "DRIVE_BASE_DIR = '/content/drive/MyDrive/forma_w4_autoresearch'\n",+ "\n",+ "if MOUNT_DRIVE:\n",+ " from google.colab import drive\n",+ " drive.mount('/content/drive')\n",+ " os.makedirs(DRIVE_BASE_DIR, exist_ok=True)\n",+ " print(f'Google Drive mounted — checkpoints, patches, and counterexamples mirror to: {DRIVE_BASE_DIR}')\n",+ "else:\n",+ " DRIVE_BASE_DIR = ''\n",+ " print('MOUNT_DRIVE = False — checkpoints will be stored locally in /content/forma_w4_out only.')"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# 3. Launch Wave 4 Marathon Multi-Track Autoresearch (Live Streaming Logs + Drive Resume)\n",+ "import os, subprocess, sys\n",+ "\n",+ "TRACKS = '1,2,3' # '1,2,3' for round-robin marathon, or '1' / '2' / '3' in 3 parallel Colab tabs\n",+ "SCHEDULE = 'round-robin' # 'round-robin' interleaves all selected tracks; 'sequential' runs one by one\n",+ "SLICE_ROUNDS = 10 # Rounds per track per cycle in round-robin mode\n",+ "MAX_MINUTES = 1440 # 24-hour wall-clock budget (set 0 for unlimited until all tracks plateau)\n",+ "T1_PLATEAU = 60 # Track 1 (Kernel Speed & 10-Part Session) plateau patience\n",+ "T1_MAX_ROUNDS = 500\n",+ "T2_PLATEAU = 60 # Track 2 (Adversarial Soundness & Fuzz / CEGAR) plateau patience\n",+ "T2_MAX_ROUNDS = 500\n",+ "T2_FUZZ_PER_ROUND = 10 # Mutated adversarial scripts per Track 2 round\n",+ "T3_PLATEAU = 50 # Track 3 (Agent Token Efficiency & 1-Shot) plateau patience\n",+ "T3_MAX_ROUNDS = 300\n",+ "RESUME = True # Automatically resumes from Drive/local checkpoint across Colab disconnects\n",+ "OPENROUTER_MODEL = 'anthropic/claude-sonnet-4'\n",+ "OUT_DIR = '/content/forma_w4_out'\n",+ "\n",+ "# Auto-namespace Drive folder if running a single track so 3 parallel Colab VMs never collide\n",+ "if DRIVE_BASE_DIR:\n",+ " DRIVE_DIR = DRIVE_BASE_DIR if ',' in TRACKS else f\"{DRIVE_BASE_DIR}/track_{TRACKS.strip()}\"\n",+ "else:\n",+ " DRIVE_DIR = ''\n",+ "\n",+ "env = os.environ.copy()\n",+ "env['PATH'] = os.path.expanduser('~/.cargo/bin') + ':' + env['PATH']\n",+ "env['PYTHONUNBUFFERED'] = '1'\n",+ "env['CARGO_BUILD_JOBS'] = str(min(os.cpu_count() or 2, 8))\n",+ "\n",+ "# Wire OPENROUTER_API_KEY from Colab Secrets or private Google Drive key file (never stored in git)\n",+ "key_source = ''\n",+ "try:\n",+ " from google.colab import userdata\n",+ " api_key = userdata.get('OPENROUTER_API_KEY')\n",+ " if api_key:\n",+ " env['OPENROUTER_API_KEY'] = api_key.strip()\n",+ " key_source = 'Colab Secrets'\n",+ "except Exception:\n",+ " pass\n",+ "if not env.get('OPENROUTER_API_KEY') and DRIVE_BASE_DIR:\n",+ " for kp in (f'{DRIVE_BASE_DIR}/.openrouter_key', f'{DRIVE_DIR}/.openrouter_key'):\n",+ " if os.path.exists(kp):\n",+ " k = open(kp).read().strip()\n",+ " if k:\n",+ " env['OPENROUTER_API_KEY'] = k\n",+ " key_source = f'private Drive file ({kp})'\n",+ " break\n",+ "if env.get('OPENROUTER_API_KEY'):\n",+ " print(f'OPENROUTER_API_KEY loaded from {key_source or \"environment\"} — LLM mutations enabled ({OPENROUTER_MODEL})', flush=True)\n",+ "else:\n",+ " print('OPENROUTER_API_KEY not set — running offline evolutionary + CEGAR fuzz mode.', flush=True)\n",+ "\n",+ "cmd = [\n",+ " sys.executable, '-u', '/content/forma/bench/colab_autoresearch_w4.py',\n",+ " '--tracks', TRACKS,\n",+ " '--schedule', SCHEDULE,\n",+ " '--slice-rounds', str(SLICE_ROUNDS),\n",+ " '--max-minutes', str(MAX_MINUTES),\n",+ " '--t1-plateau', str(T1_PLATEAU),\n",+ " '--t1-max-rounds', str(T1_MAX_ROUNDS),\n",+ " '--t2-plateau', str(T2_PLATEAU),\n",+ " '--t2-max-rounds', str(T2_MAX_ROUNDS),\n",+ " '--t2-fuzz-per-round', str(T2_FUZZ_PER_ROUND),\n",+ " '--t3-plateau', str(T3_PLATEAU),\n",+ " '--t3-max-rounds', str(T3_MAX_ROUNDS),\n",+ " '--out-dir', OUT_DIR,\n",+ " '--model', OPENROUTER_MODEL,\n",+ "]\n",+ "if RESUME:\n",+ " cmd.append('--resume')\n",+ "if DRIVE_DIR:\n",+ " cmd.extend(['--drive-dir', DRIVE_DIR])\n",+ "\n",+ "print('Running:', ' '.join(cmd), flush=True)\n",+ "proc = subprocess.Popen(\n",+ " cmd,\n",+ " cwd='/content/forma',\n",+ " env=env,\n",+ " stdout=subprocess.PIPE,\n",+ " stderr=subprocess.STDOUT,\n",+ " text=True,\n",+ " bufsize=1,\n",+ ")\n",+ "for line in proc.stdout:\n",+ " print(line, end='', flush=True)\n",+ "rc = proc.wait()\n",+ "print(f'\\nExited with code {rc}', flush=True)\n",+ "assert rc == 0, f'Wave 4 autoresearch exited with code {rc}'"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# 4. Visualize Wave 4 Progression Charts, Markdown Report & Counterexample Bank\n",+ "import json\n",+ "from pathlib import Path\n",+ "from IPython.display import Image, Markdown, display\n",+ "import matplotlib.pyplot as plt\n",+ "\n",+ "out_dir = Path('/content/forma_w4_out')\n",+ "if not out_dir.exists() and DRIVE_DIR:\n",+ " out_dir = Path(DRIVE_DIR)\n",+ "\n",+ "report_path = out_dir / 'w4_report.md'\n",+ "if report_path.exists():\n",+ " display(Markdown(report_path.read_text()))\n",+ "\n",+ "chart_path = out_dir / 'w4_progression.png'\n",+ "if chart_path.exists():\n",+ " display(Image(filename=str(chart_path)))\n",+ "else:\n",+ " log_path = out_dir / 'w4_autoresearch_log.jsonl'\n",+ " if log_path.exists():\n",+ " rows = [json.loads(l) for l in log_path.read_text().splitlines() if l.strip()]\n",+ " fig, axes = plt.subplots(1, 3, figsize=(16, 4.5), dpi=130)\n",+ " titles = [\n",+ " (1, 'Track 1: Kernel + 10-Part Speed (ms, lower=better)', '#2563eb'),\n",+ " (2, 'Track 2: Adversarial Bank Failures (lower=better)', '#dc2626'),\n",+ " (3, 'Track 3: Token Eff & 1-Shot Score (higher=better)', '#7c3aed'),\n",+ " ]\n",+ " for ax, (tid, title, color) in zip(axes, titles):\n",+ " trows = [r for r in rows if r.get('track') == tid]\n",+ " if trows:\n",+ " xs = [r['round'] for r in trows]\n",+ " ys = [r.get('bank_failures', r.get('best', 0)) if tid == 2 else r.get('best', 0) for r in trows]\n",+ " kx = [r['round'] for r in trows if r.get('kept')]\n",+ " ky = [r.get('bank_failures', r.get('best', 0)) if tid == 2 else r.get('best', 0) for r in trows if r.get('kept')]\n",+ " ax.plot(xs, ys, color=color, lw=2)\n",+ " if kx:\n",+ " ax.scatter(kx, ky, color='#10b981', s=45, zorder=5, label='Kept')\n",+ " ax.set_title(title)\n",+ " ax.set_xlabel('Round')\n",+ " ax.grid(alpha=0.3)\n",+ " plt.tight_layout()\n",+ " plt.show()\n",+ "\n",+ "ce_dir = out_dir / 'counterexamples'\n",+ "if ce_dir.exists():\n",+ " ces = sorted(ce_dir.glob('*.forma'))\n",+ " print(f'\\nCEGAR Counterexample Bank: {len(ces)} minimal failing scripts in {ce_dir}')\n",+ " for fp in ces[:10]:\n",+ " print(f' - {fp.name}')"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# 5. Download Verified Winning Patches & Artifacts Bundle (.tar.gz)\n",+ "from pathlib import Path\n",+ "\n",+ "tar_candidates = [\n",+ " Path('/content/forma_w4_winners.tar.gz'),\n",+ " Path(DRIVE_DIR) / 'forma_w4_winners.tar.gz' if DRIVE_DIR else Path('/nonexistent'),\n",+ "]\n",+ "tar_file = next((p for p in tar_candidates if p.exists()), None)\n",+ "\n",+ "if tar_file:\n",+ " print(f'Winning bundle ready ({tar_file.stat().st_size / 1024:.1f} KB): {tar_file}')\n",+ " try:\n",+ " from google.colab import files\n",+ " files.download(str(tar_file))\n",+ " except Exception as e:\n",+ " print('Browser download skipped:', e)\n",+ "else:\n",+ " print('No tarball found yet — run Cell 3 to completion first.')"+ ]+ }+ ],+ "metadata": {+ "colab": {+ "name": "forma_autoresearch_w4_colab.ipynb",+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "name": "python",+ "version": "3.11.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 4+}