#!/usr/bin/env python3
"""Join 2: e vs E2 vs o Caller/State Selector across all 805 QO·k·A·d·y hosts.

Reads frozen research snapshots strictly read-only and writes deterministic
outputs only inside ../../../resources/tools/provenance/index.html#s-0f91a5bb95bed40f
"""

from __future__ import annotations

import hashlib
import json
import math
import random
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

import numpy as np

JOIN_DIR = Path(__file__).resolve().parent.parent
ANALYSIS_PATH = JOIN_DIR / "ANALYSIS.json"
RECEIPT_PATH = JOIN_DIR / "RECEIPT.json"

SRC_SNAPSHOT = Path(
    "../../../resources/tools/provenance/index.html#s-f7b743c9687c88d6"
)
SRC_TARGETS = Path(
    "../../../resources/tools/provenance/index.html#s-fc57cc085de81461"
)
SRC_SOURCE_REL = Path(
    "../../../resources/tools/provenance/index.html#s-38382d88f4d9ec29"
)
SRC_HANDS = Path(
    "../../../resources/tools/provenance/index.html#s-7912361b3b7aaa63"
)
SRC_EXPANDED = Path(
    "../../../resources/tools/provenance/index.html#s-8e1f4e57a86251ef"
)
SRC_CONDITIONAL = Path(
    "../../../resources/tools/provenance/index.html#s-85a9a88b435a9d31"
)
SRC_CATALOG = Path(
    "../../../resources/tools/provenance/index.html#s-c05a5e1f710a8133"
)

SEED = 20261128
N_PERM = 2000
PRIMARY_CHIPS = ("e", "[E2]", "o")


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def load_json_ro(path: Path) -> Any:
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def is_qok_dy(ops: list[str]) -> bool:
    return len(ops) >= 5 and ops[:2] == ["[QO]", "k"] and ops[-2:] == ["d", "y"]


def is_qot_dy(ops: list[str]) -> bool:
    return len(ops) >= 5 and ops[:2] == ["[QO]", "t"] and ops[-2:] == ["d", "y"]


def is_ch_dy(ops: list[str]) -> bool:
    return len(ops) >= 4 and ops[0] == "[CH]" and ops[-2:] == ["d", "y"]


def unique_mode(counts: Counter[str]) -> tuple[str | None, str]:
    if not counts:
        return None, "unseen"
    top = max(counts.values())
    winners = sorted(k for k, v in counts.items() if v == top)
    if len(winners) == 1:
        return winners[0], "predicted"
    return None, "tied"


def exact_binomial_two_sided(k: int, n: int, p: float = 0.5) -> float | None:
    if n == 0:
        return None
    if abs(p - 0.5) < 1e-12:
        p_obs = math.comb(n, k) / (2**n)
        total = sum(math.comb(n, i) for i in range(n + 1) if math.comb(n, i) / (2**n) <= p_obs + 1e-15)
        return min(1.0, total / (2**n))
    p_obs = math.comb(n, k) * (p**k) * ((1 - p) ** (n - k))
    total = 0.0
    for i in range(n + 1):
        pi = math.comb(n, i) * (p**i) * ((1 - p) ** (n - i))
        if pi <= p_obs + 1e-15:
            total += pi
    return min(1.0, total)


def exact_binomial_one_sided_ge(k: int, n: int) -> float | None:
    if n == 0:
        return None
    return sum(math.comb(n, i) for i in range(k, n + 1)) / (2**n)


def exact_fisher_2x2(a: int, b: int, c: int, d: int) -> dict[str, Any]:
    """Exact two-sided Fisher hypergeometric test for [[a, b], [c, d]]."""
    r1, r2 = a + b, c + d
    c1, c2 = a + c, b + d
    n = r1 + r2
    if n == 0 or r1 == 0 or r2 == 0 or c1 == 0 or c2 == 0:
        return {"p_two_sided": None, "odds_ratio": None}
    denom = math.comb(n, r1)
    lo = max(0, r1 - c2)
    hi = min(r1, c1)
    p_obs = math.comb(c1, a) * math.comb(c2, r1 - a) / denom
    p_two = 0.0
    for x in range(lo, hi + 1):
        px = math.comb(c1, x) * math.comb(c2, r1 - x) / denom
        if px <= p_obs + 1e-15:
            p_two += px
    odds_ratio = (a * d) / (b * c) if (b * c) > 0 else (math.inf if a * d > 0 else None)
    return {"p_two_sided": min(1.0, p_two), "odds_ratio": None if odds_ratio == math.inf else odds_ratio}


def pearson_chi2(table: np.ndarray, rng: random.Random | None = None, n_perm: int = 0) -> dict[str, Any]:
    """Compute Pearson chi-square, Cramer's V, asymptotic p (if df=1), and MC permutation p."""
    table = np.asarray(table, dtype=np.int64)
    n = int(table.sum())
    if n == 0:
        return {"n": 0, "chi2": None, "df": 0, "cramers_v": None, "p_asymp": None, "p_perm": None}
    row_sums = table.sum(axis=1, keepdims=True)
    col_sums = table.sum(axis=0, keepdims=True)
    expected = (row_sums * col_sums) / float(n)
    mask = expected > 0
    chi2 = float(np.sum(((table[mask] - expected[mask]) ** 2) / expected[mask]))
    r, c = table.shape
    df = (r - 1) * (c - 1)
    k_min = min(r - 1, c - 1)
    v = math.sqrt(chi2 / (n * k_min)) if (n * k_min) > 0 else 0.0
    p_asymp = math.erfc(math.sqrt(chi2 / 2.0)) if df == 1 else (math.exp(-chi2 / 2.0) if df == 2 else None)

    p_perm = None
    if n_perm > 0 and rng is not None and df > 0:
        rows_idx = []
        cols_idx = []
        for ri in range(r):
            for ci in range(c):
                cnt = int(table[ri, ci])
                if cnt > 0:
                    rows_idx.extend([ri] * cnt)
                    cols_idx.extend([ci] * cnt)
        cols_perm = list(cols_idx)
        ge = 0
        for _ in range(n_perm):
            rng.shuffle(cols_perm)
            sim = np.zeros((r, c), dtype=np.int64)
            for ri, ci in zip(rows_idx, cols_perm):
                sim[ri, ci] += 1
            c_sim = float(np.sum(((sim[mask] - expected[mask]) ** 2) / expected[mask]))
            if c_sim >= chi2 - 1e-12:
                ge += 1
        p_perm = (1 + ge) / (n_perm + 1)

    return {
        "n": n,
        "chi2": chi2,
        "df": df,
        "cramers_v": v,
        "p_asymp": p_asymp,
        "p_perm": p_perm,
        "min_expected": float(expected.min()),
    }


def kruskal_wallis_perm(groups: list[list[float]], rng: random.Random, n_perm: int = N_PERM) -> dict[str, Any]:
    """Kruskal-Wallis H statistic on average ranks + exact Monte Carlo permutation p-value."""
    non_empty = [g for g in groups if len(g) > 0]
    if len(non_empty) < 2:
        return {"H": None, "p_perm": None, "n": sum(len(g) for g in groups)}
    all_vals: list[float] = []
    sizes: list[int] = []
    for g in non_empty:
        all_vals.extend(g)
        sizes.append(len(g))
    n = len(all_vals)
    # Assign midranks
    indexed = sorted(enumerate(all_vals), key=lambda x: x[1])
    ranks = np.zeros(n, dtype=np.float64)
    i = 0
    tie_correction = 0.0
    while i < n:
        j = i
        while j + 1 < n and indexed[j + 1][1] == indexed[i][1]:
            j += 1
        avg_rank = 0.5 * (i + j) + 1.0
        for idx_pos in range(i, j + 1):
            ranks[indexed[idx_pos][0]] = avg_rank
        t = j - i + 1
        if t > 1:
            tie_correction += t * (t * t - 1)
        i = j + 1

    denom_tie = 1.0 - tie_correction / (n * (n * n - 1)) if n > 1 else 1.0
    if denom_tie <= 0:
        return {"H": 0.0, "p_perm": 1.0, "n": n}

    def h_stat(r_arr: np.ndarray) -> float:
        offset = 0
        s = 0.0
        for sz in sizes:
            r_sum = float(r_arr[offset : offset + sz].sum())
            s += (r_sum * r_sum) / sz
            offset += sz
        h_raw = (12.0 / (n * (n + 1))) * s - 3.0 * (n + 1)
        return h_raw / denom_tie

    h_obs = h_stat(ranks)
    perm_ranks = ranks.tolist()
    ge = 0
    for _ in range(n_perm):
        rng.shuffle(perm_ranks)
        if h_stat(np.asarray(perm_ranks, dtype=np.float64)) >= h_obs - 1e-12:
            ge += 1
    return {"H": h_obs, "p_perm": (1 + ge) / (n_perm + 1), "n": n, "group_sizes": sizes}


def boundary_marks_for_line(line: dict[str, Any]) -> list[str | None] | None:
    cursor = 0
    marks: list[str | None] = []
    raw = line["raw"]
    for idx, g in enumerate(line["groups"]):
        pos = raw.find(g["raw"], cursor)
        if pos < cursor:
            return None
        gap = raw[cursor:pos]
        if idx > 0:
            if "<->" in gap:
                marks.append("<->")
            elif "," in gap:
                marks.append(",")
            elif "." in gap:
                marks.append(".")
            else:
                marks.append(gap or None)
        cursor = pos + len(g["raw"])
    return marks


def build_corpus_index() -> dict[str, Any]:
    css = load_json_ro(SRC_SNAPSHOT)
    ata = load_json_ro(SRC_TARGETS)["targets"]
    asr = load_json_ro(SRC_SOURCE_REL)["targets"]
    hp = load_json_ro(SRC_HANDS)
    efa = load_json_ro(SRC_EXPANDED)["groups"]

    ata_by_id = {t["id"]: t for t in ata}
    asr_by_id = {r["target"]["id"]: r["source"] for r in asr}
    efa_by_id = {g["id"]: g for g in efa}

    units: dict[str, list[dict[str, Any]]] = defaultdict(list)
    pages_by_folio: dict[str, dict[str, Any]] = {}
    groups_by_id: dict[str, dict[str, Any]] = {}
    folio_groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
    line_marks: dict[str, list[str | None] | None] = {}

    qok_805: list[dict[str, Any]] = []
    qot_all_dy: list[dict[str, Any]] = []
    ch_e2_dy: list[dict[str, Any]] = []
    ch_eo_dy: list[dict[str, Any]] = []

    for p in css["pages"]:
        folio = p["folio"]
        pages_by_folio[folio] = p
        prov = hp[folio]
        for li, line in enumerate(p["lines"]):
            locus = line["id"]
            unit = line.get("paragraph") or locus
            marks = boundary_marks_for_line(line)
            line_marks[locus] = marks
            for gi, g in enumerate(line["groups"], 1):
                gid = f"{locus}:G{gi}"
                ops = list(g.get("ops") or [])
                rec = {
                    "id": gid,
                    "folio": folio,
                    "support": prov["physical_support"],
                    "Davis_hand": prov["Davis_hand_H"],
                    "Currier_hand": prov["Currier_hand_C"],
                    "Currier_language": prov["Currier_language_L"],
                    "section": p["section"],
                    "unit": unit,
                    "locus": locus,
                    "line_idx_in_page": li,
                    "group": gi,
                    "line_group_count": len(line["groups"]),
                    "register": line["register"],
                    "paragraph": line.get("paragraph"),
                    "ops": ops,
                    "raw": g.get("raw"),
                    "uncertain": bool(g.get("uncertain", False)),
                    "source_status": g.get("source_status"),
                    "unit_pos": len(units[unit]),
                    "folio_pos": len(folio_groups[folio]),
                }
                units[unit].append(rec)
                folio_groups[folio].append(rec)
                groups_by_id[gid] = rec
                if is_qok_dy(ops):
                    qok_805.append(rec)
                if is_qot_dy(ops):
                    qot_all_dy.append(rec)
                if ops == ["[CH]", "[E2]", "d", "y"]:
                    ch_e2_dy.append(rec)
                if ops == ["[CH]", "e", "o", "d", "y"]:
                    ch_eo_dy.append(rec)

    assert len(css["pages"]) == 227
    assert len(qok_805) == 805
    assert {g["id"] for g in qok_805} == set(efa_by_id.keys())
    assert len(ata_by_id) == 655
    assert all(tid in groups_by_id for tid in ata_by_id)

    return {
        "pages_by_folio": pages_by_folio,
        "units": dict(units),
        "folio_groups": dict(folio_groups),
        "groups_by_id": groups_by_id,
        "line_marks": line_marks,
        "qok_805": qok_805,
        "qot_all_dy": qot_all_dy,
        "ch_e2_dy": ch_e2_dy,
        "ch_eo_dy": ch_eo_dy,
        "ata": ata,
        "ata_by_id": ata_by_id,
        "asr_by_id": asr_by_id,
        "efa_by_id": efa_by_id,
        "hp": hp,
    }


def extract_task1_features(idx: dict[str, Any]) -> list[dict[str, Any]]:
    units = idx["units"]
    folio_groups = idx["folio_groups"]
    ata_by_id = idx["ata_by_id"]

    # Map each target id to its earlier-host features (masking current and future targets)
    feats_by_id: dict[str, dict[str, Any]] = {}

    for u, seq in units.items():
        first_qok_single = None
        last_qok_single = None
        last_qok_single_anyflag = None
        last_qok_any = None
        last_qot_single = None
        last_qot_any = None
        last_either_single = None

        for g in seq:
            ops = g["ops"]
            qok_any = is_qok_dy(ops)
            qot_any = is_qot_dy(ops)
            qok_single = qok_any and len(ops) == 5
            qot_single = qot_any and len(ops) == 5

            if qok_single and g["id"] in ata_by_id:
                t = ata_by_id[g["id"]]
                feats_by_id[g["id"]] = {
                    **t,
                    "F1_prev_qok_single": last_qok_single["ops"][2] if last_qok_single else None,
                    "F1_prev_qok_single_id": last_qok_single["id"] if last_qok_single else None,
                    "F1b_prev_qok_single_incflag": last_qok_single_anyflag["ops"][2] if last_qok_single_anyflag else None,
                    "F2_prev_qok_any": "|".join(last_qok_any["ops"][2:-2]) if last_qok_any else None,
                    "F3_prev_qot_single": last_qot_single["ops"][2] if last_qot_single else None,
                    "F3_prev_qot_single_id": last_qot_single["id"] if last_qot_single else None,
                    "F3b_prev_qot_any": "|".join(last_qot_any["ops"][2:-2]) if last_qot_any else None,
                    "F4_prev_qok_or_qot_single": last_either_single["ops"][2] if last_either_single else None,
                    "F4_prev_qok_or_qot_kind": last_either_single["kind"] if last_either_single else None,
                    "F5_first_qok_single": first_qok_single["ops"][2] if first_qok_single else None,
                    "F5_first_qok_single_id": first_qok_single["id"] if first_qok_single else None,
                }

            if qok_single and not g["uncertain"]:
                if first_qok_single is None:
                    first_qok_single = g
                last_qok_single = g
                last_either_single = {**g, "kind": "qok"}
            if qok_single:
                last_qok_single_anyflag = g
            if qok_any:
                last_qok_any = g
            if qot_single and not g["uncertain"]:
                last_qot_single = g
                last_either_single = {**g, "kind": "qot"}
            if qot_any:
                last_qot_any = g

    # Add folio-level cross-paragraph F6_prev_qok_single_folio
    for folio, seq in folio_groups.items():
        last_folio_qok = None
        for g in seq:
            ops = g["ops"]
            qok_single = is_qok_dy(ops) and len(ops) == 5
            if qok_single and g["id"] in feats_by_id:
                feats_by_id[g["id"]]["F6_prev_qok_single_folio"] = (
                    last_folio_qok["ops"][2] if last_folio_qok else None
                )
            if qok_single and not g["uncertain"]:
                last_folio_qok = g

    return [feats_by_id[t["id"]] for t in idx["ata"]]


def lofo_baseline_predictions(
    rows: list[dict[str, Any]],
    labels: list[str],
    train_indices: list[int],
    holdout_key: str,
    stratum_fn: Any,
) -> list[str | None]:
    """Unique modal prediction excluding target's holdout_key (folio or support)."""
    total = Counter(labels[i] for i in train_indices)
    by_hold: dict[Any, Counter[str]] = defaultdict(Counter)
    by_strat: dict[Any, Counter[str]] = defaultdict(Counter)
    by_strat_hold: dict[tuple[Any, Any], Counter[str]] = defaultdict(Counter)
    for i in train_indices:
        hk = rows[i][holdout_key]
        sk = stratum_fn(rows[i])
        by_hold[hk][labels[i]] += 1
        by_strat[sk][labels[i]] += 1
        by_strat_hold[(sk, hk)][labels[i]] += 1

    preds: list[str | None] = []
    for r in rows:
        hk = r[holdout_key]
        sk = stratum_fn(r)
        if sk is None or (isinstance(sk, tuple) and any(x is None for x in sk)):
            # Allow Currier_hand=None? Actually if Currier_hand is None we can still stratify on it or mark unseen;
            # keep exact stratum tuple as-is, matching caller_condition_2026-11-27.
            pass
        c = by_strat[sk] - by_strat_hold[(sk, hk)]
        preds.append(unique_mode(c)[0])
    return preds


def lofo_feature_predictions(
    rows: list[dict[str, Any]],
    labels: list[str],
    train_indices: list[int],
    holdout_key: str,
    feat_fn: Any,
) -> list[str | None]:
    by_feat: dict[Any, Counter[str]] = defaultdict(Counter)
    by_feat_hold: dict[tuple[Any, Any], Counter[str]] = defaultdict(Counter)
    for i in train_indices:
        fv = feat_fn(rows[i])
        if fv is None:
            continue
        hk = rows[i][holdout_key]
        by_feat[fv][labels[i]] += 1
        by_feat_hold[(fv, hk)][labels[i]] += 1

    preds: list[str | None] = []
    for r in rows:
        fv = feat_fn(r)
        if fv is None:
            preds.append(None)
        else:
            c = by_feat[fv] - by_feat_hold[(fv, r[holdout_key])]
            preds.append(unique_mode(c)[0])
    return preds


def eval_pair(
    indices: list[int],
    labels: list[str],
    preds: list[str | None],
    baseline: list[str | None],
) -> dict[str, Any]:
    covered = [i for i in indices if preds[i] is not None]
    common = [i for i in covered if baseline[i] is not None]
    cov_corr = sum(preds[i] == labels[i] for i in covered)
    com_m = sum(preds[i] == labels[i] for i in common)
    com_b = sum(baseline[i] == labels[i] for i in common)
    return {
        "eligible": len(indices),
        "covered": len(covered),
        "covered_correct": cov_corr,
        "covered_rate": cov_corr / len(covered) if covered else None,
        "common": len(common),
        "method_correct": com_m,
        "baseline_correct": com_b,
        "increment": com_m - com_b,
        "method_rate": com_m / len(common) if common else None,
        "baseline_rate": com_b / len(common) if common else None,
        "rate_increment": (com_m - com_b) / len(common) if common else None,
    }


def run_task1(idx: dict[str, Any], rng: random.Random) -> dict[str, Any]:
    rows = extract_task1_features(idx)
    labels = [r["true_chip"] for r in rows]
    unflagged = [i for i, r in enumerate(rows) if not r["uncertain"]]
    all_idx = list(range(len(rows)))
    ee2o_unflagged = [i for i in unflagged if labels[i] in PRIMARY_CHIPS]
    ee2o_all = [i for i in all_idx if labels[i] in PRIMARY_CHIPS]

    # Baselines under LOFO (holdout=folio) and LOSO (holdout=support)
    def strat_davis_pos(r: dict[str, Any]) -> tuple[Any, ...]:
        return (r["Davis_hand"], r["section"], r["line_position"])

    def strat_davis_sec(r: dict[str, Any]) -> tuple[Any, ...]:
        return (r["Davis_hand"], r["section"])

    def strat_currier_pos(r: dict[str, Any]) -> tuple[Any, ...]:
        return (r["Currier_hand"], r["section"], r["line_position"])

    def strat_global(_: dict[str, Any]) -> str:
        return "ALL"

    b_lofo_davis_pos = lofo_baseline_predictions(rows, labels, unflagged, "folio", strat_davis_pos)
    b_lofo_davis_sec = lofo_baseline_predictions(rows, labels, unflagged, "folio", strat_davis_sec)
    b_lofo_currier_pos = lofo_baseline_predictions(rows, labels, unflagged, "folio", strat_currier_pos)
    b_lofo_global = lofo_baseline_predictions(rows, labels, unflagged, "folio", strat_global)
    b_loso_davis_pos = lofo_baseline_predictions(rows, labels, unflagged, "support", strat_davis_pos)

    feature_names = [
        "F1_prev_qok_single",
        "F1b_prev_qok_single_incflag",
        "F2_prev_qok_any",
        "F3_prev_qot_single",
        "F3b_prev_qot_any",
        "F4_prev_qok_or_qot_single",
        "F5_first_qok_single",
        "F6_prev_qok_single_folio",
    ]
    single_carry_features = {
        "F1_prev_qok_single",
        "F1b_prev_qok_single_incflag",
        "F3_prev_qot_single",
        "F4_prev_qok_or_qot_single",
        "F5_first_qok_single",
        "F6_prev_qok_single_folio",
    }

    evaluations: dict[str, Any] = {}
    for fname in feature_names:
        lofo_preds = lofo_feature_predictions(rows, labels, unflagged, "folio", lambda r, k=fname: r[k])
        loso_preds = lofo_feature_predictions(rows, labels, unflagged, "support", lambda r, k=fname: r[k])
        entry: dict[str, Any] = {
            "lofo_modal_vs_davis_pos": eval_pair(unflagged, labels, lofo_preds, b_lofo_davis_pos),
            "lofo_modal_vs_davis_sec": eval_pair(unflagged, labels, lofo_preds, b_lofo_davis_sec),
            "lofo_modal_vs_currier_pos": eval_pair(unflagged, labels, lofo_preds, b_lofo_currier_pos),
            "lofo_modal_vs_global": eval_pair(unflagged, labels, lofo_preds, b_lofo_global),
            "lofo_modal_ee2o_vs_davis_pos": eval_pair(ee2o_unflagged, labels, lofo_preds, b_lofo_davis_pos),
            "loso_modal_vs_davis_pos": eval_pair(unflagged, labels, loso_preds, b_loso_davis_pos),
        }
        if fname in single_carry_features:
            direct_preds = [r[fname] for r in rows]
            entry["direct_carry_vs_davis_pos"] = eval_pair(unflagged, labels, direct_preds, b_lofo_davis_pos)
            entry["direct_carry_vs_global"] = eval_pair(unflagged, labels, direct_preds, b_lofo_global)
            entry["direct_carry_ee2o_vs_davis_pos"] = eval_pair(ee2o_unflagged, labels, direct_preds, b_lofo_davis_pos)
            entry["direct_carry_all_targets_655"] = eval_pair(all_idx, labels, direct_preds, b_lofo_davis_pos)
            # Subset where BOTH earlier and target are in {e, [E2], o}
            both_ee2o = [i for i in ee2o_unflagged if direct_preds[i] in PRIMARY_CHIPS]
            entry["direct_carry_both_ee2o"] = eval_pair(both_ee2o, labels, direct_preds, b_lofo_davis_pos)
        evaluations[fname] = entry

    # Hybrid stratum: (Davis_hand, section, line_position, F1_prev_qok_single)
    hybrid_lofo = lofo_feature_predictions(
        rows,
        labels,
        unflagged,
        "folio",
        lambda r: (r["Davis_hand"], r["section"], r["line_position"], r["F1_prev_qok_single"])
        if r["F1_prev_qok_single"] is not None
        else None,
    )
    hybrid_loso = lofo_feature_predictions(
        rows,
        labels,
        unflagged,
        "support",
        lambda r: (r["Davis_hand"], r["section"], r["line_position"], r["F1_prev_qok_single"])
        if r["F1_prev_qok_single"] is not None
        else None,
    )
    hybrid_eval = {
        "lofo_vs_davis_pos": eval_pair(unflagged, labels, hybrid_lofo, b_lofo_davis_pos),
        "lofo_ee2o_vs_davis_pos": eval_pair(ee2o_unflagged, labels, hybrid_lofo, b_lofo_davis_pos),
        "loso_vs_davis_pos": eval_pair(unflagged, labels, hybrid_loso, b_loso_davis_pos),
    }

    # Contingency tables & exact tests for F1_prev_qok_single and F3_prev_qot_single
    def build_contingency(fname: str, chips: tuple[str, ...]) -> dict[str, Any]:
        mat = np.zeros((len(chips), len(chips)), dtype=np.int64)
        chip_to_i = {c: j for j, c in enumerate(chips)}
        for i in unflagged:
            fv = rows[i][fname]
            tv = labels[i]
            if fv in chip_to_i and tv in chip_to_i:
                mat[chip_to_i[fv], chip_to_i[tv]] += 1
        chi = pearson_chi2(mat, rng=rng, n_perm=N_PERM)
        res = {
            "chips": list(chips),
            "matrix": mat.tolist(),
            "chi2_test": chi,
        }
        if len(chips) == 2:
            res["exact_fisher_2x2"] = exact_fisher_2x2(
                int(mat[0, 0]), int(mat[0, 1]), int(mat[1, 0]), int(mat[1, 1])
            )
        return res

    contingencies = {
        "F1_prev_qok_single_2x2_e_E2": build_contingency("F1_prev_qok_single", ("e", "[E2]")),
        "F1_prev_qok_single_3x3_e_E2_o": build_contingency("F1_prev_qok_single", PRIMARY_CHIPS),
        "F3_prev_qot_single_2x2_e_E2": build_contingency("F3_prev_qot_single", ("e", "[E2]")),
        "F3_prev_qot_single_3x3_e_E2_o": build_contingency("F3_prev_qot_single", PRIMARY_CHIPS),
        "F4_prev_qok_or_qot_2x2_e_E2": build_contingency("F4_prev_qok_or_qot_single", ("e", "[E2]")),
        "F5_first_qok_single_2x2_e_E2": build_contingency("F5_first_qok_single", ("e", "[E2]")),
    }

    # Stratified, Within-Folio, and Within-Paragraph permutation tests (recomputing BOTH earlier & target!)
    # Note: shuffling true_chip labels among unflagged targets ALSO changes what the earlier QOk/QOt chip is!
    # That is the exact right null for sequential order/carry vs static stratum/folio/paragraph composition.
    strata_groups: dict[tuple[Any, ...], list[int]] = defaultdict(list)
    folio_groups_idx: dict[str, list[int]] = defaultdict(list)
    para_groups_idx: dict[str, list[int]] = defaultdict(list)
    for i in unflagged:
        strata_groups[strat_davis_pos(rows[i])].append(i)
        folio_groups_idx[rows[i]["folio"]].append(i)
        para_groups_idx[rows[i]["unit"]].append(i)

    # Precompute index chains for F1 (within unit) and F3 (fixed non-target QOt!) and F5 (first in unit)
    unit_qok_targets: dict[str, list[int]] = defaultdict(list)
    for i in unflagged:
        unit_qok_targets[rows[i]["unit"]].append(i)

    def perm_metrics(sim_labels: list[str]) -> dict[str, float]:
        # Direct carry for F1 (earlier unflagged QOk in same unit) and F5 (first unflagged QOk in unit)
        f1_hits = 0
        f1_n = 0
        f5_hits = 0
        f5_n = 0
        f3_hits = 0
        f3_n = 0
        for u, idxs in unit_qok_targets.items():
            for pos, ti in enumerate(idxs):
                if pos > 0:
                    f1_n += 1
                    if sim_labels[idxs[pos - 1]] == sim_labels[ti]:
                        f1_hits += 1
                    f5_n += 1
                    if sim_labels[idxs[0]] == sim_labels[ti]:
                        f5_hits += 1
                if rows[ti]["F3_prev_qot_single"] is not None:
                    f3_n += 1
                    if rows[ti]["F3_prev_qot_single"] == sim_labels[ti]:
                        f3_hits += 1
        # LOFO modal F1 vs LOFO baseline on common covered cases
        # Build F1 value from sim_labels
        sim_f1 = [None] * len(rows)
        for u, idxs in unit_qok_targets.items():
            for pos in range(1, len(idxs)):
                sim_f1[idxs[pos]] = sim_labels[idxs[pos - 1]]
        b_sim = lofo_baseline_predictions(rows, sim_labels, unflagged, "folio", strat_davis_pos)
        f1_lofo_sim = lofo_feature_predictions(rows, sim_labels, unflagged, "folio", lambda r, s=sim_f1, id_map={r["id"]: j for j, r in enumerate(rows)}: s[id_map[r["id"]]])
        ev = eval_pair(unflagged, sim_labels, f1_lofo_sim, b_sim)
        return {
            "f1_carry_rate": f1_hits / f1_n if f1_n else 0.0,
            "f5_carry_rate": f5_hits / f5_n if f5_n else 0.0,
            "f3_carry_rate": f3_hits / f3_n if f3_n else 0.0,
            "f1_lofo_increment": float(ev["increment"]),
        }

    obs_pm = perm_metrics(labels)
    perm_results: dict[str, Any] = {"observed": obs_pm, "n_perm": N_PERM}

    for scope_name, group_dict in [
        ("within_davis_section_linepos_strata", strata_groups),
        ("within_folio", folio_groups_idx),
        ("within_paragraph_unit", para_groups_idx),
    ]:
        counts_ge = Counter()
        null_dists: dict[str, list[float]] = defaultdict(list)
        groups_list = [ix for ix in group_dict.values() if len(ix) >= 2]
        for _ in range(N_PERM):
            sim = list(labels)
            for ix in groups_list:
                vals = [labels[i] for i in ix]
                rng.shuffle(vals)
                for i, v in zip(ix, vals):
                    sim[i] = v
            pm = perm_metrics(sim)
            for k, val in pm.items():
                null_dists[k].append(val)
                if val >= obs_pm[k] - 1e-12:
                    counts_ge[k] += 1
        perm_results[scope_name] = {
            k: {
                "observed": obs_pm[k],
                "null_mean": float(np.mean(null_dists[k])),
                "null_sd": float(np.std(null_dists[k])),
                "p_one_sided_ge": (1 + counts_ge[k]) / (N_PERM + 1),
            }
            for k in obs_pm
        }

    # Explicit f26r carry pattern check
    f26r_rows = [r for r in rows if r["folio"] == "f26r"]
    f26r_summary = [
        {
            "id": r["id"],
            "unit": r["unit"],
            "true_chip": r["true_chip"],
            "F1_prev_qok_single": r["F1_prev_qok_single"],
            "F1_prev_qok_single_id": r["F1_prev_qok_single_id"],
            "F3_prev_qot_single": r["F3_prev_qot_single"],
            "F5_first_qok_single": r["F5_first_qok_single"],
            "lofo_davis_pos_baseline": b_lofo_davis_pos[rows.index(r)],
        }
        for r in f26r_rows
    ]

    return {
        "cohort_counts": {
            "total_single_chip_targets": len(rows),
            "unflagged_single_chip_targets": len(unflagged),
            "flagged_single_chip_targets": len(rows) - len(unflagged),
            "unflagged_e_E2_o_targets": len(ee2o_unflagged),
            "all_e_E2_o_targets": len(ee2o_all),
            "distinct_folios": len({r["folio"] for r in rows}),
            "distinct_supports": len({r["support"] for r in rows}),
            "unflagged_chip_distribution": dict(Counter(labels[i] for i in unflagged)),
        },
        "evaluations": evaluations,
        "hybrid_davis_pos_plus_F1": hybrid_eval,
        "contingencies": contingencies,
        "permutation_tests": perm_results,
        "f26r_carry_audit": f26r_summary,
    }


def summarize_pair_list(pairs: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]]) -> dict[str, Any]:
    """Summarize transition pairs (a, b, meta) and exact binomial test for [E2]->e vs e->[E2]."""
    all_trans = Counter((a["ops"][2] if len(a["ops"]) == 5 else "|".join(a["ops"][2:-2]),
                         b["ops"][2] if len(b["ops"]) == 5 else "|".join(b["ops"][2:-2]))
                        for a, b, _ in pairs)
    unflagged_pairs = [(a, b, m) for a, b, m in pairs if not a["uncertain"] and not b["uncertain"]]
    unflagged_trans = Counter((a["ops"][2] if len(a["ops"]) == 5 else "|".join(a["ops"][2:-2]),
                               b["ops"][2] if len(b["ops"]) == 5 else "|".join(b["ops"][2:-2]))
                              for a, b, _ in unflagged_pairs)

    def asym_block(c: Counter[tuple[str, str]]) -> dict[str, Any]:
        e2_to_e = c[("[E2]", "e")]
        e_to_e2 = c[("e", "[E2]")]
        n_switch = e2_to_e + e_to_e2
        e2_to_e2 = c[("[E2]", "[E2]")]
        e_to_e = c[("e", "e")]
        e2_to_o = c[("[E2]", "o")]
        o_to_e2 = c[("o", "[E2]")]
        e_to_o = c[("e", "o")]
        o_to_e = c[("o", "e")]
        return {
            "E2_to_e": e2_to_e,
            "e_to_E2": e_to_e2,
            "E2_to_E2": e2_to_e2,
            "e_to_e": e_to_e,
            "E2_to_o": e2_to_o,
            "o_to_E2": o_to_e2,
            "e_to_o": e_to_o,
            "o_to_e": o_to_e,
            "n_e_E2_switches": n_switch,
            "exact_binomial_two_sided_p": exact_binomial_two_sided(e2_to_e, n_switch),
            "exact_binomial_one_sided_E2_to_e_ge_p": exact_binomial_one_sided_ge(e2_to_e, n_switch),
        }

    # Breakdown by section and Davis hand (unflagged)
    by_section: dict[str, Any] = {}
    for sec in sorted({a["section"] for a, _, _ in unflagged_pairs}):
        sc = Counter((a["ops"][2] if len(a["ops"]) == 5 else "|".join(a["ops"][2:-2]),
                      b["ops"][2] if len(b["ops"]) == 5 else "|".join(b["ops"][2:-2]))
                     for a, b, _ in unflagged_pairs if a["section"] == sec)
        by_section[sec] = {"total": sum(sc.values()), **asym_block(sc)}

    by_hand: dict[str, Any] = {}
    for h in sorted({str(a["Davis_hand"]) for a, _, _ in unflagged_pairs}):
        hc = Counter((a["ops"][2] if len(a["ops"]) == 5 else "|".join(a["ops"][2:-2]),
                      b["ops"][2] if len(b["ops"]) == 5 else "|".join(b["ops"][2:-2]))
                     for a, b, _ in unflagged_pairs if str(a["Davis_hand"]) == h)
        by_hand[h] = {"total": sum(hc.values()), **asym_block(hc)}

    return {
        "total_pairs": len(pairs),
        "unflagged_pairs": len(unflagged_pairs),
        "all_transitions": {f"{k[0]}->{k[1]}": v for k, v in sorted(all_trans.items())},
        "unflagged_transitions": {f"{k[0]}->{k[1]}": v for k, v in sorted(unflagged_trans.items())},
        "unflagged_asymmetry": asym_block(unflagged_trans),
        "all_asymmetry": asym_block(all_trans),
        "by_section_unflagged": by_section,
        "by_davis_hand_unflagged": by_hand,
    }


def run_task2(idx: dict[str, Any]) -> dict[str, Any]:
    units = idx["units"]
    line_marks = idx["line_marks"]

    same_line_adj_single = []
    unit_adj_single = []
    unit_gap_le1_single = []
    unit_gap_le2_single = []
    unit_consec_qok_single = []
    same_line_adj_805 = []

    for u, seq in sorted(units.items()):
        # Same-line adjacent (single-chip and expanded 805)
        for i in range(len(seq) - 1):
            a, b = seq[i], seq[i + 1]
            a_qok = is_qok_dy(a["ops"])
            b_qok = is_qok_dy(b["ops"])
            a_s = a_qok and len(a["ops"]) == 5
            b_s = b_qok and len(b["ops"]) == 5
            marks = line_marks.get(a["locus"])
            bmark = marks[a["group"] - 1] if (a["locus"] == b["locus"] and marks and a["group"] - 1 < len(marks)) else "LINE_BREAK"
            meta = {"unit_gap": 0, "same_line": a["locus"] == b["locus"], "boundary_mark": bmark}

            if a_s and b_s:
                unit_adj_single.append((a, b, meta))
                if a["locus"] == b["locus"]:
                    same_line_adj_single.append((a, b, meta))
            if a_qok and b_qok and a["locus"] == b["locus"]:
                same_line_adj_805.append((a, b, meta))

        # Near-adjacent in unit (gap <= 1, gap <= 2, and all consecutive single-chip QOk)
        qok_single_positions = [k for k, g in enumerate(seq) if is_qok_dy(g["ops"]) and len(g["ops"]) == 5]
        for idx_pos in range(len(qok_single_positions) - 1):
            p1, p2 = qok_single_positions[idx_pos], qok_single_positions[idx_pos + 1]
            a, b = seq[p1], seq[p2]
            gap = p2 - p1 - 1
            meta = {
                "unit_gap": gap,
                "same_line": a["locus"] == b["locus"],
                "intervening_ids": [seq[k]["id"] for k in range(p1 + 1, p2)],
            }
            unit_consec_qok_single.append((a, b, meta))
            if gap <= 1:
                unit_gap_le1_single.append((a, b, meta))
            if gap <= 2:
                unit_gap_le2_single.append((a, b, meta))

    # Full detailed list for all same-line adjacent single-chip pairs and line-wrap pairs
    detailed_adj = []
    for a, b, m in unit_adj_single:
        detailed_adj.append({
            "first_id": a["id"],
            "second_id": b["id"],
            "folio": a["folio"],
            "unit": a["unit"],
            "Davis_hand": a["Davis_hand"],
            "Currier_hand": a["Currier_hand"],
            "Currier_language": a["Currier_language"],
            "section": a["section"],
            "first_chip": a["ops"][2],
            "second_chip": b["ops"][2],
            "uncertain": a["uncertain"] or b["uncertain"],
            "same_line": m["same_line"],
            "boundary_mark": m["boundary_mark"],
        })

    # Boundary mark cross-check on E2->e vs e->E2
    mark_counts = Counter(
        (d["boundary_mark"], f"{d['first_chip']}->{d['second_chip']}")
        for d in detailed_adj
        if not d["uncertain"] and {d["first_chip"], d["second_chip"]} <= {"e", "[E2]", "o"}
    )

    # Focal checks
    focal_pair_ids = {("f26r.5:G9", "f26r.5:G10"), ("f26r.8:G9", "f26r.8:G10"), ("f43r.12:G6", "f43r.12:G7")}
    focal_records = [d for d in detailed_adj if (d["first_id"], d["second_id"]) in focal_pair_ids]

    return {
        "scopes": {
            "same_line_adjacent_single": summarize_pair_list(same_line_adj_single),
            "unit_adjacent_single": summarize_pair_list(unit_adj_single),
            "unit_gap_le1_single": summarize_pair_list(unit_gap_le1_single),
            "unit_gap_le2_single": summarize_pair_list(unit_gap_le2_single),
            "unit_consecutive_qok_single": summarize_pair_list(unit_consec_qok_single),
            "same_line_adjacent_expanded_805": summarize_pair_list(same_line_adj_805),
        },
        "boundary_mark_breakdown": {f"{k[0]}|{k[1]}": v for k, v in sorted(mark_counts.items())},
        "focal_pairs": focal_records,
        "all_unit_adjacent_single_pairs": detailed_adj,
    }


def unit_context_profile(seq: list[dict[str, Any]]) -> dict[str, Any]:
    n_total = len(seq)
    qok_any = [g for g in seq if len(g["ops"]) >= 2 and g["ops"][:2] == ["[QO]", "k"]]
    qot_any = [g for g in seq if len(g["ops"]) >= 2 and g["ops"][:2] == ["[QO]", "t"]]
    qok_dy = [g for g in seq if is_qok_dy(g["ops"])]
    qot_dy = [g for g in seq if is_qot_dy(g["ops"])]
    qok_eo_dy = [g for g in qok_dy if g["ops"][2:-2] == ["e", "o"]]
    ch_eo_dy = [g for g in seq if g["ops"] == ["[CH]", "e", "o", "d", "y"]]
    ch_e2_dy = [g for g in seq if g["ops"] == ["[CH]", "[E2]", "d", "y"]]
    qok_multi_dy = [g for g in qok_dy if len(g["ops"]) > 5]
    ch_multi_dy = [g for g in seq if is_ch_dy(g["ops"]) and len(g["ops"]) > 4]

    # Alternation across QO-(k|t) sequence in unit
    kt_seq = ["k" if g["ops"][:2] == ["[QO]", "k"] else "t" for g in seq if len(g["ops"]) >= 2 and g["ops"][:2] in (["[QO]", "k"], ["[QO]", "t"])]
    kt_switches = sum(1 for i in range(len(kt_seq) - 1) if kt_seq[i] != kt_seq[i + 1])
    kt_alt_rate = kt_switches / (len(kt_seq) - 1) if len(kt_seq) >= 2 else None

    kt_dy_seq = ["k" if is_qok_dy(g["ops"]) else "t" for g in seq if is_qok_dy(g["ops"]) or is_qot_dy(g["ops"])]
    kt_dy_switches = sum(1 for i in range(len(kt_dy_seq) - 1) if kt_dy_seq[i] != kt_dy_seq[i + 1])
    kt_dy_alt_rate = kt_dy_switches / (len(kt_dy_seq) - 1) if len(kt_dy_seq) >= 2 else None

    n_qo_kt = len(qok_any) + len(qot_any)
    n_qo_kt_dy = len(qok_dy) + len(qot_dy)

    return {
        "n_groups": n_total,
        "qok_any_count": len(qok_any),
        "qot_any_count": len(qot_any),
        "qok_dy_count": len(qok_dy),
        "qot_dy_count": len(qot_dy),
        "qok_eo_dy_count": len(qok_eo_dy),
        "ch_eo_dy_count": len(ch_eo_dy),
        "eo_dy_total_count": len(qok_eo_dy) + len(ch_eo_dy),
        "ch_e2_dy_count": len(ch_e2_dy),
        "qok_multi_dy_count": len(qok_multi_dy),
        "ch_multi_dy_count": len(ch_multi_dy),
        "has_qok_eo_dy": len(qok_eo_dy) > 0,
        "has_ch_eo_dy": len(ch_eo_dy) > 0,
        "has_any_eo_dy": (len(qok_eo_dy) + len(ch_eo_dy)) > 0,
        "has_qot_any": len(qot_any) > 0,
        "has_qot_dy": len(qot_dy) > 0,
        "eo_dy_density_per_group": (len(qok_eo_dy) + len(ch_eo_dy)) / n_total if n_total else 0.0,
        "qok_multi_density_per_qok_dy": len(qok_multi_dy) / len(qok_dy) if qok_dy else 0.0,
        "qot_share_any": len(qot_any) / n_qo_kt if n_qo_kt else None,
        "qot_share_dy": len(qot_dy) / n_qo_kt_dy if n_qo_kt_dy else None,
        "kt_switches_any": kt_switches,
        "kt_alt_rate_any": kt_alt_rate,
        "kt_switches_dy": kt_dy_switches,
        "kt_alt_rate_dy": kt_dy_alt_rate,
    }


def run_task3(idx: dict[str, Any], rng: random.Random) -> dict[str, Any]:
    units = idx["units"]
    ata = idx["ata"]
    ata_by_id = idx["ata_by_id"]
    asr_by_id = idx["asr_by_id"]
    groups_by_id = idx["groups_by_id"]

    unit_profiles = {u: unit_context_profile(seq) for u, seq in units.items()}

    # 1. All 8 o targets
    eight_o_cases = []
    for t in sorted(ata, key=lambda x: x["id"]):
        if t["true_chip"] == "o":
            u_seq = units[t["unit"]]
            pos = [i for i, g in enumerate(u_seq) if g["id"] == t["id"]][0]
            prev_g = u_seq[pos - 1] if pos > 0 else None
            next_g = u_seq[pos + 1] if pos + 1 < len(u_seq) else None
            src = asr_by_id[t["id"]]
            eight_o_cases.append({
                "id": t["id"],
                "unit": t["unit"],
                "folio": t["folio"],
                "support": t["support"],
                "Davis_hand": t["Davis_hand"],
                "Currier_hand": t["Currier_hand"],
                "Currier_language": t["Currier_language"],
                "section": t["section"],
                "line_position": t["line_position"],
                "uncertain": t["uncertain"],
                "raw": t["raw"],
                "prev_group": {"id": prev_g["id"], "ops": prev_g["ops"], "raw": prev_g["raw"]} if prev_g else None,
                "next_group": {"id": next_g["id"], "ops": next_g["ops"], "raw": next_g["raw"]} if next_g else None,
                "following_CH_source": {
                    "status": src["status"],
                    "clean": src.get("clean"),
                    "candidate_id": src["candidates"][0]["source_id"] if src.get("candidates") else None,
                    "candidate_interior": src["candidates"][0]["interior"] if src.get("candidates") else None,
                },
                "paragraph_profile": unit_profiles[t["unit"]],
            })

    # 2. All 5 exact CH·E2·d·y -> QO·k·X·d·y cases (+ expanded multi-chip note)
    ch_e2_exact = []
    ch_e2_expanded = []
    for g in idx["ch_e2_dy"]:
        u_seq = units[g["unit"]]
        pos = [i for i, x in enumerate(u_seq) if x["id"] == g["id"]][0]
        if pos + 1 < len(u_seq):
            nx = u_seq[pos + 1]
            if is_qok_dy(nx["ops"]):
                rec = {
                    "caller_id": g["id"],
                    "receiver_id": nx["id"],
                    "unit": g["unit"],
                    "folio": g["folio"],
                    "Davis_hand": g["Davis_hand"],
                    "Currier_hand": g["Currier_hand"],
                    "Currier_language": g["Currier_language"],
                    "section": g["section"],
                    "receiver_interior": nx["ops"][2:-2],
                    "uncertain": g["uncertain"] or nx["uncertain"],
                    "paragraph_profile": unit_profiles[g["unit"]],
                }
                if len(nx["ops"]) == 5:
                    ch_e2_exact.append(rec)
                else:
                    ch_e2_expanded.append(rec)

    # 3A. All 15 clean observed receivers under CH·e·o·d·y following-source hypothesis
    fifteen_eo_source = []
    for t in sorted(ata, key=lambda x: x["id"]):
        if t["uncertain"]:
            continue
        src = asr_by_id[t["id"]]
        if src["status"] == "source_found" and src.get("candidates") and src["candidates"][0]["interior"] == ["e", "o"]:
            u_seq = units[t["unit"]]
            pos = [i for i, x in enumerate(u_seq) if x["id"] == t["id"]][0]
            prev_g = u_seq[pos - 1] if pos > 0 else None
            fifteen_eo_source.append({
                "target_id": t["id"],
                "unit": t["unit"],
                "true_chip": t["true_chip"],
                "Davis_hand": t["Davis_hand"],
                "Currier_hand": t["Currier_hand"],
                "section": t["section"],
                "source_id": src["candidates"][0]["source_id"],
                "prev_group_ops": prev_g["ops"] if prev_g else None,
                "paragraph_profile": unit_profiles[t["unit"]],
            })

    # 3B. Corpus-wide QO·k·e·o·d·y (33) and CH·e·o·d·y (91) host census + co-occurring single-chip targets
    qok_eo_hosts = [g for g in idx["qok_805"] if g["ops"][2:-2] == ["e", "o"]]
    ch_eo_hosts = idx["ch_eo_dy"]
    qok_eo_units = {g["unit"] for g in qok_eo_hosts}
    ch_eo_units = {g["unit"] for g in ch_eo_hosts}
    any_eo_units = qok_eo_units | ch_eo_units

    cooccur_in_qok_eo_units = Counter(t["true_chip"] for t in ata if not t["uncertain"] and t["unit"] in qok_eo_units)
    cooccur_in_ch_eo_units = Counter(t["true_chip"] for t in ata if not t["uncertain"] and t["unit"] in ch_eo_units)
    cooccur_in_any_eo_units = Counter(t["true_chip"] for t in ata if not t["uncertain"] and t["unit"] in any_eo_units)

    # 4. Statistical comparison across X in {e, [E2], o} (unflagged n=588)
    ee2o_targets = [t for t in ata if not t["uncertain"] and t["true_chip"] in PRIMARY_CHIPS]
    by_chip: dict[str, list[dict[str, Any]]] = {c: [] for c in PRIMARY_CHIPS}
    for t in ee2o_targets:
        by_chip[t["true_chip"]].append({**t, **unit_profiles[t["unit"]]})

    group_summaries = {}
    for c in PRIMARY_CHIPS:
        items = by_chip[c]
        n = len(items)
        qot_shares = [x["qot_share_any"] for x in items if x["qot_share_any"] is not None]
        qot_dy_shares = [x["qot_share_dy"] for x in items if x["qot_share_dy"] is not None]
        kt_alts = [x["kt_alt_rate_any"] for x in items if x["kt_alt_rate_any"] is not None]
        group_summaries[c] = {
            "n_targets": n,
            "n_distinct_units": len({x["unit"] for x in items}),
            "frac_has_qok_eo_dy": sum(x["has_qok_eo_dy"] for x in items) / n,
            "count_has_qok_eo_dy": sum(x["has_qok_eo_dy"] for x in items),
            "frac_has_ch_eo_dy": sum(x["has_ch_eo_dy"] for x in items) / n,
            "count_has_ch_eo_dy": sum(x["has_ch_eo_dy"] for x in items),
            "frac_has_any_eo_dy": sum(x["has_any_eo_dy"] for x in items) / n,
            "count_has_any_eo_dy": sum(x["has_any_eo_dy"] for x in items),
            "mean_eo_dy_density": float(np.mean([x["eo_dy_density_per_group"] for x in items])),
            "mean_qok_multi_density": float(np.mean([x["qok_multi_density_per_qok_dy"] for x in items])),
            "frac_has_qot_any": sum(x["has_qot_any"] for x in items) / n,
            "count_has_qot_any": sum(x["has_qot_any"] for x in items),
            "frac_has_qot_dy": sum(x["has_qot_dy"] for x in items) / n,
            "count_has_qot_dy": sum(x["has_qot_dy"] for x in items),
            "mean_qot_share_any": float(np.mean(qot_shares)) if qot_shares else None,
            "mean_qot_share_dy": float(np.mean(qot_dy_shares)) if qot_dy_shares else None,
            "mean_kt_alt_rate_any": float(np.mean(kt_alts)) if kt_alts else None,
            "n_kt_alt_eligible": len(kt_alts),
        }

    # Contingency & Kruskal-Wallis tests across {e, [E2], o} and pairwise {e, [E2]}
    def binary_3way_chi2(field: str) -> dict[str, Any]:
        mat3 = np.array([
            [sum(bool(x[field]) for x in by_chip[c]), sum(not bool(x[field]) for x in by_chip[c])]
            for c in PRIMARY_CHIPS
        ], dtype=np.int64)
        res3 = pearson_chi2(mat3, rng=rng, n_perm=N_PERM)
        mat2 = mat3[:2, :]
        res2 = pearson_chi2(mat2, rng=rng, n_perm=N_PERM)
        fish2 = exact_fisher_2x2(int(mat2[0, 0]), int(mat2[0, 1]), int(mat2[1, 0]), int(mat2[1, 1]))
        return {
            "matrix_e_E2_o": mat3.tolist(),
            "chi2_3way": res3,
            "chi2_e_vs_E2": res2,
            "fisher_e_vs_E2": fish2,
        }

    tests = {
        "has_qok_eo_dy": binary_3way_chi2("has_qok_eo_dy"),
        "has_ch_eo_dy": binary_3way_chi2("has_ch_eo_dy"),
        "has_any_eo_dy": binary_3way_chi2("has_any_eo_dy"),
        "has_qot_any": binary_3way_chi2("has_qot_any"),
        "has_qot_dy": binary_3way_chi2("has_qot_dy"),
        "kw_eo_dy_density_3way": kruskal_wallis_perm(
            [[x["eo_dy_density_per_group"] for x in by_chip[c]] for c in PRIMARY_CHIPS], rng
        ),
        "kw_qok_multi_density_3way": kruskal_wallis_perm(
            [[x["qok_multi_density_per_qok_dy"] for x in by_chip[c]] for c in PRIMARY_CHIPS], rng
        ),
        "kw_qot_share_any_3way": kruskal_wallis_perm(
            [[x["qot_share_any"] for x in by_chip[c] if x["qot_share_any"] is not None] for c in PRIMARY_CHIPS], rng
        ),
        "kw_kt_alt_rate_any_3way": kruskal_wallis_perm(
            [[x["kt_alt_rate_any"] for x in by_chip[c] if x["kt_alt_rate_any"] is not None] for c in PRIMARY_CHIPS], rng
        ),
    }

    # Stratified permutation test (controlling for Davis_hand x section) for e vs E2 vs o differences
    stratum_items: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
    for item in [x for c in PRIMARY_CHIPS for x in by_chip[c]]:
        stratum_items[(str(item["Davis_hand"]), str(item["section"]))].append(item)

    # Check if stratified permutation confirms null when controlling hand+section
    def stat_o_any_eo(items_by_stratum: dict[tuple[str, str], list[tuple[str, dict[str, Any]]]]) -> float:
        o_cnt = 0
        o_hit = 0
        for lst in items_by_stratum.values():
            for lbl, feat in lst:
                if lbl == "o":
                    o_cnt += 1
                    if feat["has_any_eo_dy"]:
                        o_hit += 1
        return o_hit / o_cnt if o_cnt else 0.0

    obs_o_eo = sum(x["has_any_eo_dy"] for x in by_chip["o"]) / len(by_chip["o"])
    obs_e2_qok_eo = sum(x["has_qok_eo_dy"] for x in by_chip["[E2]"]) / len(by_chip["[E2]"])
    obs_e_qok_eo = sum(x["has_qok_eo_dy"] for x in by_chip["e"]) / len(by_chip["e"])
    obs_diff_e2_e_qok_eo = obs_e2_qok_eo - obs_e_qok_eo

    obs_e2_qot_sh = float(np.mean([x["qot_share_any"] for x in by_chip["[E2]"] if x["qot_share_any"] is not None]))
    obs_e_qot_sh = float(np.mean([x["qot_share_any"] for x in by_chip["e"] if x["qot_share_any"] is not None]))
    obs_diff_e2_e_qot_sh = obs_e2_qot_sh - obs_e_qot_sh

    ge_o_eo = 0
    ge_e2_e_qok_eo = 0
    ge_e2_e_qot_sh = 0
    for _ in range(N_PERM):
        o_hits = 0
        o_tot = 0
        e2_hits = 0
        e2_tot = 0
        e_hits = 0
        e_tot = 0
        e2_qot_vals: list[float] = []
        e_qot_vals: list[float] = []
        for st, lst in stratum_items.items():
            lbls = [x["true_chip"] for x in lst]
            rng.shuffle(lbls)
            for lbl, feat in zip(lbls, lst):
                if lbl == "o":
                    o_tot += 1
                    o_hits += int(feat["has_any_eo_dy"])
                elif lbl == "[E2]":
                    e2_tot += 1
                    e2_hits += int(feat["has_qok_eo_dy"])
                    if feat["qot_share_any"] is not None:
                        e2_qot_vals.append(feat["qot_share_any"])
                elif lbl == "e":
                    e_tot += 1
                    e_hits += int(feat["has_qok_eo_dy"])
                    if feat["qot_share_any"] is not None:
                        e_qot_vals.append(feat["qot_share_any"])
        r_o = o_hits / o_tot if o_tot else 0.0
        r_diff = (e2_hits / e2_tot if e2_tot else 0.0) - (e_hits / e_tot if e_tot else 0.0)
        qot_diff = (float(np.mean(e2_qot_vals)) if e2_qot_vals else 0.0) - (float(np.mean(e_qot_vals)) if e_qot_vals else 0.0)
        if r_o >= obs_o_eo - 1e-12:
            ge_o_eo += 1
        if abs(r_diff) >= abs(obs_diff_e2_e_qok_eo) - 1e-12:
            ge_e2_e_qok_eo += 1
        if abs(qot_diff) >= abs(obs_diff_e2_e_qot_sh) - 1e-12:
            ge_e2_e_qot_sh += 1

    strat_eo_breakdown = {}
    for st in sorted(stratum_items):
        lst = stratum_items[st]
        st_key = f"{st[0]}|{st[1]}"
        strat_eo_breakdown[st_key] = {
            c: {
                "n": sum(1 for x in lst if x["true_chip"] == c),
                "has_any_eo_dy": sum(1 for x in lst if x["true_chip"] == c and x["has_any_eo_dy"]),
                "has_qot_any": sum(1 for x in lst if x["true_chip"] == c and x["has_qot_any"]),
            }
            for c in PRIMARY_CHIPS
            if any(x["true_chip"] == c for x in lst)
        }

    stratified_controls = {
        "stratified_by": ["Davis_hand", "section"],
        "o_has_any_eo_dy_obs": obs_o_eo,
        "o_has_any_eo_dy_stratified_p_ge": (1 + ge_o_eo) / (N_PERM + 1),
        "e2_minus_e_has_qok_eo_dy_obs": obs_diff_e2_e_qok_eo,
        "e2_minus_e_has_qok_eo_dy_stratified_p_two_sided": (1 + ge_e2_e_qok_eo) / (N_PERM + 1),
        "e2_minus_e_qot_share_any_obs": obs_diff_e2_e_qot_sh,
        "e2_minus_e_qot_share_any_stratified_p_two_sided": (1 + ge_e2_e_qot_sh) / (N_PERM + 1),
        "stratum_breakdown": strat_eo_breakdown,
    }

    # 5. Focal Context Matrix: f26r <-> f75v L2 & f88v <-> f83v (+ f26v.P1, f43r.P3)
    focal_units = [
        ("f26r.P1", "f26r upper paragraph (.1-.6)"),
        ("f26r.P2", "f26r lower paragraph (.7-.10)"),
        ("f75v.50", "f75v L2.1 (OT-a-l; o-p-a-l)"),
        ("f75v.51", "f75v L2.2 (o-k-E2-y; l-o-l)"),
        ("f75v.52", "f75v L2.3 (o-l-o-l)"),
        ("f75v.53", "f75v L2.4 (y-t-e-d-y)"),
        ("f75v.54", "f75v L3.27 control (OT-e-d-y)"),
        ("f75v.P1", "f75v upper apparatus prose P1"),
        ("f75v.P3", "f75v middle prose P3"),
        ("f75v.P5", "f75v lower-right pool prose P5 (.60-.70)"),
        ("f88v.P2", "Store f88v.P2 (.15-.20)"),
        ("f83v.P3", "Bath f83v.P3 (.21-.32)"),
        ("f26v.P1", "Leaf-reverse control f26v.P1"),
        ("f43r.P3", "Adjacent E2->o control f43r.P3"),
    ]
    focal_matrix = []
    for uid, desc in focal_units:
        seq = units[uid]
        folio = seq[0]["folio"]
        prov = idx["hp"][folio]
        qok_targets = [
            {"id": g["id"], "interior": g["ops"][2:-2], "uncertain": g["uncertain"]}
            for g in seq
            if is_qok_dy(g["ops"])
        ]
        focal_matrix.append({
            "unit": uid,
            "description": desc,
            "folio": folio,
            "Davis_hand": prov["Davis_hand_H"],
            "Currier_hand": prov["Currier_hand_C"],
            "Currier_language": prov["Currier_language_L"],
            "section": idx["pages_by_folio"][folio]["section"],
            "qok_dy_targets": qok_targets,
            "profile": unit_profiles[uid],
        })

    return {
        "eight_o_cases": eight_o_cases,
        "five_ch_e2_to_qok_exact": ch_e2_exact,
        "one_ch_e2_to_qok_expanded_multi": ch_e2_expanded,
        "fifteen_clean_ch_eo_source_targets": fifteen_eo_source,
        "corpus_eo_census": {
            "qok_eo_dy_count": len(qok_eo_hosts),
            "qok_eo_dy_distinct_units": len(qok_eo_units),
            "qok_eo_dy_ids": [g["id"] for g in qok_eo_hosts],
            "cooccur_targets_in_qok_eo_units": dict(cooccur_in_qok_eo_units),
            "ch_eo_dy_count": len(ch_eo_hosts),
            "ch_eo_dy_distinct_units": len(ch_eo_units),
            "cooccur_targets_in_ch_eo_units": dict(cooccur_in_ch_eo_units),
            "cooccur_targets_in_any_eo_units": dict(cooccur_in_any_eo_units),
        },
        "e_E2_o_paragraph_profiles": group_summaries,
        "statistical_tests": tests,
        "stratified_controls": stratified_controls,
        "focal_context_matrix": focal_matrix,
    }


def predecessor_qualifications() -> dict[str, Any]:
    return {
        "hand_and_language_provenance": {
            "f26r": {"Davis_hand": "2", "Currier_hand": "2", "Currier_language": "B", "section": "herbal"},
            "f75v": {"Davis_hand": "2", "Currier_hand": "2", "Currier_language": "B", "section": "balne"},
            "f88v": {"Davis_hand": "1", "Currier_hand": "4", "Currier_language": "A", "section": "pharma"},
            "f83v": {"Davis_hand": "2", "Currier_hand": "2", "Currier_language": "B", "section": "balne"},
            "f43r": {"Davis_hand": "2", "Currier_hand": "2", "Currier_language": "B", "section": "herbal"},
            "note": "Davis hand labels and Currier hand/language labels are distinct systems and are both retained without silent substitution.",
        },
        "older_reading_variants": {
            "f26r": [
                "f26r.7:G1: Current/C reads p-E2-o; older H and F read p-CH-o.",
                "f26r.8:G6-7: Current and H/C/F retain o-k and o-l as separate groups across a plant stalk interruption (not one joined okol host).",
                "f26r.8:G8-10: Current/C reads ytedy / QOk-E2-dy / QOk-e-dy; H reads otedy / QOk-CH-dy / QOk-e-dy; F reads otedy / QOk-o-e-dy / QOk-e-dy.",
                "f26r.10:G4: Current and H/C/F all retain CH-e-o-d-y and final OT-a-l.",
                "f26v.3:G10-11 (leaf-reverse control): H/C/F/U all retain y-t-e-d-y followed by o-k-CH-d-y.",
            ],
            "f75v": [
                "f75v.51 (L2.2): H/C/F read okeey.lol (matching E2 in vessel frame), whereas U/V read okchg.lol or okchy.lol (retaining vessel onset o-k and lol companion, without E2).",
                "f75v.51 spatial pairing: Old editor notes o-k-E2-y and l-o-l may be two separate labels sharing a row rather than one compound record.",
                "f75v.53 (L2.4): H/C/F/U/V all preserve standalone y-t-e-d-y.",
                "f75v.54 (L3.27): Separate below-channel label OT-e-d-y matches the older H/F lower f26r otedy reading, not L2 ytedy.",
                "f75v.61 (P5, old P3.25): Editorial comment notes a possible alignment with ytedy across the pool; current .61 begins fused o-k-SH-e-y-QO-l-k-E2-y.",
            ],
            "flagged_targets_excluded_from_primary": [
                "f41r.3:G3 ([q:y][o:e]kedy -> e)",
                "f51v.10:G3 (qok[o:a]dy -> o/a reading alternative)",
                "f82r.15:G4 (qok[ee:ch]dy -> [E2]/ch reading alternative)",
            ],
        },
        "non_literal_gloss_scopes": [
            "MS 408 is not a cipher; results do not search for or assume an individual Voynich key.",
            "E2 is a compound lattice chip retaining double-state naming in some records; it does not establish a numerical doubling, dose, or two units of time.",
            "Medial e inside compound frames is a structural component/ligature, not standalone conjunction 'et' and not simply 'unfinished' relative to E2.",
            "Medial o retains -ro/-to/-tio component scope; medicinal 'oleum' belongs to head/label scope and is not licensed on every medial o.",
            "qok and qot retain distinct heads (May row 44 notes pairing in recipe blocks without equating heads).",
            "y-t-e-d-y retains y-tau-completed proposal with unresolved tau operation; initial y does not inherit terminal -tur/-atur.",
            "CH-e-o-s terminal s (tentative semis) vs standalone s on f26r.8 does not establish an instruction selecting between e and E2.",
        ],
    }


def write_receipt() -> None:
    files_info = {}
    for p in sorted(JOIN_DIR.rglob("*")):
        if p.is_file() and p != RECEIPT_PATH:
            rel = str(p.relative_to(JOIN_DIR))
            files_info[rel] = {
                "path": str(p),
                "bytes": p.stat().st_size,
                "sha256": sha256_file(p),
            }
    receipt = {
        "generated_utc": datetime.now(timezone.utc).isoformat(),
        "join_dir": str(JOIN_DIR),
        "seed": SEED,
        "permutations": N_PERM,
        "read_only_inputs": {
            str(p): {"bytes": p.stat().st_size, "sha256": sha256_file(p)}
            for p in [
                SRC_SNAPSHOT,
                SRC_TARGETS,
                SRC_SOURCE_REL,
                SRC_HANDS,
                SRC_EXPANDED,
                SRC_CONDITIONAL,
                SRC_CATALOG,
            ]
        },
        "outputs": files_info,
    }
    RECEIPT_PATH.write_text(json.dumps(receipt, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def main() -> None:
    rng = random.Random(SEED)
    idx = build_corpus_index()
    task1 = run_task1(idx, rng)
    task2 = run_task2(idx)
    task3 = run_task3(idx, rng)
    task4 = predecessor_qualifications()

    analysis = {
        "meta": {
            "join": "Join 2: e vs E2 vs o Caller/State Selector",
            "generated_utc": datetime.now(timezone.utc).isoformat(),
            "seed": SEED,
            "permutations": N_PERM,
            "corpus_panels": 227,
            "expanded_qok_A_dy_hosts": 805,
            "single_chip_targets": 655,
            "unflagged_single_chip_targets": 652,
            "qot_A_dy_hosts": len(idx["qot_all_dy"]),
            "scipy_used": False,
        },
        "task1_state_carry_vs_external_fetch": task1,
        "task2_consecutive_qok_transition_census": task2,
        "task3_eo_qot_ch_context_matrix": task3,
        "task4_predecessor_qualifications": task4,
    }
    ANALYSIS_PATH.write_text(json.dumps(analysis, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    write_receipt()
    print(json.dumps({
        "status": "ok",
        "analysis_bytes": ANALYSIS_PATH.stat().st_size,
        "receipt_bytes": RECEIPT_PATH.stat().st_size,
    }))


if __name__ == "__main__":
    main()
