"""Loop validator for one-change-at-a-time T1 campaigns (QECT T1_LOOP_PLAN.md, 2026-10-15).

Why it exists. In the 2026-10-08 campaign acceptance was left to agents reading their own numbers (seven logged misreports), and
the ledger's best was the largest receipt-verified point estimate. Here one deterministic tool reads the RAW Gamma_II couplings,
displacement manifests, phonon sets and T1 files of parent and variant, recomputes T1 itself and decides. Agents run calculations
and call it; its signed receipts are the only thing that sets sota.T1_300K_s (ledger ``owner``) and the ``loop_accept`` gate.

Pre-registered rules (V(IV) d1, Protocol P: NEVPT2 couplings, sigma 10 cm-1, 0.345 T powder, 300 K):
  hit    T1_var(s) / T1_par(s) >= 1.2 for every broadening s in (5, 10, 20) cm-1 (paired: s is shared), main couplings, AND the
         matched mode family's Gamma_II coupling gradient fell (sec. 5a). A family that is not conserved -> accepted only on total
         T1 + C1 + C2 (logged as an unassigned crystal/phonon-spectrum effect).
  C1     the same paired test on each material's pooled band over every coupling set (main, the +/-2Q step alternative,
         start-orbital replicates): min_s lo_var(s) / hi_par(s) >= 1.2; and the family-gradient decrease exceeds the parent's plus
         the variant's spread (step / replicate change of the family gradient, or the two-step linearity of its directions).
  C2     every hit: the top-3 relaxing modes of hit and parent at 0, +/-2Q, CAS(n,5) vs CAS(n+2k,5+k) (the 5 d orbitals plus the
         k highest inactive orbitals of the reference: the frontier donor orbitals): each d-d root keeps a match (same open-shell
         d orbital, overlap >= 0.7) with unchanged ordering, no d-d state crosses a charge-transfer root along the mode and no
         charge-transfer root is the lowest excitation (one inside the d-d manifold is reported, not failed); derivatives are
         compared RELATIVE to the parent (user decision 2026-10-16): the hit/parent ratios of sum ||d(g g^T)/dQ|| and of the
         summed low d-d gap derivatives agree between the two active spaces within 20% and stay on the same side of 1 (the
         seed's absolute change, -43..-48% on d(g g^T)/dQ, is the common CAS(n,5) covalency scaling and cancels).
  C3     counterion swaps: the top-3 modes of hit and parent at +/-Q with the explicit point charges moved along the crystal
         eigenvector vs fixed: d(g g^T)/dQ within 20% per mode, hit/parent ordering unchanged.
  C4     Clari-sourced variants and disordered deposited structures: the family is conserved and its gradient falls in every
         carried packing (or ordered model) within 2 kJ/mol per formula unit.
  round  several confirmed hits against one parent: A wins iff min_s lo_A(s) / hi_B(s) > 1 for every other hit B (the paired
         band rule); else fewest Clari-sourced structures, then fewest core-hours (sacct over the variant's directories).
  stop   6 consecutive rejected variants; confirmed incumbent >= 3x the seed at every s; seed T1 < VOPc / 2.
g g^T is used instead of g because it is independent of the pseudo-spin basis ORCA picks (g -> g R)."""

from __future__ import annotations

import hashlib
import itertools
import json
import math
import re
import subprocess
from pathlib import Path
from typing import Annotated, Any, Dict

import numpy as np
from langchain.tools import ToolRuntime
from langchain_core.tools import tool

from Hypothesis_generation.skill_library.periodic_dft import excited_state_raman as es
from Hypothesis_generation.skill_library.periodic_dft import harness as _h
from Hypothesis_generation.skill_library.periodic_dft import spin_relaxation as sr
from Hypothesis_generation.skill_library.periodic_dft.low_mode_hessian import translations

VALIDATOR = "t1_loop_judge"
METRIC = "T1_300K_s"
ACCEPT_GATE = "loop_accept"
INCUMBENT_GATE = "loop_incumbent"
SIGMAS = (5.0, 10.0, 20.0)
CENTRAL_SIGMA = 10.0
T_K = 300.0
FIELD_T = 0.345
HIT_RATIO = 1.2
MATCH_COS = 0.7  # principal-angle cosine for a conserved family; open-shell overlap for a C2 match
SELECT_COS2 = 0.5  # a mode joins a family when half its first-shell motion lies in the designed subspace
WINDOW_CM1 = 10.0  # the broadening scale: family members sit within it of the designed modes' frequencies
LABELING_TOL_ANGSTROM = 0.1  # first-shell labelings this close to the best Kabsch rmsd are geometrically equivalent
REL_TOL = 0.2  # C2 / C3: derivatives within 20%
FLOOR = 0.05  # C3: a near-zero d(g g^T)/dQ is measured against 5% of the largest mode's
DEGENERATE = 0.05  # d-d roots closer than 5% of their gap may swap order
STOP_REJECTIONS = 6
STOP_GAIN = 3.0
VOPC_T1_300K_S = 8.4e-7  # VOPc, Protocol P (QECT handoff 2026-10-08)
MOVES = ("ligand_edit", "counterion_swap", "substituent", "host_check")
SOURCES = ("deposited", "deposited_disordered", "clari")  # disordered CIF: every ordered model within 2 kJ/mol is a packing (C4)
ORCA_D = ("dz2", "dxz", "dyz", "dx2y2", "dxy")
STEP_FS_ANGSTROM = 0.01  # Q: the metal + donor rms displacement of the export's steps
MAX_ATOM_ANGSTROM = 0.05


# --------------------------------------------------------------------------- materials


def _sha(path: Path) -> str:
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def _json(path: Path) -> dict:
    return json.loads(Path(path).read_text())


def _rates(data: dict, sigmas, keep_pairs_at=None) -> tuple[dict, np.ndarray | None]:
    """{sigma: Gamma_II 1/T1 at 300 K} of one couplings file (d1, no covalency), and the 300 K pair rates at keep_pairs_at."""
    v0, h0 = (np.array(data["reference"][k], dtype=float) for k in ("V_nevpt2", "h_soc"))
    freqs = np.array(data["modes"]["frequencies_cm1"], dtype=float)
    dops = es.coupling_operators(np.array(data["mode_couplings"]["dV"], dtype=float), np.array(data["mode_couplings"]["dh"], dtype=float), 1)
    out, pairs = {}, None
    for s in sigmas:
        res = es.gamma2_powder(v0, h0, dops, freqs, FIELD_T, [T_K], float(s), 1)
        out[float(s)] = float(res["rate"][0])
        if keep_pairs_at is not None and float(s) == float(keep_pairs_at):
            pairs = res["pairs"][0]
    return out, pairs


def _block_norms(data: dict) -> np.ndarray:
    """Per mode: Frobenius norm of the ground-doublet x excited-state block of dH_ion/dQ in the B = 0 eigenbasis -- the coupling
    that enters the Gamma_II amplitude (dE/dQ and dSOC/dQ together)."""
    v0, h0 = (np.array(data["reference"][k], dtype=float) for k in ("V_nevpt2", "h_soc"))
    dops = es.coupling_operators(np.array(data["mode_couplings"]["dV"], dtype=float), np.array(data["mode_couplings"]["dh"], dtype=float), 1)
    _e, u = np.linalg.eigh(es.ion_hamiltonian(v0, h0, (0.0, 0.0, 0.0), 1))
    vm = np.einsum("ji,ajk,kl->ail", u.conj(), dops, u)
    return np.sqrt((np.abs(vm[:, :2, 2:]) ** 2).sum(axis=(1, 2)))


def load_material(root: Path, spec: dict, need_t1: bool = True) -> dict:
    """One computed material from its raw files. spec: {couplings, manifest, phonon_dir, t1, replicates?: [couplings ...]}."""
    rp = lambda p: _h._resolve_path(root, p, must_exist=True, dir_ok=False)  # noqa: E731
    cpath, mpath = rp(spec["couplings"]), rp(spec["manifest"])
    ph = _h._resolve_path(root, spec["phonon_dir"], must_exist=True, file_ok=False)
    data, man = _json(cpath), _json(mpath)
    if data.get("kind") != es.COUPLINGS_KIND or "step_test_alternative_of" in data:
        raise ValueError(f"{cpath.name}: not the main collect_excited_state_couplings output")
    if man.get("kind") != es.KIND:
        raise ValueError(f"{mpath.name}: not an export_excited_state_displacements manifest")
    if int(data["d_count"]) != 1 or str(data.get("metal")) != "V":
        raise ValueError(f"{cpath.name}: {data.get('metal')} d{data['d_count']}; this loop validator is V(IV) d1 only")
    if data.get("couplings_level") != "nevpt2":
        raise ValueError(f"{cpath.name}: couplings_level {data.get('couplings_level')!r}; Protocol P verdicts need NEVPT2 members")
    phonon_sha = _sha(ph / "phonopy_params.yaml")
    for name, recorded in (("couplings", data.get("phonon_set_sha256")), ("manifest", man.get("phonon_set_sha256"))):
        if recorded != phonon_sha:
            raise ValueError(f"the {name} file was computed on another phonon set ({str(recorded)[:12]} vs {phonon_sha[:12]} of {ph.name})")
    if list(data["modes"]["indices"]) != list(man["modes"]["indices"]) or not np.allclose(
            data["modes"]["frequencies_cm1"], man["modes"]["frequencies_cm1"]):
        raise ValueError(f"{cpath.name} and {mpath.name} describe different Gamma modes")
    files = {"couplings": cpath, "manifest": mpath, "phonopy_params": ph / "phonopy_params.yaml"}
    sets = {"main": data}
    if data.get("step_test"):
        alt = cpath.parent / data["step_test"]["alternative_couplings"]
        sets["step2"] = _json(alt)
        files["step2"] = alt
    for k, rel in enumerate(spec.get("replicates") or []):
        path = rp(rel)
        rep = _json(path)
        if rep.get("phonon_set_sha256") != phonon_sha or list(rep["modes"]["indices"]) != list(data["modes"]["indices"]):
            raise ValueError(f"replicate {path.name}: different phonon set or modes")
        sets[f"replicate{k + 1}"] = rep
        files[f"replicate{k + 1}"] = path
    rates, pairs = {}, None
    for name, d in sets.items():
        rates[name], p = _rates(d, SIGMAS, CENTRAL_SIGMA if name == "main" else None)
        pairs = p if name == "main" else pairs
    t1 = {s: 1.0 / rates["main"][s] for s in SIGMAS}
    if need_t1:
        tpath = rp(spec["t1"])
        tout = _json(tpath)
        if float(tout.get("broadening_cm1", -1)) != CENTRAL_SIGMA or float(tout.get("field_tesla", -1)) != FIELD_T:
            raise ValueError(f"{tpath.name}: sigma {tout.get('broadening_cm1')} / field {tout.get('field_tesla')}; Protocol P is sigma 10, 0.345 T")
        if Path(str(tout.get("couplings"))).name != cpath.name:
            raise ValueError(f"{tpath.name} was computed from {tout.get('couplings')}, not {cpath.name}")
        row = next((r for r in tout.get("results") or [] if float(r["T_K"]) == T_K), None)
        if row is None or not row.get("T1_II_s"):
            raise ValueError(f"{tpath.name} has no 300 K T1_II_s: rerun compute_excited_state_spin_relaxation with 300 in temperatures_k")
        if abs(row["T1_II_s"] / t1[CENTRAL_SIGMA] - 1) > 5e-3:
            raise ValueError(f"{tpath.name} says T1_II(300 K) = {row['T1_II_s']:.4g} s; these couplings give {t1[CENTRAL_SIGMA]:.4g} s")
        files["t1"] = tpath
    band = {s: [min(1 / r[s] for r in rates.values()), max(1 / r[s] for r in rates.values())] for s in SIGMAS}
    share = (pairs.sum(axis=0) + pairs.sum(axis=1)) / 2 / max(pairs.sum(), 1e-300)
    shas = {name: _sha(path) for name, path in files.items()}
    # identity = what defines the computed T1 (couplings, step alternative, manifest, force sets, T1 file); replicates only
    # widen the band, so registering them later keeps the snapshot
    core = {k: v for k, v in shas.items() if not k.startswith("replicate")}
    snapshot = "snap-" + hashlib.sha256(json.dumps(core, sort_keys=True).encode()).hexdigest()[:16]
    return {
        "snapshot": snapshot, "spec": {k: v for k, v in spec.items() if k in ("couplings", "manifest", "phonon_dir", "t1", "replicates")},
        "files": {k: _h._rel(root, p) for k, p in files.items()}, "shas": shas, "phonon_sha": phonon_sha,
        "data": data, "sets": sets, "man": man, "mpath": mpath, "ph": ph,
        "indices": [int(i) for i in data["modes"]["indices"]], "freqs": np.array(data["modes"]["frequencies_cm1"], dtype=float),
        "vecs": np.array(man["modes"]["vectors_mass_weighted"], dtype=float), "metal": int(man["metal_index"]),
        "donors": [int(i) for i in man["donors"]], "symbols": list(man["symbols"]), "masses": np.array(man["masses_amu"], dtype=float),
        "positions": np.array(man["positions_angstrom"], dtype=float), "t1": t1, "band": band, "rate": rates["main"][CENTRAL_SIGMA],
        "share": share, "G": {name: _block_norms(d) for name, d in sets.items()},
        "dV": np.linalg.norm(np.array(data["mode_couplings"]["dV"]), axis=(1, 2)),
        "dh": np.sqrt((np.array(data["mode_couplings"]["dh"]) ** 2).sum(axis=(1, 2, 3))),
        "linearity": {int(r["direction"]): max(float(r["rel_diff_V"]), float(r["rel_diff_h"])) for r in data["checks"].get("linearity", [])},
        "proj": np.array(man["modes"]["vectors_mass_weighted"], dtype=float) @ np.array(man["directions_mass_weighted"], dtype=float).T,
    }


def top_modes(mat: dict, n: int = 3) -> list[int]:
    return [mat["indices"][i] for i in np.argsort(-mat["share"])[:n]]


# --------------------------------------------------------------------------- mode families (sec. 5a)


def _orth(rows: np.ndarray) -> np.ndarray:
    """Orthonormal basis (columns) of the span of the rows."""
    if len(rows) == 0:
        return np.zeros((0 if rows.ndim < 2 else rows.shape[1], 0))
    u, s, _vt = np.linalg.svd(np.asarray(rows, dtype=float).T, full_matrices=False)
    return u[:, s > 1e-8 * max(s.max(), 1e-300)]


def _kabsch(mobile: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, float]:
    """Rotation R (rows act on column vectors: x' = R x) taking centred mobile onto centred target, and the rmsd."""
    a, b = mobile - mobile.mean(axis=0), target - target.mean(axis=0)
    u, _s, vt = np.linalg.svd(a.T @ b)
    d = np.sign(np.linalg.det(u @ vt))
    r = (u @ np.diag([1.0, 1.0, d]) @ vt).T
    return r, float(np.sqrt((((a @ r.T) - b) ** 2).sum(axis=1).mean()))


def _shell_maps(par: dict, var: dict) -> list[tuple[list[int], list[int], np.ndarray, float]]:
    """First shells (metal + donors) of parent and variant matched atom by atom: every donor permutation (same elements) whose
    Kabsch rmsd is within LABELING_TOL_ANGSTROM of the best, with the rotation of the variant's frame onto the parent's. A
    pseudo-symmetric shell (VOS4) has several such labelings; the first shell alone cannot tell them apart."""
    sp = [par["metal"]] + par["donors"]
    sv0 = [var["metal"]] + var["donors"]
    el = lambda m, idx: [m["symbols"][i] for i in idx]  # noqa: E731
    if el(par, sp)[0] != el(var, sv0)[0] or sorted(el(par, sp)) != sorted(el(var, sv0)):
        raise ValueError(f"first shells differ: parent {el(par, sp)} vs variant {el(var, sv0)}")
    groups = {}
    for k, i in enumerate(sp[1:], 1):
        groups.setdefault(par["symbols"][i], []).append(k)
    maps = []
    choices = [list(itertools.permutations([i for i in var["donors"] if var["symbols"][i] == e])) for e in groups]
    for combo in itertools.product(*choices):
        sv = [var["metal"]] + [0] * len(var["donors"])
        for (e, slots), perm in zip(groups.items(), combo):
            for slot, atom in zip(slots, perm):
                sv[slot] = atom
        r, rmsd = _kabsch(var["positions"][sv], par["positions"][sp])
        maps.append((sp, sv, r, rmsd))
    best = min(m[3] for m in maps)
    return sorted((m for m in maps if m[3] <= best + LABELING_TOL_ANGSTROM), key=lambda m: m[3])


def _fs_rows(mat: dict, atoms: list[int], rot: np.ndarray | None = None) -> np.ndarray:
    v = mat["vecs"].reshape(len(mat["vecs"]), -1, 3)[:, atoms, :]
    if rot is not None:
        v = v @ rot.T
    return v.reshape(len(v), -1)


def _closure(fs: np.ndarray, freqs: np.ndarray, basis: np.ndarray, lo: float, hi: float) -> list[int]:
    """Modes inside [lo, hi] with >= SELECT_COS2 of their first-shell motion inside span(basis)."""
    out = []
    for j in np.where((freqs >= lo) & (freqs <= hi))[0]:
        n2 = float(fs[j] @ fs[j])
        if n2 > 0 and float(np.sum((basis.T @ fs[j]) ** 2)) / n2 >= SELECT_COS2:
            out.append(int(j))
    return out


def _rss(x) -> float:
    return float(np.sqrt(np.sum(np.asarray(x, dtype=float) ** 2)))


def _family_numbers(mat: dict, fam: list[int], shell: list[int]) -> dict:
    p = np.array([float(np.sum(mat["vecs"][j].reshape(-1, 3)[shell] ** 2)) for j in fam])
    w = mat["share"][fam]
    return {
        "modes": [mat["indices"][j] for j in fam], "frequencies_cm1": [round(float(mat["freqs"][j]), 2) for j in fam],
        "rate_weighted_frequency_cm1": round(float((w * mat["freqs"][fam]).sum() / max(w.sum(), 1e-300)), 2) if fam else None,
        "first_shell_participation": [round(float(x), 4) for x in p],
        "gradient": _rss(mat["G"]["main"][fam]), "gradient_over_sqrt_p": _rss(mat["G"]["main"][fam] / np.sqrt(np.maximum(p, 1e-12))),
        "dE_dQ": _rss(mat["dV"][fam]), "dE_dQ_over_sqrt_p": _rss(mat["dV"][fam] / np.sqrt(np.maximum(p, 1e-12))),
        "dSOC_dQ": _rss(mat["dh"][fam]), "dSOC_dQ_over_sqrt_p": _rss(mat["dh"][fam] / np.sqrt(np.maximum(p, 1e-12))),
        "rate_300K_s-1": float(w.sum() * mat["rate"]), "rate_fraction": round(float(w.sum()), 4),
    }


def _spread(mat: dict, fam: list[int]) -> float:
    """Numerical spread of a family gradient: the largest relative change with the step-test / replicate couplings, and the
    first-order effect of the two-step linearity data: sum_j w_j r_j over the family's whole weight (w_j its squared projection
    on direction j, r_j that direction's +/-Q vs +/-2Q difference; directions without +/-2Q data contribute nothing -- the seed's
    ~380 cm-1 family puts 3% of its weight on them, so a mean over those directions alone would inflate it 30x)."""
    g = _rss(mat["G"]["main"][fam])
    alt = [abs(_rss(gs[fam]) / g - 1) for name, gs in mat["G"].items() if name != "main" and g > 0]
    w = (mat["proj"][fam] ** 2).sum(axis=0)
    lin = sum(w[j] * r for j, r in mat["linearity"].items() if j < len(w)) / max(float(w.sum()), 1e-300)
    return float(max(alt + [lin]))


def match_family(par: dict, var: dict, designed: list[int], window_cm1: float = WINDOW_CM1) -> dict:
    """Sec. 5a: the parent's designed modes (closed over near-degenerate partners) vs the variant modes within the broadening
    window whose first-shell motion lies in the same subspace, compared by principal angles after a Kabsch fit. Among
    geometrically equivalent first-shell labelings the one that best preserves the designed subspace is used (reported)."""
    pos = {m: k for k, m in enumerate(par["indices"])}
    missing = [m for m in designed if m not in pos]
    if not designed or missing:
        raise ValueError(f"designed_modes must name parent mode indices (the T1 tool's top_modes 'mode'); unknown: {missing or 'none given'}")
    d_idx = [pos[m] for m in designed]
    lo, hi = float(par["freqs"][d_idx].min()) - window_cm1, float(par["freqs"][d_idx].max()) + window_cm1
    maps = _shell_maps(par, var)
    best = None
    for sp, sv, rot, rmsd in maps:
        fp, fv = _fs_rows(par, sp), _fs_rows(var, sv, rot)
        pfam = sorted(set(d_idx) | set(_closure(fp, par["freqs"], _orth(fp[d_idx]), lo, hi)))
        qp = _orth(fp[pfam])
        vfam = _closure(fv, var["freqs"], qp, lo, hi)
        cosines = np.linalg.svd(qp.T @ _orth(fv[vfam]), compute_uv=False) if vfam else np.zeros(0)
        k = qp.shape[1]
        score = float(np.min(cosines[:k])) if len(cosines) >= k else -1.0 + len(cosines) / max(k, 1) * 1e-3
        if best is None or score > best[0] + 1e-9:
            best = (score, sp, sv, rot, rmsd, fp, fv, pfam, qp, vfam, cosines, k)
    _score, sp, sv, rot, rmsd, fp, fv, pfam, qp, vfam, cosines, k = best
    conserved = len(cosines) >= k and float(np.min(cosines[:k])) >= MATCH_COS
    outside = [(var["indices"][j], round(float(var["freqs"][j]), 1)) for j in _closure(fv, var["freqs"], qp, -1e9, 1e9) if j not in vfam]
    pn, vn = _family_numbers(par, pfam, sp), _family_numbers(var, vfam, sv) if vfam else None
    out = {"window_cm1": [round(lo, 1), round(hi, 1)], "kabsch_rmsd_angstrom": round(rmsd, 4), "equivalent_labelings": len(maps),
           "variant_shell_atoms": [int(i) for i in sv], "subspace_dim": int(k),
           "principal_cosines": [round(float(c), 4) for c in cosines], "conserved": bool(conserved), "parent": pn, "variant": vn,
           "same_motion_outside_window": outside[:6]}
    if vn:
        out["gradient_fell"] = vn["gradient"] < pn["gradient"]
        out["gradient_ratio"] = round(vn["gradient"] / max(pn["gradient"], 1e-300), 4)
        out["local_coupling_fell"] = vn["gradient_over_sqrt_p"] < pn["gradient_over_sqrt_p"]
        d_total = var["rate"] - par["rate"]
        d_fam = vn["rate_300K_s-1"] - pn["rate_300K_s-1"]
        out["delta_rate_300K_s-1"] = {"total": d_total, "family": d_fam, "unmatched": d_total - d_fam}
        out["mechanism_claim"] = bool(conserved and d_total < 0 and d_fam < 0 and d_fam / d_total > 0.5 and out["local_coupling_fell"])
        out["spread"] = {"parent": round(_spread(par, pfam), 5), "variant": round(_spread(var, vfam), 5)}
    return out


def paired_ratio(var: dict, par: dict, pooled: bool) -> dict:
    """min over sigma of T1_var / T1_par (main couplings), or of lo_var / hi_par (pooled bands)."""
    r = {s: (var["band"][s][0] / par["band"][s][1]) if pooled else var["t1"][s] / par["t1"][s] for s in SIGMAS}
    return {"per_sigma": {f"{s:g}": round(v, 4) for s, v in r.items()}, "min": round(min(r.values()), 4)}


# --------------------------------------------------------------------------- ORCA outputs (C2, C3)


def parse_cas_output(path: Path) -> dict:
    """CASSCF roots (energy, configurations over the active orbitals), Loewdin reduced active-MO compositions and the QDPT
    g-matrix ('ELECTRONIC G-MATRIX FROM EFFECTIVE HAMILTONIAN') of an ORCA 6 output."""
    text = Path(path).read_text(errors="ignore")
    act = re.search(r"Active\s+(\d+)\s*-\s*(\d+)\s*\(\s*\d+\s+orbitals\)", text)
    k = text.rfind("CAS-SCF STATES FOR BLOCK")
    roots = []
    for line in text[k:].splitlines()[3:] if k >= 0 else []:
        m = re.match(r"\s*ROOT\s+\d+:\s+E=\s+(-?[\d.]+)\s+Eh", line)
        if m:
            roots.append({"E": float(m.group(1)), "configs": []})
            continue
        m = re.match(r"\s+([\d.]+)\s+\[\s*\d+\]:\s+([0-2]+)\s*$", line)
        if m and roots:
            roots[-1]["configs"].append((float(m.group(1)), m.group(2)))
        elif roots and line.strip() and not m:
            break
    comp: dict[int, dict] = {}
    k = text.rfind("LOEWDIN REDUCED ACTIVE MOs")
    if k >= 0:
        end = text.find("ORCA POPULATION ANALYSIS", k)
        cols = []
        for line in text[k:end if end > 0 else None].splitlines()[2:]:
            t = line.split()
            if t and all(x.isdigit() for x in t):
                cols = [int(x) for x in t]
                for c in cols:
                    comp.setdefault(c, {})
                continue
            m = re.match(r"\s*(\d+)\s+([A-Z][a-z]?)\s+(\S+)\s+((?:-?[\d.]+\s*)+)$", line)
            if m and cols:
                vals = [float(x) for x in m.group(4).split()]
                for c, v in zip(cols, vals):
                    comp[c][(int(m.group(1)), m.group(3))] = v
    g = None
    for title in ("QDPT WITH NEVPT2 DIAGONAL ENERGIES", "QDPT WITH CASSCF DIAGONAL ENERGIES"):
        k = text.find(title)
        j = text.find("ELECTRONIC G-MATRIX FROM EFFECTIVE HAMILTONIAN", k) if k >= 0 else -1
        m = re.search(r"g-matrix:\s*\n((?:\s*-?[\d.]+\s+-?[\d.]+\s+-?[\d.]+\s*\n){3})", text[j:]) if j >= 0 else None
        if m:
            g = np.array([[float(x) for x in row.split()] for row in m.group(1).strip().splitlines()])
            break
    return {"active": (int(act.group(1)), int(act.group(2))) if act else None, "roots": roots, "composition": comp, "g": g,
            "terminated": "ORCA TERMINATED NORMALLY" in text, "converged": "THE CAS-SCF GRADIENT HAS CONVERGED" in text}


def characterize_roots(parsed: dict, metal_atom: int) -> list[dict]:
    """Per root: its d-d weight (configurations with exactly one open shell, on a metal-d orbital, and every ligand-dominant
    active orbital doubly occupied) and the d character of that open shell (Loewdin populations of the 5 d labels, weighted over
    those configurations). 'dd' when the d-d weight is >= 0.5, else 'ct' (ligand hole or several open shells). Near-degenerate
    d-d states mix under a distortion, so a root is characterised by its whole d vector, not one configuration."""
    a, b = parsed["active"]
    orbs = list(range(a, b + 1))
    frac = []
    for mo in orbs:
        c = parsed["composition"].get(mo, {})
        frac.append(np.array([c.get((metal_atom, lab), 0.0) for lab in ORCA_D]) / 100.0)
    d_dom = [f.sum() >= 0.5 for f in frac]
    out = []
    for root in parsed["roots"]:
        total = sum(w for w, _ in root["configs"]) or 1.0
        vec, dd = np.zeros(5), 0.0
        for w, occ in root["configs"]:
            if len(occ) != len(orbs):
                raise ValueError(f"configuration {occ} does not span the {len(orbs)} active orbitals")
            open_ = [i for i, ch in enumerate(occ) if ch == "1"]
            if len(open_) == 1 and d_dom[open_[0]] and all(d_dom[i] or occ[i] == "2" for i in range(len(orbs))):
                dd += w / total
                vec += w * frac[open_[0]] / max(frac[open_[0]].sum(), 1e-12)
        vec = vec / max(np.linalg.norm(vec), 1e-12)
        out.append({"E": root["E"], "kind": "dd" if dd >= 0.5 else "ct", "dd_weight": round(dd, 4), "vec": vec,
                    "label": ORCA_D[int(np.argmax(vec))] if dd >= 0.5 else None})
    return out


def _gg(g: np.ndarray) -> np.ndarray:
    return g @ g.T


def _rel_change(new: np.ndarray, ref: np.ndarray, scale: float) -> float:
    return float(np.linalg.norm(new - ref) / max(np.linalg.norm(ref), FLOOR * scale, 1e-300))


def _echoed_input(out_text: str) -> str:
    """The input file ORCA echoes at the top of its output ('| 12> ...' lines up to ****END OF INPUT****)."""
    lines = []
    for line in out_text.splitlines():
        m = re.match(r"\|\s*\d+>\s?(.*)$", line)
        if m:
            if "****END OF INPUT****" in m.group(1):
                break
            lines.append(m.group(1))
    return "\n".join(lines) + "\n"


def _load_checks(root: Path, path: str, mat: dict, check: str) -> dict:
    """A t1_loop_check_manifest.json of export_t1_loop_check_inputs, verified against the material and its sweeps' integrity,
    with every member parsed. Missing / running outputs -> {'missing': [...]}."""
    from ElAgenteQ.skill_library import orca_sweeps as osw
    from ElAgenteQ.skill_library.slurm_interaction.slurm_tools import _orca_output_diagnostics

    cpath = _h._resolve_path(root, path, must_exist=True, dir_ok=False)
    cm = _json(cpath)
    if cm.get("kind") != "t1_loop_checks" or cm.get("check") != check:
        raise ValueError(f"{cpath.name} is not a {check} manifest of export_t1_loop_check_inputs")
    for key in ("couplings", "manifest", "phonopy_params"):
        if cm["material_sha256"].get(key) != mat["shas"][key]:
            raise ValueError(f"{cpath.name} was exported for another material ({key} differs)")
    parsed, missing, problems = {}, [], []
    for sweep, spath in cm["sweeps"].items():
        sw = _json(_h._resolve_path(root, spath, must_exist=True, dir_ok=False))
        integrity = osw._integrity_problems(root, sw)
        if integrity:
            problems.append(f"{sweep}: inputs changed after export {dict(list(integrity.items())[:3])}")
        for job in sw["jobs"]:
            out = root / job["expected_output_path"]
            label = job["job_label"]
            sha = (cm.get("pointcharge_sha256") or {}).get(sweep, {}).get(label)
            if sha and _sha((root / job["input_path"]).parent / "embedding.pc") != sha:
                problems.append(f"{sweep}/{label}: displaced point charges changed after export")
            if not out.is_file() or _orca_output_diagnostics(out)["scientific_state"] != "validated":
                missing.append(f"{sweep}/{label}")
                continue
            # the output must come from THIS input: a job from an earlier export of the same folder can land its output here
            text = out.read_text(errors="ignore")
            if "THE CAS-SCF GRADIENT HAS CONVERGED" not in text:
                problems.append(f"{sweep}/{label}: CASSCF stopped without gradient convergence; rerun that member")
                continue
            echo = _echoed_input(text)
            if osw.protocol_sha256(echo) != sw["protocol_sha256"] or osw.geometry_sha256(echo) != job.get("geometry_sha256"):
                problems.append(f"{sweep}/{label}: the output was produced by a different input (stale job?); rerun that member")
                continue
            parsed[(sweep, label)] = parse_cas_output(out)
    if problems:
        raise ValueError("; ".join(problems))
    return {"manifest": cm, "parsed": parsed, "missing": missing, "path": _h._rel(root, cpath)}


def _match_dd(small: list[dict], large: list[dict]) -> dict:
    """small root index -> large root index: the assignment of the 5 small-CAS d-d roots onto larger-CAS d-d roots that maximises
    the summed d-character overlap; pairs below MATCH_COS are dropped (the state lost its match)."""
    from scipy.optimize import linear_sum_assignment

    cand = [j for j, r in enumerate(large) if r["kind"] == "dd"]
    if not cand:
        return {}
    cos = np.array([[float(s_["vec"] @ large[j]["vec"]) for j in cand] for s_ in small])
    rows, cols = linear_sum_assignment(-cos)
    return {int(i): cand[j] for i, j in zip(rows, cols) if cos[i, j] >= MATCH_COS}


def _c2_material(chk: dict, metal_atom: int) -> dict:
    """C2 on one material: per mode the d-d state tracking at -2Q, 0, +2Q (absolute: these fail), and the sums the hit/parent
    comparison uses -- sum ||d(g g^T)/dQ|| and sum |d gap/dQ| of the three low excited d-d states over the top modes, at both
    active spaces. The derivatives are compared only as hit/parent ratios (_c2_pair, user decision 2026-10-16): on the seed
    CAS(n,5) -> CAS(n+10,10) moved d(g g^T)/dQ by -43..-48% on every top mode, the common covalency scaling."""
    cm, parsed = chk["manifest"], chk["parsed"]
    modes, fails, dg = [], [], {}
    sums = {"sum_dggT": {"small": 0.0, "large": 0.0}, "sum_gap": {"small": 0.0, "large": 0.0}}
    for mode in cm["modes"]:
        labels = {"m": f"m{mode['mode']:04d}_m2", "0": "reference", "p": f"m{mode['mode']:04d}_p2"}
        rec = {"mode": mode["mode"], "frequency_cm1": mode["frequency_cm1"]}
        gaps, below_by_geo, inside = {}, {}, {}
        for geo, label in labels.items():
            small = characterize_roots(parsed[("small", label)], metal_atom)
            large = characterize_roots(parsed[("large", label)], metal_atom)
            if len(small) != 5 or any(r["kind"] != "dd" for r in small):
                raise ValueError(f"C2 small CAS at {label}: expected 5 d-d roots, got {[r['kind'] for r in small]}")
            order = sorted(range(5), key=lambda i: small[i]["E"])
            match = _match_dd(small, large)
            lost = [small[i]["label"] for i in order if i not in match]
            if lost:
                fails.append(f"mode {mode['mode']} {geo}: d-d root(s) {lost} have no larger-CAS counterpart")
                continue
            span = small[order[-1]]["E"] - small[order[0]]["E"]
            for i0, i1 in zip(order, order[1:]):
                if large[match[i1]]["E"] < large[match[i0]]["E"] and small[i1]["E"] - small[i0]["E"] > DEGENERATE * span:
                    fails.append(f"mode {mode['mode']} {geo}: d-d ordering changed ({small[i0]['label']}/{small[i1]['label']})")
            ct = [r["E"] for r in large if r["kind"] != "dd"]
            below_by_geo[geo] = [sum(e < large[match[i]]["E"] for e in ct) for i in order]  # CT roots under each d-d state
            if below_by_geo[geo][1] > 0:
                fails.append(f"mode {mode['mode']} {geo}: a charge-transfer root lies below the first excited d-d state "
                             "(the lowest excitation is not a d-d state)")
            top = max(large[j]["E"] for j in match.values())
            inside[geo] = [round((e - large[match[order[0]]]["E"]) * es.EH_TO_CM1) for e in ct if e < top]
            gaps[geo] = ([(small[i]["E"] - small[order[0]]["E"]) * es.EH_TO_CM1 for i in order[1:]],
                         [(large[match[i]]["E"] - large[match[order[0]]]["E"]) * es.EH_TO_CM1 for i in order[1:]])
        if len({tuple(v) for v in below_by_geo.values()}) > 1:
            fails.append(f"mode {mode['mode']}: a d-d state crosses a charge-transfer root along the mode {below_by_geo}")
        rec["ct_roots_inside_dd_manifold_cm1"] = inside.get("0")
        q2 = 2 * float(mode["q"])
        if "m" in gaps and "p" in gaps:
            ds = [(p - m) / (2 * q2) for p, m in zip(gaps["p"][0], gaps["m"][0])]
            dl = [(p - m) / (2 * q2) for p, m in zip(gaps["p"][1], gaps["m"][1])]
            sums["sum_gap"]["small"] += sum(abs(x) for x in ds[:3])
            sums["sum_gap"]["large"] += sum(abs(x) for x in dl[:3])
            rec["gap_derivatives_cm1_per_Q"] = {"small": [round(x, 3) for x in ds], "large": [round(x, 3) for x in dl]}
        g = {lvl: {s_: parsed[(lvl, labels[s_])]["g"] for s_ in ("m", "p")} for lvl in ("small", "large")}
        if any(x is None for lvl in g.values() for x in lvl.values()):
            raise ValueError(f"C2 mode {mode['mode']}: a QDPT g-matrix is missing (rel dosoc/gtensor)")
        dg[mode["mode"]] = {lvl: (_gg(g[lvl]["p"]) - _gg(g[lvl]["m"])) / (2 * q2) for lvl in g}
        modes.append(rec)
    scale = max(np.linalg.norm(v["small"]) for v in dg.values())
    for m, v in dg.items():
        next(r for r in modes if r["mode"] == m)["dggT_rel_change"] = round(_rel_change(v["large"], v["small"], scale), 4)
        for lvl in ("small", "large"):
            sums["sum_dggT"][lvl] += float(np.linalg.norm(v[lvl]))
    return {"modes": modes, "fails": fails, **sums}


def _c3_material(chk: dict) -> dict:
    cm, parsed = chk["manifest"], chk["parsed"]
    dg, fails, sums = {}, [], {"fixed": 0.0, "comoving": 0.0}
    for mode in cm["modes"]:
        q = float(mode["q"])
        lab = {s: f"m{mode['mode']:04d}_{s}1" for s in ("m", "p")}
        g = {e: {s: parsed[(e, lab[s])]["g"] for s in lab} for e in ("fixed", "comoving")}
        if any(x is None for e in g.values() for x in e.values()):
            raise ValueError(f"C3 mode {mode['mode']}: a QDPT g-matrix is missing")
        dg[mode["mode"]] = {e: (_gg(g[e]["p"]) - _gg(g[e]["m"])) / (2 * q) for e in g}
    scale = max(np.linalg.norm(v["fixed"]) for v in dg.values())
    rows = []
    for m, v in dg.items():
        rel = _rel_change(v["comoving"], v["fixed"], scale)
        rows.append({"mode": m, "dggT_rel_change": round(rel, 4)})
        if rel > REL_TOL:
            fails.append(f"mode {m}: d(g g^T)/dQ moves {rel:.0%} when the counterion charges move with the mode")
        for e in sums:
            sums[e] += float(np.linalg.norm(v[e]))
    return {"modes": rows, "fails": fails, "sum_dggT": sums}


def _c2_pair(var_res: dict, par_res: dict) -> tuple[list[str], dict]:
    """C2 derivatives, relative: for sum ||d(g g^T)/dQ|| and the summed low d-d gap derivatives, the hit/parent ratio at
    CAS(n+10,10) must agree with the one at CAS(n,5) within 20% and stay on the same side of 1."""
    fails, ratios = [], {}
    for key in ("sum_dggT", "sum_gap"):
        r = {lvl: var_res[key][lvl] / max(par_res[key][lvl], 1e-300) for lvl in ("small", "large")}
        ratios[key] = {k: round(v, 4) for k, v in r.items()}
        if abs(r["large"] / max(r["small"], 1e-300) - 1) > REL_TOL:
            fails.append(f"C2: hit/parent {key} ratio {r['small']:.3f} at CAS(n,5) vs {r['large']:.3f} at the larger CAS (> 20% apart)")
        if (r["small"] < 1) != (r["large"] < 1):
            fails.append(f"C2: hit/parent ordering of {key} flips between the active spaces ({r['small']:.3f} vs {r['large']:.3f})")
    return fails, ratios


def _pair_check(kind: str, var_res: dict, par_res: dict, levels: tuple[str, str]) -> list[str]:
    a, b = levels
    before = var_res["sum_dggT"][a] < par_res["sum_dggT"][a]
    after = var_res["sum_dggT"][b] < par_res["sum_dggT"][b]
    return [] if before == after else [f"{kind}: the hit/parent ordering of sum ||d(g g^T)/dQ|| flips from {a} to {b}"]


# --------------------------------------------------------------------------- receipts and state


def _receipts(root: Path) -> list[dict]:
    from ElAgenteQ.skill_library.campaign_ledger import campaign_ledger as L

    path = root / L.RECEIPTS_RELATIVE_PATH
    out = []
    if path.is_file():
        for line in path.read_text().splitlines():
            try:
                rec = json.loads(line)
            except ValueError:
                continue
            if rec.get("validator") == VALIDATOR and L._signature_ok(rec):
                out.append(rec)
    return out


def loop_state(root: Path) -> dict:
    """Seed, incumbent, every variant's latest verdict and the stop state -- from this validator's signed receipts only."""
    seed, incumbent, chain, latest = None, None, [], {}
    for n, r in enumerate(_receipts(root)):  # file order = time order
        d = r.get("details") or {}
        if d.get("kind") == "seed":
            seed = incumbent = d
            chain = []
        elif d.get("kind") == "promotion":
            incumbent = d
            chain.append(d["candidate"])
        elif d.get("kind") == "variant":
            latest.pop(d["candidate"], None)  # re-insert: dict order = order of the latest verdicts
            latest[d["candidate"]] = d | {"ts": r["ts"], "receipt": r["id"], "n": n}
    finals = [d for d in latest.values() if d["move"] != "host_check" and d["verdict"] in ("confirmed", "rejected")]
    streak = 0
    for d in finals:
        streak = streak + 1 if d["verdict"] == "rejected" else 0
    stop = {"consecutive_rejections": streak, "rejections_limit": streak >= STOP_REJECTIONS}
    if seed and incumbent:
        gain = min(incumbent["t1_s"][f"{s:g}"] / seed["t1_s"][f"{s:g}"] for s in SIGMAS)
        stop.update({"incumbent_over_seed_min_sigma": round(gain, 4), "gain_reached": gain >= STOP_GAIN,
                     "seed_over_vopc": round(seed["t1_s"][f"{CENTRAL_SIGMA:g}"] / VOPC_T1_300K_S, 4),
                     "seed_too_slow": seed["t1_s"][f"{CENTRAL_SIGMA:g}"] < VOPC_T1_300K_S / 2})
    stop["stop"] = bool(stop.get("rejections_limit") or stop.get("gain_reached") or stop.get("seed_too_slow"))
    return {"seed": seed, "incumbent": incumbent, "variants": latest, "stop": stop, "chain": chain}


def _plain(obj):
    """JSON-native copy (numpy scalars/arrays, tuples) so the signed receipt is canonical."""
    return json.loads(json.dumps(obj, default=lambda o: o.item() if hasattr(o, "item") and np.ndim(o) == 0 else
                                 (o.tolist() if hasattr(o, "tolist") else str(o))))


def _record(root: Path, *, passed: bool, candidate: str, gate: str | None, details: dict, artifacts, summary: str, value=None) -> dict:
    from ElAgenteQ.skill_library.campaign_ledger.campaign_ledger import record_validator_receipt

    values = [{"kind": METRIC, "value": float(value), "tol": 0.0}] if value is not None else None
    return record_validator_receipt(root, validator=VALIDATOR, passed=passed, artifacts=[root / a for a in artifacts], summary=summary,
                                    candidate=candidate or None, gate=gate, details=_plain(details), values=values)


def _set_incumbent(root: Path, receipt: dict, candidate: str, value: float, snapshot: str, source: str) -> None:
    from ElAgenteQ.skill_library.campaign_ledger.campaign_ledger import set_validator_sota

    set_validator_sota(root, METRIC, owner={"validator": VALIDATOR, "gate": INCUMBENT_GATE},
                       best={"value": value, "candidate": candidate, "receipt": receipt["id"], "snapshot": snapshot},
                       unit="s", direction="higher",
                       bar_source=f"loop incumbent ({source}); Protocol P T1_II at 300 K, sigma 10 cm-1; set only by {VALIDATOR}")


def _material_summary(mat: dict) -> dict:
    return {"snapshot": mat["snapshot"], "spec": mat["spec"], "files": mat["files"],
            "t1_s": {f"{s:g}": mat["t1"][s] for s in SIGMAS}, "band_s": {f"{s:g}": mat["band"][s] for s in SIGMAS},
            "coupling_sets": sorted(mat["sets"]), "top_modes": top_modes(mat)}


def _reload(root: Path, summary: dict) -> dict:
    mat = load_material(root, summary["spec"])
    if mat["snapshot"] != summary["snapshot"]:
        raise ValueError(f"the files of snapshot {summary['snapshot']} changed since it was judged (now {mat['snapshot']})")
    return mat


def _core_hours(dirs: list[str], root: Path) -> float | None:
    try:
        res = subprocess.run(["sacct", "-X", "-n", "-P", "-S", "2026-01-01", "--format=JobID,AllocCPUS,ElapsedRaw,WorkDir"],
                             capture_output=True, text=True, timeout=120)
    except (OSError, subprocess.TimeoutExpired):
        return None
    if res.returncode != 0:
        return None
    prefixes = tuple(str(_h._resolve_path(root, d)).rstrip("/") for d in dirs)
    total = 0.0
    for line in res.stdout.splitlines():
        parts = line.split("|", 3)
        if len(parts) == 4 and parts[3].rstrip("/").startswith(prefixes) and parts[1].isdigit() and parts[2].isdigit():
            total += int(parts[1]) * int(parts[2]) / 3600.0
    return total


# --------------------------------------------------------------------------- the tool


def judge_t1_loop(
    action: Annotated[str, "'seed' (register the seed baseline: the first incumbent), 'variant' (judge one variant against its parent "
                           "snapshot), 'promote' (apply the round-winner rule to a finished round) or 'status' (incumbent, verdicts, stop state)."],
    candidate: Annotated[str, "Ledger candidate id of the seed or variant (seed / variant actions)."] = "",
    couplings_json: Annotated[str, "Main excited_state_couplings.json of collect_excited_state_couplings (NEVPT2 members)."] = "",
    displacement_manifest: Annotated[str, "excited_state_displacements_manifest.json of export_excited_state_displacements."] = "",
    phonon_dir: Annotated[str, "The crystal phonon directory the export used (phonopy_params.yaml; its sha256 must match)."] = "",
    t1_json: Annotated[str, "compute_excited_state_spin_relaxation output at broadening 10 cm-1, 0.345 T, with 300 K among its temperatures."] = "",
    replicate_couplings: Annotated[str, "Optional space-separated couplings files of start-orbital replicate sweeps (electronic step only): "
                                        "they widen the C1 band."] = "",
    parent_snapshot: Annotated[str, "variant / promote: the incumbent snapshot (snap-...) the variant was proposed against."] = "",
    move: Annotated[str, f"variant: one of {MOVES} (host_check = the one-off MoO host control; it never promotes)."] = "",
    structure_source: Annotated[str, f"variant: {SOURCES} -- 'clari' and 'deposited_disordered' need every other carried packing / "
                                     "ordered model in packings_json (C4)."] = "",
    designed_modes: Annotated[str, "variant: space-separated PARENT mode indices of the motion the move targets (top_modes 'mode')."] = "",
    c2_manifest: Annotated[str, "t1_loop_check_manifest.json (check c2) of this material; parent_c2_manifest is the parent's."] = "",
    parent_c2_manifest: Annotated[str, "The parent's C2 manifest (C2 compares hit and parent)."] = "",
    c3_manifest: Annotated[str, "Counterion swaps: t1_loop_check_manifest.json (check c3) of this material."] = "",
    parent_c3_manifest: Annotated[str, "Counterion swaps: the parent's C3 manifest."] = "",
    packings_json: Annotated[str, "Clari / disordered variants: JSON list of the OTHER carried packings or ordered models (within 2 kJ/mol "
                                  "per formula unit), each {couplings, manifest, phonon_dir, t1}; [] when only one is carried."] = "",
    calculation_dirs: Annotated[str, "Space-separated directories holding this variant's Slurm jobs (core-hour tie-breaker)."] = "",
    round_candidates: Annotated[str, "promote: space-separated candidate ids of the round (every one needs a final verdict)."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Deterministic judge of a one-change-at-a-time T1 campaign (T1_LOOP_PLAN.md): recomputes Gamma_II T1(300 K) at sigma 5/10/20
    from the raw couplings, applies the paired 1.2x hit rule, the mode-family match with participation normalisation, C1-C4, the
    round-winner and stop rules, and records signed receipts. Only its receipts set sota.T1_300K_s and the loop_accept gate."""
    root = _h._root(runtime)
    try:
        state = loop_state(root)
        if action == "status":
            rec = _record(root, passed=True, candidate="", gate=None,
                          details={"kind": "status", "stop": state["stop"], "chain": state["chain"]}, artifacts=[],
                          summary=f"stop={state['stop']['stop']} {state['stop']}")
            return {"ok": True, "incumbent": state["incumbent"] and {k: state["incumbent"].get(k) for k in ("candidate", "snapshot", "t1_s")},
                    "seed": state["seed"] and {k: state["seed"].get(k) for k in ("candidate", "snapshot", "t1_s")},
                    "verdicts": {c: {k: d.get(k) for k in ("verdict", "move", "parent_snapshot", "reasons", "stale_parent")}
                                 for c, d in state["variants"].items()},
                    "promotion_chain": state["chain"], "stop": state["stop"], "validator_receipt": rec["id"]}
        if action == "promote":
            return _promote(root, state, parent_snapshot.strip(), round_candidates.split())
        if not candidate.strip():
            raise ValueError("candidate is required")
        spec = {"couplings": couplings_json, "manifest": displacement_manifest, "phonon_dir": phonon_dir, "t1": t1_json,
                "replicates": replicate_couplings.split()}
        mat = load_material(root, spec)
        if action == "seed":
            if state["chain"]:
                raise ValueError(f"the incumbent has already moved on ({state['chain']}); the seed cannot be re-registered")
            summary = {"kind": "seed", "candidate": candidate, **_material_summary(mat)}
            if c2_manifest.strip():
                summary["c2_manifest"] = c2_manifest.strip()
            if c3_manifest.strip():
                summary["c3_manifest"] = c3_manifest.strip()
            rec = _record(root, passed=True, candidate=candidate, gate=INCUMBENT_GATE, details=summary, artifacts=mat["files"].values(),
                          summary=f"seed {candidate} {mat['snapshot']}: T1(300 K) {mat['t1'][10.0]:.4g} s (sigma 10), band "
                                  f"{ {f'{s:g}': [round(x, 9) for x in mat['band'][s]] for s in SIGMAS} }", value=mat["t1"][CENTRAL_SIGMA])
            _set_incumbent(root, rec, candidate, mat["t1"][CENTRAL_SIGMA], mat["snapshot"], "seed")
            st = loop_state(root)
            return {"ok": True, "snapshot": mat["snapshot"], "T1_300K_s": summary["t1_s"], "band_s": summary["band_s"],
                    "coupling_sets": summary["coupling_sets"], "top_modes": summary["top_modes"],
                    "c1_band_set": len(mat["sets"]) > 1 and any(k.startswith("replicate") for k in mat["sets"]),
                    "stop": st["stop"], "validator_receipt": rec["id"]}
        if action != "variant":
            raise ValueError("action must be seed, variant, promote or status")
        args = {"move": move, "structure_source": structure_source, "parent_snapshot": parent_snapshot, "designed_modes": designed_modes,
                "c2_manifest": c2_manifest, "parent_c2_manifest": parent_c2_manifest, "c3_manifest": c3_manifest,
                "parent_c3_manifest": parent_c3_manifest, "packings_json": packings_json, "calculation_dirs": calculation_dirs}
        return _judge_variant(root, state, mat, candidate.strip(), args)
    except Exception as exc:
        return _h._error(exc)


def _incumbent_by_snapshot(state: dict, snapshot: str) -> dict:
    seed, inc = state["seed"], state["incumbent"]
    if not seed:
        raise ValueError("no seed registered: run judge_t1_loop(action='seed') first")
    for d in (inc, seed):
        if d and d["snapshot"] == snapshot:
            return d
    raise ValueError(f"{snapshot} is not the seed or the incumbent ({inc['snapshot']}); bind variants to the incumbent's snapshot")


def _judge_variant(root: Path, state: dict, var: dict, cand: str, a: dict) -> dict:
    move, source = a["move"].strip(), a["structure_source"].strip()
    if move not in MOVES or source not in SOURCES:
        raise ValueError(f"move must be one of {MOVES} and structure_source one of {SOURCES}")
    pdet = _incumbent_by_snapshot(state, a["parent_snapshot"].strip())
    par = _reload(root, pdet)
    if var["snapshot"] == par["snapshot"]:
        raise ValueError("the variant's files are the parent's")
    designed = [int(x) for x in a["designed_modes"].split()]
    fam = match_family(par, var, designed)
    hit_ratio = paired_ratio(var, par, pooled=False)
    t1_ok = hit_ratio["min"] >= HIT_RATIO
    conserved = fam["conserved"]
    fell = bool(fam.get("gradient_fell"))
    reasons, checks = [], {}
    if not t1_ok:
        reasons.append(f"T1 ratio {hit_ratio['min']:.3f} < {HIT_RATIO} at some sigma {hit_ratio['per_sigma']}")
    if conserved and not fell:
        reasons.append(f"the matched family's coupling gradient did not fall (x{fam.get('gradient_ratio')})")
    hit = t1_ok and (fell or not conserved) and move != "host_check"
    path = "designed_family" if conserved else "total_T1_only (family not conserved: unassigned crystal/phonon-spectrum effect)"
    if hit:
        pooled = paired_ratio(var, par, pooled=True)
        c1 = {"pooled_ratio": pooled, "fails": []}
        if pooled["min"] < HIT_RATIO:
            c1["fails"].append(f"pooled band ratio {pooled['min']:.3f} < {HIT_RATIO}")
        if conserved:
            dec = 1 - fam["gradient_ratio"]
            spread = fam["spread"]["parent"] + fam["spread"]["variant"]
            c1["gradient_decrease"], c1["combined_spread"] = round(dec, 4), round(spread, 4)
            if dec <= spread:
                c1["fails"].append(f"family-gradient decrease {dec:.3f} does not exceed the numerical spread {spread:.3f}")
        checks["C1"] = c1
        if a["c2_manifest"].strip() and a["parent_c2_manifest"].strip():
            cv = _load_checks(root, a["c2_manifest"], var, "c2")
            cp_ = _load_checks(root, a["parent_c2_manifest"], par, "c2")
            if cv["missing"] or cp_["missing"]:
                checks["C2"] = {"missing": (cv["missing"] + cp_["missing"])[:12]}
            else:
                rv, rp_ = _c2_material(cv, var["metal"]), _c2_material(cp_, par["metal"])
                pair_fails, ratios = _c2_pair(rv, rp_)
                checks["C2"] = {"variant": rv, "parent": rp_, "hit_over_parent": ratios,
                                "fails": rv["fails"] + [f"parent: {f}" for f in rp_["fails"]] + pair_fails}
        else:
            checks["C2"] = {"missing": ["c2_manifest and parent_c2_manifest (export_t1_loop_check_inputs check='c2')"]}
        if move == "counterion_swap":
            if a["c3_manifest"].strip() and a["parent_c3_manifest"].strip():
                cv = _load_checks(root, a["c3_manifest"], var, "c3")
                cp_ = _load_checks(root, a["parent_c3_manifest"], par, "c3")
                if cv["missing"] or cp_["missing"]:
                    checks["C3"] = {"missing": (cv["missing"] + cp_["missing"])[:12]}
                else:
                    rv, rp_ = _c3_material(cv), _c3_material(cp_)
                    checks["C3"] = {"variant": rv, "parent": rp_, "fails": rv["fails"] + [f"parent: {f}" for f in rp_["fails"]]
                                    + _pair_check("C3", rv, rp_, ("fixed", "comoving"))}
            else:
                checks["C3"] = {"missing": ["c3_manifest and parent_c3_manifest (export_t1_loop_check_inputs check='c3')"]}
        if source in ("clari", "deposited_disordered"):
            packs = json.loads(a["packings_json"]) if a["packings_json"].strip() else None
            if packs is None:
                checks["C4"] = {"missing": ["packings_json: every other carried packing within 2 kJ/mol (or [] when only one)"]}
            else:
                rows, fails = [], []
                for k, ps in enumerate(packs):
                    pm = load_material(root, ps)
                    f = match_family(par, pm, designed)
                    rows.append({"packing": k + 1, "snapshot": pm["snapshot"], "conserved": f["conserved"], "gradient_ratio": f.get("gradient_ratio")})
                    if not (f["conserved"] and f.get("gradient_fell")):
                        fails.append(f"packing {k + 1}: designed family {'not conserved' if not f['conserved'] else 'gradient did not fall'}")
                checks["C4"] = {"packings": rows, "fails": fails}
    missing = [k for k, v in checks.items() if "missing" in v]
    failed = [k for k, v in checks.items() if v.get("fails")]
    reasons += [f"{k}: {f}" for k in failed for f in checks[k]["fails"][:4]]
    if move == "host_check":
        verdict = "control"
    elif not hit or failed:
        verdict = "rejected"
    elif missing:
        verdict = "pending_checks"
    else:
        verdict = "confirmed"
    stale = pdet["snapshot"] != state["incumbent"]["snapshot"]
    details = {"kind": "variant", "candidate": cand, "parent_snapshot": pdet["snapshot"], "parent": pdet["candidate"], "move": move,
               "structure_source": source, "designed_modes": designed, "verdict": verdict, "hit": hit, "path": path,
               "paired_ratio": hit_ratio, "family": {k: fam[k] for k in fam if k not in ("parent", "variant")} | {
                   "parent": fam["parent"], "variant": fam["variant"]}, "checks": checks, "reasons": reasons, "stale_parent": stale,
               "calculation_dirs": a["calculation_dirs"].split(), "parent_band_s": pdet["band_s"], **_material_summary(var)}
    gate = ACCEPT_GATE if verdict in ("confirmed", "rejected") else None
    rec = _record(root, passed=verdict == "confirmed", candidate=cand, gate=gate, details=details,
                  artifacts=var["files"].values(), value=var["t1"][CENTRAL_SIGMA],
                  summary=f"{cand} vs {pdet['candidate']}: {verdict}; paired T1 ratio min {hit_ratio['min']:.3f}; family "
                          f"{'conserved' if conserved else 'not conserved'}, gradient x{fam.get('gradient_ratio')}; " + "; ".join(reasons)[:200])
    st = loop_state(root)
    return {"ok": True, "verdict": verdict, "hit": hit, "path": path, "reasons": reasons, "missing_checks": missing,
            "paired_T1_ratio": hit_ratio, "family": details["family"], "checks": {k: {kk: vv for kk, vv in v.items() if kk != "variant" and kk != "parent"}
                                                                                 for k, v in checks.items()},
            "snapshot": var["snapshot"], "stale_parent": stale, "stop": st["stop"], "validator_receipt": rec["id"],
            "next": ("re-judge against the current incumbent " + st["incumbent"]["snapshot"]) if stale else
                    ("run the missing checks, then judge again" if verdict == "pending_checks" else
                     "when every variant of the round has a final verdict: judge_t1_loop(action='promote', ...)")}


def _promote(root: Path, state: dict, parent: str, round_ids: list[str]) -> dict:
    if not round_ids:
        raise ValueError("round_candidates is required")
    inc = state["incumbent"]
    if not inc or parent != inc["snapshot"]:
        raise ValueError(f"promote against the current incumbent {inc and inc['snapshot']}, not {parent}")
    rows = {}
    for c in round_ids:
        d = state["variants"].get(c)
        if not d or d["parent_snapshot"] != parent:
            raise ValueError(f"{c} has no verdict against {parent}")
        if d["verdict"] == "pending_checks":
            raise ValueError(f"{c} is still pending checks: the round is not finished")
        rows[c] = d
    eligible = [c for c, d in rows.items() if d["verdict"] == "confirmed" and d["move"] != "host_check"]
    stale = [c for c in eligible if rows[c].get("parent_band_s") not in (None, inc["band_s"])]
    if stale:
        raise ValueError(f"{stale} were judged before the parent's band changed (replicates added): judge them again")
    details = {"kind": "round", "parent_snapshot": parent, "round": round_ids, "eligible": eligible}
    winner, rule = None, ""
    if len(eligible) == 1:
        winner, rule = eligible[0], "single confirmed hit"
    elif len(eligible) > 1:
        bands = {c: rows[c]["band_s"] for c in eligible}
        beats = [c for c in eligible if all(min(bands[c][f"{s:g}"][0] / bands[o][f"{s:g}"][1] for s in SIGMAS) > 1 for o in eligible if o != c)]
        if beats:
            winner, rule = beats[0], "paired band rule (lower band edge above every other hit's upper edge at every sigma)"
        else:
            clari = {c: int(rows[c]["structure_source"] == "clari") for c in eligible}
            least = [c for c in eligible if clari[c] == min(clari.values())]
            if len(least) == 1:
                winner, rule = least[0], "unresolved bands; tie-breaker: fewest Clari-sourced structures"
            else:
                hours = {c: _core_hours(rows[c]["calculation_dirs"], root) if rows[c]["calculation_dirs"] else None for c in least}
                details["core_hours"] = hours
                if all(h is not None for h in hours.values()) and len(set(hours.values())) == len(hours):
                    winner = min(hours, key=hours.get)
                    rule = "unresolved bands; tie-breaker: fewest core-hours (sacct over calculation_dirs)"
                else:
                    rule = "unresolved: bands overlap and the tie-breakers do not separate the hits (run C1 replicates or ask the user)"
    details.update({"winner": winner, "rule": rule})
    if winner is None:
        rec = _record(root, passed=False, candidate="", gate=None, details=details, artifacts=[],
                      summary=f"round vs {parent}: no promotion ({rule or 'no confirmed hit'})")
        return {"ok": True, "promoted": None, "rule": rule or "no confirmed hit: the incumbent stays", "eligible": eligible,
                "stop": loop_state(root)["stop"], "validator_receipt": rec["id"]}
    w = rows[winner]
    mat = load_material(root, w["spec"])
    if mat["snapshot"] != w["snapshot"]:
        raise ValueError(f"{winner}'s files changed since it was judged")
    details.update({"kind": "promotion", "candidate": winner, "snapshot": w["snapshot"], "spec": w["spec"], "files": w["files"],
                    "t1_s": w["t1_s"], "band_s": w["band_s"], "top_modes": w["top_modes"]})
    rec = _record(root, passed=True, candidate=winner, gate=INCUMBENT_GATE, details=details, artifacts=mat["files"].values(),
                  value=w["t1_s"][f"{CENTRAL_SIGMA:g}"], summary=f"{winner} promoted over {parent} ({rule})")
    _set_incumbent(root, rec, winner, w["t1_s"][f"{CENTRAL_SIGMA:g}"], w["snapshot"], f"promoted by {rule}")
    return {"ok": True, "promoted": winner, "snapshot": w["snapshot"], "rule": rule, "eligible": eligible,
            "stop": loop_state(root)["stop"], "validator_receipt": rec["id"]}


# --------------------------------------------------------------------------- C2 / C3 inputs


def _mode_q(mat: dict, j: int) -> tuple[np.ndarray, float]:
    """Cartesian displacement per unit Q (metal frame) of mode position j and the export's step: first-shell rms 0.01 A, no atom
    beyond 0.05 A."""
    d = (mat["vecs"][j] / np.repeat(np.sqrt(mat["masses"]), 3)).reshape(-1, 3)
    shell = [mat["metal"]] + mat["donors"]
    fs = math.sqrt(float((d[shell] ** 2).sum(axis=1).mean()))
    return d, min(STEP_FS_ANGSTROM / fs, MAX_ATOM_ANGSTROM / float(np.linalg.norm(d, axis=1).max()))


def _xyz(path: Path, symbols, xyz, comment: str) -> None:
    path.write_text(f"{len(symbols)}\n{comment}\n" + "".join(f"{s:<3}{p[0]:18.10f}{p[1]:18.10f}{p[2]:18.10f}\n" for s, p in zip(symbols, xyz)))


def _comoving_charges(root: Path, mat: dict, mode_index: int, q: float) -> tuple[np.ndarray, np.ndarray, int]:
    """(charges, metal-frame positions of the export's embedding.pc displaced by q along the crystal mode, n moved): explicit
    charges sit on cell atoms and move with them (minus the molecule's removed net translation); fitted sphere charges stay."""
    man = mat["man"]
    gs = sr.load_gamma_set(root, _h._rel(root, mat["ph"]), "")
    cm = _json(_h._resolve_path(root, man["reference_manifest"], must_exist=True, dir_ok=False))
    pc_cluster = np.loadtxt(_h._resolve_path(root, cm["pointcharge_file"], must_exist=True, dir_ok=False), skiprows=1, ndmin=2)
    pc_frame = np.loadtxt(mat["mpath"].parent / man["embedding"]["pointcharge_file"], skiprows=1, ndmin=2)
    rot = np.array(man["frame"]["rotation_rows_new_axes"], dtype=float)
    if pc_cluster.shape != pc_frame.shape or np.abs(pc_cluster[:, 1:] @ rot.T - pc_frame[:, 1:]).max() > 1e-4:
        raise ValueError("the export's embedding.pc is not the carve's point charges in the metal frame")
    cell = np.array(gs.phonon.primitive.cell, dtype=float)
    frac_atoms = np.array(gs.phonon.primitive.scaled_positions, dtype=float)
    centre = frac_atoms[int(cm["center_index"])] @ cell
    mol = [int(at["cell_atom"]) for at in man["atoms"]]
    m = gs.masses
    e = gs.vecs[:, mode_index].reshape(-1, 3)
    shift = (np.sqrt(m[mol])[:, None] * e[mol]).sum(axis=0) / m[mol].sum()  # the net translation the export removed
    t = translations(m[mol])
    vec = ((e[mol].ravel() - t @ (t.T @ e[mol].ravel())).reshape(-1, 3) @ rot.T).ravel()
    ref = mat["vecs"][mat["indices"].index(mode_index)]
    cos = float(vec @ ref / (np.linalg.norm(vec) * np.linalg.norm(ref)))
    if abs(cos) < 0.999:
        raise ValueError(f"mode {mode_index}: the phonon set's eigenvector differs from the export's (overlap {cos:.4f})")
    sign = 1.0 if cos > 0 else -1.0
    moved = pc_frame[:, 1:].copy()
    n = 0
    inv = np.linalg.inv(cell)
    for k, r in enumerate(pc_cluster[:, 1:] + centre):
        df = (r @ inv - frac_atoms + 0.5) % 1.0 - 0.5
        dist = np.linalg.norm(df @ cell, axis=1)
        i = int(np.argmin(dist))
        if dist[i] < 0.02:
            moved[k] += rot @ (sign * q * (e[i] / math.sqrt(m[i]) - shift))
            n += 1
    return pc_frame[:, 0], moved, n


def export_t1_loop_check_inputs(
    check: Annotated[str, "'c2' (CAS(n,5) vs the larger active space at 0, +/-2Q) or 'c3' (Protocol P members at +/-Q, fixed vs co-moving point charges)."],
    couplings_json: Annotated[str, "Main excited_state_couplings.json of the material."],
    displacement_manifest: Annotated[str, "Its excited_state_displacements_manifest.json (orca/reference.gbw and sweep_template.inp beside it)."],
    phonon_dir: Annotated[str, "Its crystal phonon directory."],
    top_n: Annotated[int, "Number of top relaxing modes (300 K Gamma_II rate share, sigma 10)."] = 3,
    extra_inactive_orbitals: Annotated[int, "C2: k highest inactive orbitals of the reference added to the 5 d -> CAS(n+2k, 5+k)."] = 5,
    nroots_large: Annotated[int, "C2: doublet roots of the larger CAS (the 5 d-d states plus charge-transfer states)."] = 12,
    output_dir: Annotated[str, "Default <manifest folder>/t1_loop_<check>."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Write the C2 or C3 ORCA sweeps of one material for judge_t1_loop: displaced geometries along its top relaxing modes, the
    sweep inputs through prepare_orca_displacement_sweep (same protocol hashing) and t1_loop_check_manifest.json. Then
    submit_orca_displacement_sweep each listed sweep and pass the manifest to judge_t1_loop."""
    from ElAgenteQ.skill_library import orca_sweeps as osw

    root = _h._root(runtime)
    try:
        if check not in ("c2", "c3"):
            raise ValueError("check must be 'c2' or 'c3'")
        mat = load_material(root, {"couplings": couplings_json, "manifest": displacement_manifest, "phonon_dir": phonon_dir}, need_t1=False)
        man, orca = mat["man"], mat["mpath"].parent / "orca"
        template = (orca / "sweep_template.inp").read_text()
        gbw = orca / "reference.gbw"
        if not gbw.is_file():
            raise FileNotFoundError(f"{_h._rel(root, gbw)} missing: the material's Gamma_II reference must have run")
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else mat["mpath"].parent / f"t1_loop_{check}")
        (out / "displaced_xyz").mkdir(parents=True, exist_ok=True)
        symbols, ref = mat["symbols"], mat["positions"]
        _xyz(out / "reference.xyz", symbols, ref, "t1 loop check reference (metal frame)")
        modes, members = [], []
        mult = 2 if check == "c2" else 1
        for mode in top_modes(mat, int(top_n)):
            j = mat["indices"].index(mode)
            d, q = _mode_q(mat, j)
            modes.append({"mode": mode, "frequency_cm1": round(float(mat["freqs"][j]), 2), "share_300K": round(float(mat["share"][j]), 4), "q": q})
            for sign, tag in ((1, "p"), (-1, "m")):
                label = f"m{mode:04d}_{tag}{mult}"
                disp = sign * mult * q * d
                _xyz(out / "displaced_xyz" / f"{label}.xyz", symbols, ref + disp, f"mode {mode} Q = {sign * mult * q:.8f}")
                members.append({"member": label, "qm_xyz": f"displaced_xyz/{label}.xyz", "displacement": np.round(disp, 12).tolist(),
                                "mode": mode, "sign": sign})
        (out / "displacements.json").write_text(json.dumps({"kind": "random", "reference_cluster": "reference.xyz", "rms_angstrom": STEP_FS_ANGSTROM * mult,
                                                            "atoms": [{"cluster_atom": i} for i in range(len(symbols))], "members": members}))
        pc = orca / "embedding.pc"
        prints = "%output\n  Print[P_ReducedOrbPopMO_L] 1\nend\n"
        n_cas = int(man["d_count"])
        if check == "c2":
            small = re.sub(r"(?im)^\s*ptmethod\s+\S+\s*\n", "", template)
            large = re.sub(r"(?im)^(\s*nel)\s+\d+", rf"\g<1> {n_cas + 2 * int(extra_inactive_orbitals)}", small)
            large = re.sub(r"(?im)^(\s*norb)\s+\d+", rf"\g<1> {5 + int(extra_inactive_orbitals)}", large)
            large = re.sub(r"(?im)^(\s*nroots)\s+\d+", rf"\g<1> {int(nroots_large)}", large)
            # natural active orbitals: LocOrbs splits the covalent V=O sigma/pi bonds (the added frontier orbitals of a vanadyl)
            # into atomic V d and O p functions and spreads every root over dozens of ionic/covalent configurations (seed,
            # 2026-10-15: SA d occupation 3.1, top configuration weight 0.04); in natural orbitals d-d roots stay single-
            # configurational. The members' etol (1e-10) is kept: with 1e-8 ORCA stopped on the energy with ||g|| 1.1e-4 > gtol.
            large = re.sub(r"(?im)^(\s*actorbs)\s+dorbs", r"\g<1> natorbs", large)
            large = re.sub(r"(?im)^(\s*maxiter)\s+\d+", r"\g<1> 200", large)
            texts = {"small": small, "large": large}
        else:
            if not pc.is_file():
                raise ValueError("C3 needs an embedded cluster (ewald_fit point charges); this material's export has none")
            texts = {"fixed": template, "comoving": template}
        texts = {k: v.replace("%casscf", prints + "%casscf", 1) for k, v in texts.items()}
        prepare = getattr(osw.prepare_orca_displacement_sweep, "func", osw.prepare_orca_displacement_sweep)
        sweeps, pc_sha = {}, {}
        for name, text in texts.items():
            tdir = out / f"template_{name}"
            tdir.mkdir(exist_ok=True)
            (tdir / f"{name}.inp").write_text(f"# t1 loop {check} ({name}) of {_h._rel(root, mat['mpath'])}\n" + text)
            if pc.is_file():
                (tdir / "embedding.pc").write_bytes(pc.read_bytes())
            res = prepare(reference_input=_h._rel(root, tdir / f"{name}.inp"), displacement_manifest=_h._rel(root, out / "displacements.json"),
                          runtime=runtime, reference_gbw=_h._rel(root, gbw), output_dir=_h._rel(root, out / f"sweep_{name}"), overwrite=True)
            if not res.get("ok"):
                raise ValueError(f"prepare_orca_displacement_sweep ({name}): {res.get('error')} {res.get('problems', '')}")
            sweeps[name] = res["sweep_manifest"]
            if name == "comoving":
                pc_sha[name] = {}
                for mem in members:
                    charges, pos, n = _comoving_charges(root, mat, mem["mode"], mem["sign"] * next(x["q"] for x in modes if x["mode"] == mem["mode"]))
                    if n == 0:
                        raise ValueError("no explicit point charge sits on a crystal atom: nothing would move")
                    path = out / f"sweep_{name}" / mem["member"] / "embedding.pc"
                    path.write_text(f"{len(charges)}\n" + "".join(f"{c:14.8f}{p[0]:16.8f}{p[1]:16.8f}{p[2]:16.8f}\n" for c, p in zip(charges, pos)))
                    pc_sha[name][mem["member"]] = _sha(path)
        cm = {"kind": "t1_loop_checks", "check": check, "material_sha256": {k: mat["shas"][k] for k in ("couplings", "manifest", "phonopy_params")},
              "material_snapshot_files": mat["files"], "metal_atom": mat["metal"], "modes": modes, "sweeps": sweeps,
              "pointcharge_sha256": pc_sha, "extra_inactive_orbitals": int(extra_inactive_orbitals) if check == "c2" else None,
              "nroots_large": int(nroots_large) if check == "c2" else None}
        (out / "t1_loop_check_manifest.json").write_text(json.dumps(cm, indent=1))
        return {"ok": True, "check_manifest": _h._rel(root, out / "t1_loop_check_manifest.json"), "sweeps": sweeps, "modes": modes,
                "active_spaces": {"small": f"CAS({n_cas},5)", "large": f"CAS({n_cas + 2 * int(extra_inactive_orbitals)},{5 + int(extra_inactive_orbitals)})"}
                if check == "c2" else None,
                "next_steps": [f"submit_orca_displacement_sweep(sweep_manifest='{s}', execution_mode='dry_run'), then submit" for s in sweeps.values()]
                + ["judge_t1_loop(..., c2_manifest / c3_manifest = the check_manifest above)"]}
    except Exception as exc:
        return _h._error(exc)


t1_loop_tool_map = {name: tool(fn) for name, fn in {
    "judge_t1_loop": judge_t1_loop,
    "export_t1_loop_check_inputs": export_t1_loop_check_inputs,
}.items()}
