File size: 29,630 Bytes
2e511b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
"""Render the IAA / Alternative Annotator Test / evaluation CSVs into a minimal ANALYSIS.md.

This is a convenience script, it reads the artifacts produced by
``legex-iaa`` (``pairwise_agreement.csv``), by the Alternative Annotator Test
reference adapter ``scripts/alt_test_reference.py``
(``alt_test_reference_*.csv``, see the README section "Alternative Annotator
Test (AAT)"), by ``scripts/alt_test_decomposition.py``
(``alt_test_decomposition.csv``), and by ``legex-analysis`` (``per_column.csv``), and emits
headers, always-true methodology notes, and live tables. Regenerate the whole
chain with ``scripts/reproduce_paper.sh``.

Usage
-----
    uv run legex-analysis-report
    uv run python -m legex.analysis.report --iaa-dir data/analysis/iaa
"""

import argparse
import csv
import math
import statistics
from pathlib import Path

from legex.analysis.countries import COUNTRY_NAMES

_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")


# IO helpers
def _read_csv(path: Path) -> list[dict[str, str]]:
    if not path.exists():
        return []
    with path.open(encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


def _short_model(model: str) -> str:
    """Display label for a litellm id (drop the provider prefix)."""
    return model.split("/")[-1]


def _country_name(cc: str) -> str:
    return COUNTRY_NAMES.get(cc, cc.upper())


def _md_table(headers: list[str], rows: list[list[str]]) -> str:
    head = "| " + " | ".join(headers) + " |"
    sep = "| " + " | ".join("---" for _ in headers) + " |"
    body = "\n".join("| " + " | ".join(r) + " |" for r in rows)
    return "\n".join([head, sep, body]) if rows else head + "\n" + sep + "\n| _(no data)_ |"


def _se(p: float, n: int) -> float:
    """Binomial standard error of a proportion (1σ of the estimate)."""
    return math.sqrt(p * (1 - p) / n) if n > 0 else 0.0


def _pct_se(p: float, n: int) -> str:
    """Percent with ±1 SE in percentage points, e.g. '49.2% ±3.3'."""
    return f"{p:.1%} ±{_se(p, n) * 100:.1f}"


def _by_field_grid(
    per_column: list[dict[str, str]],
    models: list[str],
    metric_key: str,
    *,
    n_buckets: tuple[str, ...] | None,
    pct: bool = True,
) -> str:
    """Field × model grid for one derived metric.

    ``n_buckets`` sums the bucket columns giving the metric's model-independent
    denominator (shown as ``n``); pass ``None`` when the denominator is
    model-dependent (precision) or composite (F1) so ``n`` is omitted.
    """
    fields = sorted({r["column"] for r in per_column})
    val = {(r["model"], r["column"]): r.get(metric_key, "") for r in per_column}
    n_by_field: dict[str, int] = {}
    if n_buckets:
        for r in per_column:
            tot = sum(int(r[b]) for b in n_buckets)
            n_by_field[r["column"]] = max(n_by_field.get(r["column"], 0), tot)
    rows = []
    for field in fields:
        row = [f"`{field}`"]
        if n_buckets:
            row.append(str(n_by_field.get(field, 0)))
        for m in models:
            v = val.get((m, field), "")
            if v in (None, ""):
                row.append("–")
            else:
                row.append(f"{float(v):.1%}" if pct else f"{float(v):.3f}")
        rows.append(row)
    headers = ["Field"] + (["n"] if n_buckets else []) + [_short_model(m) for m in models]
    return _md_table(headers, rows)


# Variables with a fixed controlled vocabulary -> Cohen's kappa is valid.
_CATEGORICAL_FIELDS = {
    "plaintiff_no1_ISIC1_industry_category",
    "defendant_no1_ISIC1_industry_category",
}

# Measurement level per variable, shown in the by-variable table.
_FIELD_TYPE = {
    "plaintiff_no1_ISIC1_industry_category": "nominal",
    "defendant_no1_ISIC1_industry_category": "nominal",
    "legal_subject_judgement": "free text",
    "trial_start_date": "date",
    "trial_end_date": "date",
    "plaintiffs_all_count": "count",
    "defendants_all_count": "count",
    "dispute_value_nominal": "monetary",
    "court_cost_awarded_nominal": "monetary",
    "party_compensation_awarded_nominal": "monetary",
    "plaintiff_loosing_share": "ratio",
}
_TYPE_ORDER = {
    t: i for i, t in enumerate(
        ["nominal", "free text", "date", "count", "monetary", "ratio", "other"]
    )
}


# Section builders
def _scope(pairwise: list[dict[str, str]]) -> str:
    annotators = {r["annotator_a"] for r in pairwise} | {r["annotator_b"] for r in pairwise}
    pairs = {(r["country"], r["annotator_a"], r["annotator_b"]) for r in pairwise}
    countries = sorted({r["country"] for r in pairwise})
    legend = ", ".join(f"**{cc}** {_country_name(cc)}" for cc in countries)
    secondary = sorted(a for a in annotators if a != "primary")
    lines = [
        "## 1. Scope",
        "",
        f"- Countries with ≥2 annotators: **{len(countries)}** — {', '.join(countries) or '(none)'}",
        f"- Annotators: **{len(annotators)}** (primary + {len(secondary)} secondary: "
        f"{', '.join(secondary) or '(none)'})",
        f"- Annotator pairs (country × pair): **{len(pairs)}**",
        "",
        f"Countries: {legend}." if legend else "",
    ]
    return "\n".join(lines)


def _agreement_sections(pairwise: list[dict[str, str]]) -> str:
    note = (
        "> **Per-variable agreement.** Percent agreement is reported for every variable, using the "
        "same value-matching as the evaluation (ISO-date / number-format aware; `0` and empty treated "
        "alike). For the two **nominal ISIC** fields — the only variables with a fixed controlled "
        "vocabulary — we additionally report **Cohen's κ**. For the other variables the category space "
        "is unbounded (free text) or continuous (dates, counts, money, ratios): there κ's chance "
        "correction collapses toward percent agreement (as the number of categories → ∞, expected "
        "agreement pₑ → 0 and κ → observed agreement) and awards no partial credit for near-misses, so "
        "percent agreement is the appropriate summary. Correlation coefficients are deliberately not "
        "used — for these labels a wrong value is wrong, not partially correct. Cell detail: "
        "`kappa_audit.csv`."
    )
    out = [
        "## 2. Human–human agreement", "", note, "",
        "_n = paired case comparisons (shared cases × annotator pairs). We report ±1 SE = √(p(1-p)/n) in "
        "percentage points, a descriptive precision marker. This is not a significance test._", "",
    ]

    by_pair: dict[tuple[str, str, str], list[dict[str, str]]] = {}
    for r in pairwise:
        by_pair.setdefault((r["country"], r["annotator_a"], r["annotator_b"]), []).append(r)
    # Shared cases per pair (constant across that pair's fields)
    pair_cases = {k: int(v[0]["n"]) for k, v in by_pair.items()}

    def _agg(rows: list[dict[str, str]]) -> tuple[int, float, float]:
        """(total paired observations, n-weighted tolerant %, mean defined κ)."""
        n = sum(int(r["n"]) for r in rows)
        tol = sum(float(r["pct_tolerant"]) * int(r["n"]) for r in rows) / n if n else 0.0
        kv = [float(r["cohen_kappa"]) for r in rows if r.get("cohen_kappa") not in (None, "")]
        mk = statistics.mean(kv) if kv else float("nan")
        return n, tol, mk

    # 2.1 by variable — % for all, κ only for the categorical (fixed-vocab) fields
    out += ["### 2.1 By variable", ""]
    by_field: dict[str, list[dict[str, str]]] = {}
    for r in pairwise:
        by_field.setdefault(r["field"], []).append(r)
    order = sorted(
        by_field,
        key=lambda f: (_TYPE_ORDER.get(_FIELD_TYPE.get(f, "other"), 99), -_agg(by_field[f])[1]),
    )
    var_rows = []
    for field in order:
        n, tol, mk = _agg(by_field[field])
        kappa = f"{mk:.3f}" if (field in _CATEGORICAL_FIELDS and mk == mk) else "—"
        var_rows.append([f"`{field}`", _FIELD_TYPE.get(field, "other"), str(n), _pct_se(tol, n), kappa])
    out.append(_md_table(["Variable", "Type", "n", "% agreement", "Cohen's κ"], var_rows))

    # 2.2 by country
    out += ["", "### 2.2 By country", ""]
    by_cc: dict[str, list[dict[str, str]]] = {}
    for r in pairwise:
        by_cc.setdefault(r["country"], []).append(r)
    cc_rows = []
    for cc in sorted(by_cc):
        pairs = {(r["annotator_a"], r["annotator_b"]) for r in by_cc[cc]}
        n_cases = sum(pair_cases[(cc, a, b)] for (a, b) in pairs)
        _n, tol, _mk = _agg(by_cc[cc])
        cc_rows.append([cc, str(len(pairs)), str(n_cases), f"{tol:.1%}"])
    out.append(_md_table(["Country", "Pairs", "n", "% agreement"], cc_rows))

    # 2.3 by pair
    out += ["", "### 2.3 By pair", ""]
    pair_rows = []
    for (cc, a, b) in sorted(by_pair):
        _n, tol, _mk = _agg(by_pair[(cc, a, b)])
        pair_rows.append([cc, f"{a}{b}", str(pair_cases[(cc, a, b)]), f"{tol:.1%}"])
    out.append(_md_table(["Country", "Pair", "n", "% agreement"], pair_rows))
    return "\n".join(out)


_ALT_TEST_FORMULA = """### 3.1 How ω and ρ are computed

_Definitions from Calderon et al. (2025), as implemented in the authors' `alt_test`.
`values_agree` is the tolerant comparator LEGEX passes in as the scoring function._

```text
One jurisdiction, one candidate f, human annotators H = {1..M}, and instances i
(here: one (judgment, variable) cell over the 10 structured fields).

LEAVE-ONE-OUT. For human j and every instance i the other humans also labelled,
let A(i,-j) be the remaining humans' labels and

    s_f(i,j) = score( f(i),    A(i,-j) )      candidate vs. the other humans
    s_h(i,j) = score( h_j(i),  A(i,-j) )      held-out human vs. the same humans

    score(p, A) = (1/|A|) * SUM_{a in A} values_agree(p, a)     in {0, 1/2, 1}

ADVANTAGE PROBABILITY of the candidate against human j. Note the ">=", which
credits every tie to the candidate:

    rho_j = (1/n_j) * SUM_i  1[ s_f(i,j) >= s_h(i,j) ]

PER-ANNOTATOR TEST. With d_i = 1[s_f < s_h] - 1[s_f >= s_h], so E[d] = 1 - 2*rho_j:

    H0: E[d] >= epsilon        vs.        H1: E[d] < epsilon

one-sided paired t-test (Wilcoxon signed-rank when n_j < 30), the M p-values
corrected by Benjamini-Yekutieli at q = 0.05. Rejecting H0 is therefore
equivalent to rho_j being significantly greater than

    (1 - epsilon) / 2  =  0.4        for the expert tolerance epsilon = 0.2

VERDICT.

    omega = |{ j : H0_j rejected }| / M          winning rate
    rho   = (1/M) * SUM_j rho_j                  advantage probability
    "f may substitute a human annotator"  <=>  omega >= 0.5
```

Two consequences worth keeping in view when reading §3.2. First, ρ is a
**≥**-comparison, so a candidate that merely matches the held-out human on an
instance is scored as winning it. Second, with ε = 0.2 the hypothesis test
clears at ρ_j > 0.4, not at 0.5. Both are deliberate: the alt-test asks whether
a candidate can *substitute* a human annotator, not whether it is *better* than
one. §3.4 separates the two.
"""


def _alt_test_section(iaa_dir: Path) -> str:
    # Only the reference-implementation outputs are rendered
    files = sorted(p for p in iaa_dir.glob("alt_test_reference_*.csv"))
    rows_by_cand: dict[str, list[dict[str, str]]] = {}
    for p in files:
        for r in _read_csv(p):
            rows_by_cand.setdefault(r["candidate"], []).append(r)
    all_rows = [r for rs in rows_by_cand.values() for r in rs]
    note = (
        "> **Alternative Annotator Test** (Calderon et al. 2025, "
        "[arXiv:2501.10970](https://arxiv.org/abs/2501.10970)): leave each human annotator out in "
        "turn and score, per instance, both the candidate and the excluded annotator against the "
        "remaining annotators; a one-sided test per annotator asks whether the candidate's "
        "advantage probability trails the human's by less than ε = 0.2 (the expert-annotator "
        "tolerance), under Benjamini–Yekutieli FDR control at q = 0.05. `passes` = winning rate "
        "≥ 0.5. Requires ≥ 3 independent annotators per country; free-text fields are excluded. "
        "ρ is the advantage probability — how likely the candidate annotates as well as or better "
        "than a randomly chosen human. The *non-trivial* variant drops instances every expert left "
        "empty: an empty prediction ties those for free, so the gap between the two columns shows "
        "how much of a pass rests on empty cells. Untestable cells (too few non-empty judgements) "
        "are excluded from the denominators.\n>\n"
        "> These numbers come from the **authors' reference implementation** "
        "([github.com/nitaytech/AltTest](https://github.com/nitaytech/AltTest)) executed on the "
        "LEGEX data via `scripts/alt_test_reference.py`. See the README section \"Alternative "
        "Annotator Test (AAT)\" for how to run it. `legex-iaa` does not produce these CSVs."
    )
    out = ["## 3. Alternative-annotator test", "", note, "", _ALT_TEST_FORMULA, ""]

    # 3.2 Headline: pooled per jurisdiction (instance = judgment x variable cell,
    # the SummEval convention of the paper) — this is what the manuscript reports.
    pooled_csv = iaa_dir / "alt_test_pooled.csv"
    if pooled_csv.exists():
        pooled = _read_csv(pooled_csv)
        out += [
            "### 3.2 Headline: pooled per jurisdiction (paper numbers)",
            "",
            "_One alt-test per jurisdiction; instance = (judgment, variable) cell over the"
            " 10 structured fields, so each annotator contributes ~190+ effective instances"
            " and the paired t-test applies without the paper's n<30 caveat._",
            "",
            "| Candidate | Country | ω | ρ | ω (non-triv) | ρ (non-triv) |",
            "| --- | --- | --- | --- | --- | --- |",
        ]
        for r in pooled:
            out.append(
                f"| {r['candidate']} | {r['country']} | {float(r['omega']):.2f}"
                f" | {float(r['rho']):.2f} | {float(r['omega_nontrivial']):.2f}"
                f" | {float(r['rho_nontrivial']):.2f} |"
            )
        out.append("")

    out += ["### 3.3 Per-field diagnostic (cells passed / testable)", ""]
    if not rows_by_cand:
        out.append("_No `alt_test_reference_*.csv` found — run `scripts/alt_test_reference.py` (see README)._")
        return "\n".join(out + ["", _decomposition_section(iaa_dir)])
    countries = sorted({r["country"] for r in all_rows})

    def _rate(rows: list[dict[str, str]], key: str) -> str:
        rows = [r for r in rows if r[key] != ""]
        if not rows:
            return "–"
        p = sum(int(r[key]) for r in rows)
        return f"{p}/{len(rows)}"

    def _mean_rho(rows: list[dict[str, str]], key: str) -> str:
        vals = [float(r[key]) for r in rows if r[key] != ""]
        return f"{statistics.mean(vals):.2f}" if vals else "–"

    headers = [
        "Candidate", "ρ̄ (all)", "Pass (all)", "ρ̄ (non-triv)", "Pass (non-triv)",
        *(f"{cc} (all · non-triv)" for cc in countries),
    ]
    table_rows = []
    for cand in sorted(rows_by_cand):
        rs = rows_by_cand[cand]
        row = [
            _short_model(cand),
            _mean_rho(rs, "advantage_probability"),
            _rate(rs, "passes"),
            _mean_rho(rs, "advantage_probability_nontrivial"),
            _rate(rs, "passes_nontrivial"),
        ]
        for cc in countries:
            sub = [r for r in rs if r["country"] == cc]
            row.append(f"{_rate(sub, 'passes')} · {_rate(sub, 'passes_nontrivial')}")
        table_rows.append(row)
    out.append(_md_table(headers, table_rows))

    out += [
        "",
        "> Per-cell winning rates and advantage probabilities are in "
        "`alt_test_reference_<model>.csv`; an empty cell there means the "
        "(country, field, variant) combination was untestable.",
        "",
        _decomposition_section(iaa_dir),
    ]
    return "\n".join(out)


def _decomposition_section(iaa_dir: Path) -> str:
    """§3.4 — the win/tie/loss counts ρ is built from (substitutable vs. better)."""
    rows = _read_csv(iaa_dir / "alt_test_decomposition.csv")
    out = ["### 3.4 Substitutable vs. better: win / tie / loss decomposition", ""]
    if not rows:
        out.append(
            "_No `alt_test_decomposition.csv` found — run "
            "`uv run python scripts/alt_test_decomposition.py`._"
        )
        return "\n".join(out)

    note = (
        "> ρ collapses the leave-one-out comparison of §3.1 into one number, and its `≥` "
        "hands every tie to the candidate. This section keeps the same comparisons and "
        "reports the counts instead: per held-out human and instance, whether the candidate "
        "scored **better than**, **the same as**, or **worse than** that human against the two "
        "remaining humans. Restricted to judgments all three experts labelled, so every "
        "comparison has exactly two references and a score is 0, ½ or 1. `ρ (alt-test)` is the "
        "reproduced advantage probability (ties → candidate); `ρ (ties split)` counts a tie as "
        "half a win for each side. Source: `alt_test_decomposition.csv` from "
        "`scripts/alt_test_decomposition.py`, which reproduces the reference ρ of §3.2 to "
        "within 0.02."
    )
    out += [note, ""]

    def _pool(candidate: str, variant: str) -> dict[str, int]:
        keys = (
            "n_comparisons", "refs_disagree", "llm_better", "human_better",
            "tie", "tie_same", "tie_diff", "tie_at_1", "tie_at_half", "tie_at_0",
        )
        totals = dict.fromkeys(keys, 0)
        for r in rows:
            if r["candidate"] == candidate and r["variant"] == variant:
                for k in keys:
                    totals[k] += int(r[k])
        return totals

    candidates = sorted({r["candidate"] for r in rows})
    countries = sorted({r["country"] for r in rows})
    headers = [
        "Candidate", "Country", "n", "Candidate better", "Tie", "Human better",
        "ρ (alt-test)", "ρ (ties split)",
    ]
    table: list[list[str]] = []
    for cand in candidates:
        for cc in [*countries, "pooled"]:
            if cc == "pooled":
                t = _pool(cand, "all")
                n = t["n_comparisons"]
                if not n:
                    continue
                cells = [t["llm_better"], t["tie"], t["human_better"]]
                rho_alt = (t["llm_better"] + t["tie"]) / n
                rho_split = (t["llm_better"] + t["tie"] / 2) / n
                label = "**all three**"
            else:
                r = next(
                    (r for r in rows if r["candidate"] == cand
                     and r["country"] == cc and r["variant"] == "all"),
                    None,
                )
                if r is None:
                    continue
                n = int(r["n_comparisons"])
                cells = [int(r["llm_better"]), int(r["tie"]), int(r["human_better"])]
                rho_alt = float(r["rho_alttest"])
                rho_split = float(r["rho_tiebroken"])
                label = cc
            table.append([
                _short_model(cand), label, str(n),
                *(f"{c} ({c / n:.0%})" for c in cells),
                f"{rho_alt:.2f}", f"{rho_split:.2f}",
            ])
    out.append(_md_table(headers, table))

    # What a "tie" actually contains — the bucket ρ is most sensitive to.
    pooled_all = {c: _pool(c, "all") for c in candidates}
    refs_disagree = next(
        (t["refs_disagree"], t["n_comparisons"]) for t in pooled_all.values()
    )
    out += [
        "",
        "**What is in the “Tie” bucket.** A tie only means *same score against the same two "
        "references*, so it merges several different situations. Split by score level, and "
        "independently by whether the candidate actually produced the held-out expert's answer:",
        "",
    ]
    tie_headers = [
        "Candidate", "Ties", "Same answer as expert", "Different answer, equal score",
        "at 1 (all agree)", "at ½ (experts conflict)", "at 0 (both differ)",
    ]
    tie_rows = []
    for cand in candidates:
        t = pooled_all[cand]
        ties = t["tie"]
        if not ties:
            continue
        tie_rows.append([
            _short_model(cand), str(ties),
            *(f"{t[k]} ({t[k] / ties:.0%})" for k in
              ("tie_same", "tie_diff", "tie_at_1", "tie_at_half", "tie_at_0")),
        ])
    out.append(_md_table(tie_headers, tie_rows))
    out += [
        "",
        f"A tie at ½ is only possible when the two reference experts contradict each other — "
        f"that caps every achievable score at ½, for the candidate and the held-out expert "
        f"alike. The two references disagree in {refs_disagree[0]} of {refs_disagree[1]} "
        f"comparisons ({refs_disagree[0] / refs_disagree[1]:.0%}; a property of the human "
        f"labels, identical for every candidate). Note that reference disagreement is *not* "
        f"the same thing as a tie: ties also arise, and in fact more often, where the two "
        f"references agree and the candidate simply matches them.",
    ]

    # Reading: who wins the decisive comparisons.
    lines = []
    for cand in candidates:
        t = pooled_all[cand]
        nt = _pool(cand, "nontrivial")
        n, ties = t["n_comparisons"], t["tie"]
        decisive = t["llm_better"] + t["human_better"]
        if not (n and ties and decisive):
            continue
        nontrivial = (
            f" Dropping instances whose reference is empty throughout leaves ρ (ties split) at "
            f"{(nt['llm_better'] + nt['tie'] / 2) / nt['n_comparisons']:.2f}."
            if nt["n_comparisons"] else ""
        )
        lines.append(
            f"- **{_short_model(cand)}** — {ties / n:.0%} of the {n} comparisons are ties. "
            f"{t['tie_same'] / ties:.0%} of those ties are real agreement (candidate gave the "
            f"held-out expert's answer); the other {t['tie_diff'] / ties:.0%} are comparisons "
            f"where candidate and expert gave *different* answers that happened to score the "
            f"same, and ρ credits every one of them to the candidate. On the {decisive} "
            f"comparisons that actually discriminate, the human wins "
            f"{t['human_better'] / decisive:.0%} ({t['human_better']} vs "
            f"{t['llm_better']}).{nontrivial}"
        )
    if lines:
        out += ["", "**Reading.**", "", *lines]

    out += [
        "",
        "This is what the alt-test is and is not evidence for. The tie rate is high and mostly "
        "genuine, so on this data the models are largely *indistinguishable* from an additional "
        "expert — which is exactly the substitutability claim ω and ρ are designed to support, "
        "and §3.2 supports it. It is not evidence of superiority: once ties stop counting as "
        "wins, ρ sits at chance, and on the comparisons that separate the two the human expert "
        "is still ahead. \"Can this model replace a human annotator?\" and \"is this model better "
        "than a human annotator?\" are different questions, and only the first one is being "
        "tested.",
    ]
    return "\n".join(out)


def _headline_section(per_column: list[dict[str, str]]) -> str:
    note = (
        "> Recall = TP / (TP + Mismatch + Missed) over cells the expert filled; precision = "
        "TP / (TP + Mismatch + Hallucinated); hallucination = invented values on empty-gold cells. "
        "Buckets from `legex/evaluation.py`; per-cell source `../per_column.csv`. n = evaluated "
        "label cells; recall and precision carry ±1 SE over their gold-filled / emitted denominators. "
        "The per-field grids (§4.2–4.5) break each metric out by variable across models; their `n` is "
        "the metric's model-independent denominator (gold-filled for recall, gold-empty for "
        "hallucination) and is omitted for precision (emitted; model-dependent) and F1 (composite)."
    )
    out = ["## 4. Headline extraction metrics", "", note, ""]
    if not per_column:
        out.append("_`../per_column.csv` not found — run `legex-analysis`._")
        return "\n".join(out)

    by_model: dict[str, list[dict[str, str]]] = {}
    for r in per_column:
        by_model.setdefault(r["model"], []).append(r)

    # 4.1 overall, summed across fields & countries
    out += ["### 4.1 Overall (all countries, summed across fields)", ""]
    rows = []
    for model in sorted(by_model):
        b = {k: sum(int(r[k]) for r in by_model[model]) for k in _BUCKETS}
        tp, mism, miss, hallu, tn = (b[k] for k in _BUCKETS)
        total = tp + mism + miss + hallu + tn
        recall = tp / (tp + mism + miss) if (tp + mism + miss) else 0.0
        prec = tp / (tp + mism + hallu) if (tp + mism + hallu) else 0.0
        acc = (tp + tn) / total if total else 0.0
        hallu_rate = hallu / (hallu + tn) if (hallu + tn) else 0.0
        f1 = 2 * prec * recall / (prec + recall) if (prec + recall) else 0.0
        filled = tp + mism + miss
        emitted = tp + mism + hallu
        rows.append([
            _short_model(model), str(total), f"{acc:.1%}",
            _pct_se(recall, filled), _pct_se(prec, emitted),
            f"{hallu_rate:.1%}", f"{f1:.3f}",
        ])
    out.append(_md_table(
        ["Model", "n", "Accuracy", "Recall (filled)", "Precision", "Hallu. rate", "F1"], rows
    ))

    # 4.2–4.5 per-field grids (Field × model) for each metric
    models = sorted(by_model)
    out += ["", "### 4.2 Recall (filled) by field (all countries)", ""]
    out.append(_by_field_grid(per_column, models, "recall_when_filled",
                              n_buckets=("tp", "mismatch", "missed")))
    out += ["", "### 4.3 Precision by field (all countries)", ""]
    out.append(_by_field_grid(per_column, models, "precision_when_emitted", n_buckets=None))
    out += ["", "### 4.4 Hallucination rate by field (all countries)", ""]
    out.append(_by_field_grid(per_column, models, "hallucination_rate",
                              n_buckets=("hallucinated", "tn")))
    out += ["", "### 4.5 F1 by field (all countries)", ""]
    out.append(_by_field_grid(per_column, models, "f1", n_buckets=None, pct=False))
    return "\n".join(out)


def _appendix() -> str:
    return "\n".join([
        "## Appendix",
        "",
        "### Landis–Koch (1977) κ scale (for interpreting the ISIC κ)",
        "",
        _md_table(
            ["κ", "Strength"],
            [
                ["< 0.00", "Poor (worse than chance)"],
                ["0.00 – 0.20", "Slight"],
                ["0.21 – 0.40", "Fair"],
                ["0.41 – 0.60", "Moderate"],
                ["0.61 – 0.80", "Substantial"],
                ["0.81 – 1.00", "Almost perfect"],
            ],
        ),
        "",
        "### Provenance",
        "",
        "- Pairwise agreement & kappa: `legex/analysis/iaa.py` (`pairwise_agreement`, "
        "`write_kappa_audit_csv`).",
        "- Alt-test: authors' reference implementation "
        "([github.com/nitaytech/AltTest](https://github.com/nitaytech/AltTest)) run via "
        "`scripts/alt_test_reference.py` → `alt_test_reference_*.csv` (see README).",
        "- Alt-test win/tie/loss decomposition: `scripts/alt_test_decomposition.py` → "
        "`alt_test_decomposition.csv`.",
        "- Tolerant comparator: `legex/evaluation/comparison.py` (`values_agree`, `normalise`).",
        "- Headline buckets: `legex/analysis/aggregate.py` over `legex/evaluation.score_country`.",
        "- This report: `legex/analysis/report.py`.",
    ])


def build_report(iaa_dir: Path, analysis_dir: Path) -> str:
    pairwise = _read_csv(iaa_dir / "pairwise_agreement.csv")
    per_column = _read_csv(analysis_dir / "per_column.csv")
    header = [
        "# Inter-Annotator Agreement & Alternative-Annotator Test",
        "",
        "_Generated by `legex-analysis-report` from the CSVs in this directory — do not edit by "
        "hand; numbers always reflect the current CSVs._",
        "",
        "Regenerate the whole chain with `scripts/reproduce_paper.sh`.",
        "",
        "---",
        "",
    ]
    parts = [
        "\n".join(header),
        _scope(pairwise),
        _agreement_sections(pairwise),
        _alt_test_section(iaa_dir),
        _headline_section(per_column),
        _appendix(),
    ]
    return "\n\n".join(p.strip() for p in parts) + "\n"


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="legex-analysis-report",
        description="Render the IAA / alt-test / evaluation CSVs into a minimal ANALYSIS.md.",
    )
    parser.add_argument(
        "--iaa-dir", type=Path, default=Path("data/analysis/iaa"),
        help="Directory with pairwise_agreement.csv (from legex-iaa) and "
             "alt_test_reference_*.csv (from scripts/alt_test_reference.py), "
             "and the output ANALYSIS.md.",
    )
    parser.add_argument(
        "--analysis-dir", type=Path, default=Path("data/analysis"),
        help="Directory with per_column.csv (from legex-analysis).",
    )
    parser.add_argument(
        "--out", type=Path, default=None,
        help="Output path (default: <iaa-dir>/ANALYSIS.md).",
    )
    args = parser.parse_args(argv)
    out = args.out or (args.iaa_dir / "ANALYSIS.md")
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(build_report(args.iaa_dir, args.analysis_dir), encoding="utf-8")
    print(f"wrote {out}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())