File size: 28,658 Bytes
43d29b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c42697
43d29b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c42697
 
 
43d29b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d51cb
43d29b8
 
 
f7d51cb
 
 
 
 
 
 
 
 
 
43d29b8
 
 
 
f7d51cb
43d29b8
 
 
 
 
 
 
 
 
 
 
 
 
f7d51cb
43d29b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d51cb
 
 
43d29b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df3df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a58472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df3df7
 
 
8c42697
 
2df3df7
 
 
 
8c42697
 
2df3df7
 
8c42697
 
2df3df7
8c42697
 
 
 
 
 
 
 
 
 
 
 
 
 
2df3df7
 
 
43d29b8
 
2df3df7
43d29b8
 
 
 
 
 
 
 
 
 
 
 
2df3df7
 
2a58472
 
 
 
 
 
43d29b8
 
 
 
 
 
 
 
 
f7d51cb
 
 
 
43d29b8
 
 
 
 
 
 
 
 
2df3df7
43d29b8
 
 
 
 
 
 
 
 
 
 
 
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
666
667
668
669
670
671
#!/usr/bin/env python3
# =============================================================================
# run_experiments.py
# -----------------------------------------------------------------------------
# Responsible for: The single entrypoint that runs every claim's experiment and
#                  writes results to an output directory as JSON + CSV.
# Role in project: Runs identically on a laptop (--stage smoke, mock backend)
#                  and on an HF GPU Job (real vLLM backend). One script, one
#                  code path, so the smoke test actually exercises the real thing.
# Assumptions: Reads backend config from EDUMIRROR_* env vars (see llm.py).
#              Writes to --out. Never reads the network except via the LLM.
# =============================================================================
"""Experiment driver for the EduMirror reproduction.

Stages:
  smoke       -- tiny mock-backed run proving the pipeline end to end
  claim2      -- kindergarten scalability at 5/15/30 agents (Table 1)
  claim3      -- dual measurement: bullying dynamics + RSES construct validity
  claim4      -- pairwise win-rate heatmap across scenarios (Figure 4)
  claim5      -- election intervention strategies (Figure 7)
  all         -- claim2 + claim3 + claim4 + claim5

Every stage writes <out>/<stage>.json and appends a row-per-record CSV so the
logbook can attach both the raw traces and the tables.
"""

from __future__ import annotations

import argparse
import csv
import json
import random
import statistics
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from edumirror.agents import AGENT_REGISTRY
from edumirror.gm import run_episode
from edumirror.judgecheck import CORRUPTIONS, probe_absolute, probe_pairwise
from edumirror.llm import llm_from_env
from edumirror.measure import (
    RATING_METRICS,
    pairwise_compare,
    rate_behaviour,
    rate_competition,
    survey_rses,
    survey_svo,
    win_rate,
)
from edumirror.needs import init_need_state_from_profile
from edumirror.scenarios import (
    BULLYING_INTERVENTIONS,
    ELECTION_INTERVENTIONS,
    bullying_scenario,
    class_task_scenario,
    election_scenario,
    kindergarten_scenario,
    representative_scenarios,
    study_group_scenario,
)

#: Methods compared, in the paper's Table 1 column order.
METHODS = ["EduMirror", "LLMob", "BabyAGI", "D2A", "ReAct"]

#: Corruption names, for filtering probe output when logging.
CORRUPTION_KEYS = set(CORRUPTIONS)


def log(msg: str) -> None:
    """Print a timestamped progress line, flushed for live HF Job logs."""
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


def write_json(path: Path, obj) -> None:
    """Write `obj` as indented JSON, creating parent directories."""
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(obj, indent=2, default=str))


def write_csv(path: Path, rows: list[dict]) -> None:
    """Write a list of flat dicts as CSV (no-op when empty)."""
    if not rows:
        return
    path.parent.mkdir(parents=True, exist_ok=True)
    keys = list(rows[0])
    with path.open("w", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=keys)
        writer.writeheader()
        writer.writerows(rows)


# -----------------------------------------------------------------------------
# Claim 2: kindergarten scalability (Table 1).
# -----------------------------------------------------------------------------


def stage_claim2(out: Path, args) -> dict:
    """
    Run the kindergarten scalability experiment across group sizes and methods.

    Args:
        out: Output directory.
        args: Parsed CLI args (group_sizes, n_steps, n_seeds, concurrency).

    Returns:
        A results dict: {"table": {size: {method: avg}}, "records": [...]}.

    Why this design:
        Every (size, method, seed) cell runs the SAME scenario object and the
        SAME seed, so the only difference across methods is architecture. We run
        n_seeds independent episodes per cell and report the mean, because a
        single LLM episode is high-variance and a one-shot comparison would be
        indistinguishable from noise. The paper does not state its own n, so we
        report ours explicitly rather than matching an unknown.
    """
    agent_llm = llm_from_env("agent")
    judge = llm_from_env("judge")
    records: list[dict] = []

    for size in args.group_sizes:
        scenario = kindergarten_scenario(n_agents=size, n_steps=args.n_steps)
        for method in METHODS:
            for seed in range(args.n_seeds):
                t0 = time.time()
                log(f"claim2: size={size} method={method} seed={seed} ...")
                try:
                    ep = run_episode(
                        scenario, method, agent_llm, seed=seed, concurrency=args.concurrency
                    )
                except Exception as exc:  # noqa: BLE001
                    # One failed episode must not lose the other 44 cells.
                    log(f"  EPISODE FAILED: {exc}")
                    records.append(
                        {"size": size, "method": method, "seed": seed, "error": str(exc)}
                    )
                    continue

                rating = rate_behaviour(judge, ep.behaviour_text(), scenario.setting)
                row = {
                    "size": size,
                    "method": method,
                    "seed": seed,
                    "elapsed_s": round(time.time() - t0, 1),
                    **{m: rating.scores.get(m) for m in RATING_METRICS},
                    "average": rating.average(list(RATING_METRICS)),
                    "rationale": rating.rationale,
                }
                records.append(row)
                log(f"  -> avg={row['average']} ({row['elapsed_s']}s)")
                ep.save(out / "episodes" / f"kindergarten_{size}_{method}_{seed}.json")

    # Aggregate to the Table 1 shape: mean of the per-seed averages.
    table: dict[str, dict[str, float]] = {}
    for size in args.group_sizes:
        table[str(size)] = {}
        for method in METHODS:
            vals = [
                r["average"]
                for r in records
                if r.get("size") == size
                and r.get("method") == method
                and isinstance(r.get("average"), (int, float))
            ]
            table[str(size)][method] = round(statistics.mean(vals), 3) if vals else None

    results = {"table": table, "records": records, "n_seeds": args.n_seeds,
               "n_steps": args.n_steps}
    write_json(out / "claim2.json", results)
    write_csv(out / "claim2_records.csv", [r for r in records if "error" not in r])
    log(f"claim2 table: {json.dumps(table)}")
    return results


# -----------------------------------------------------------------------------
# Claim 3: dual measurement protocol.
# -----------------------------------------------------------------------------


def stage_claim3(out: Path, args) -> dict:
    """
    Run the bullying case study with dual-track measurement + RSES validity check.

    Args:
        out: Output directory.
        args: Parsed CLI args.

    Returns:
        Results dict with per-arm need dynamics, RSES pre/post, and the
        internal-vs-external correlation.

    Why the pre/post RSES design:
        Appendix F.5 administers the RSES to Alice before and after the bullying
        incidents and compares delta-RSES (external instrument) against
        delta-Value on the "self worth"/"sense of respect" dimensions (internal
        state). Agreement between them is the construct-validity evidence for
        Claim 3: it shows the internal value numbers mean what they claim to.
        We reproduce exactly that comparison.
    """
    agent_llm = llm_from_env("agent")
    surveyor = llm_from_env("judge")
    records: list[dict] = []

    for arm in BULLYING_INTERVENTIONS:
        for seed in range(args.n_seeds):
            scenario = bullying_scenario(arm, n_steps=args.n_steps)
            # Pin Alice's initial state so arms are compared under "identical
            # initial settings" (Sec 4.3).
            need_states = {
                "Alice": init_need_state_from_profile(
                    random.Random(seed), baseline_current=6.0
                )
            }
            pre_state = {
                "category_means": need_states["Alice"].category_means(),
                "needs_current": dict(need_states["Alice"].current),
            }
            pre = survey_rses(surveyor, pre_state, "Alice, a 14-year-old student")

            log(f"claim3: arm={arm} seed={seed} ...")
            try:
                ep = run_episode(
                    scenario, "EduMirror", agent_llm, seed=seed,
                    need_states=need_states, concurrency=args.concurrency,
                )
            except Exception as exc:  # noqa: BLE001
                log(f"  EPISODE FAILED: {exc}")
                continue

            alice = ep.internal_states.get("Alice", {})
            post = survey_rses(surveyor, alice, "Alice, a 14-year-old student")

            # Internal metric: mean of the two self-esteem sub-dimensions
            # (Appendix F.5's delta-Value definition).
            esteem_dims = ("self worth", "sense of respect")
            pre_val = statistics.mean(pre_state["needs_current"][d] for d in esteem_dims)
            post_val = statistics.mean(
                alice.get("needs_current", pre_state["needs_current"])[d] for d in esteem_dims
            )

            records.append({
                "arm": arm,
                "seed": seed,
                "rses_pre": pre["total"],
                "rses_post": post["total"],
                "rses_valid": pre["valid"] and post["valid"],
                "delta_rses": (post["total"] - pre["total"])
                if (pre["valid"] and post["valid"]) else None,
                "value_pre": round(pre_val, 3),
                "value_post": round(post_val, 3),
                "delta_value": round(post_val - pre_val, 3),
                **{f"cat_{k}": round(v, 3)
                   for k, v in alice.get("category_means", {}).items()},
            })
            ep.save(out / "episodes" / f"bullying_{arm}_{seed}.json")

    # Construct validity: does the external instrument track the internal state?
    paired = [
        (r["delta_value"], r["delta_rses"])
        for r in records
        if r["delta_rses"] is not None
    ]
    correlation = None
    if len(paired) >= 3:
        xs, ys = zip(*paired)
        # Guard: correlation is undefined if either series is constant, which
        # happens when a small mock/smoke run produces no variation.
        if len(set(xs)) > 1 and len(set(ys)) > 1:
            correlation = statistics.correlation(xs, ys)

    results = {
        "records": records,
        "delta_value_vs_delta_rses_correlation": correlation,
        "n_paired": len(paired),
    }
    write_json(out / "claim3.json", results)
    write_csv(out / "claim3_records.csv", records)
    log(f"claim3: correlation(delta_value, delta_RSES) = {correlation} over n={len(paired)}")
    return results


# -----------------------------------------------------------------------------
# Claim 4: pairwise win-rate heatmap (Figure 4).
# -----------------------------------------------------------------------------


def stage_claim4(out: Path, args) -> dict:
    """
    Run pairwise comparisons among all methods across the scenario suite.

    Args:
        out: Output directory.
        args: Parsed CLI args.

    Returns:
        Results dict with the win-rate matrix and every individual verdict.

    Why we generate once and compare many times:
        Each method produces one transcript per (scenario, seed); all pairwise
        comparisons then reuse those transcripts. Regenerating per comparison
        would cost O(pairs) episodes instead of O(methods) and would also mean
        A-vs-B and A-vs-C judged *different* A transcripts, adding variance that
        has nothing to do with the methods.
    """
    agent_llm = llm_from_env("agent")
    judge = llm_from_env("judge")
    rng = random.Random(1234)

    scenarios = representative_scenarios()
    scenarios += [bullying_scenario("neglectful", n_steps=args.n_steps)]
    scenarios += [study_group_scenario(), class_task_scenario(),
                  election_scenario("neglectful")]
    total_available = len(scenarios)
    if args.max_scenarios:
        scenarios = scenarios[: args.max_scenarios]

    # Claim 4 is O(scenarios x methods x seeds) episodes and is by far the most
    # expensive stage, so it gets its own seed count. Log any truncation loudly:
    # a silently-capped suite would read as "covered everything" when it did not.
    n_seeds = args.n_seeds_claim4 or args.n_seeds
    if len(scenarios) < total_available:
        log(f"claim4: NOTE capped to {len(scenarios)}/{total_available} scenarios "
            f"(paper evaluates 17); seeds={n_seeds}")
    log(f"claim4: {len(scenarios)} scenarios x {len(METHODS)} methods x {n_seeds} seeds "
        f"= {len(scenarios) * len(METHODS) * n_seeds} episodes")

    # Stage 1: generate one transcript per (scenario, method, seed).
    transcripts: dict[tuple[str, str, int], str] = {}
    for scenario in scenarios:
        for method in METHODS:
            for seed in range(n_seeds):
                log(f"claim4: gen {scenario.key}/{method}/{seed}")
                try:
                    ep = run_episode(scenario, method, agent_llm, seed=seed,
                                     concurrency=args.concurrency)
                    transcripts[(scenario.key, method, seed)] = ep.behaviour_text()
                except Exception as exc:  # noqa: BLE001
                    log(f"  FAILED: {exc}")

    # Stage 2: pairwise judging over the generated transcripts.
    verdicts: list[dict] = []
    for scenario in scenarios:
        for i, m_a in enumerate(METHODS):
            for m_b in METHODS[i + 1 :]:
                for seed in range(n_seeds):
                    ta = transcripts.get((scenario.key, m_a, seed))
                    tb = transcripts.get((scenario.key, m_b, seed))
                    if not ta or not tb:
                        continue
                    winner = pairwise_compare(judge, ta, tb, scenario.setting, rng)
                    verdicts.append({
                        "scenario": scenario.key, "method_a": m_a, "method_b": m_b,
                        "seed": seed,
                        "winner": {"A": m_a, "B": m_b}.get(winner),
                    })

    # Build the win-rate matrix: matrix[row][col] = win rate of COLUMN vs ROW,
    # matching the paper's Figure 4 convention ("the win rate of the column
    # model relative to the row model").
    matrix: dict[str, dict[str, float]] = {r: {} for r in METHODS}
    for row in METHODS:
        for col in METHODS:
            if row == col:
                matrix[row][col] = float("nan")
                continue
            wins = sum(
                1 for v in verdicts
                if {v["method_a"], v["method_b"]} == {row, col} and v["winner"] == col
            )
            losses = sum(
                1 for v in verdicts
                if {v["method_a"], v["method_b"]} == {row, col} and v["winner"] == row
            )
            matrix[row][col] = win_rate(wins, losses)

    # Average win rate per method across all opponents (the paper's headline
    # "strongest overall performance in terms of average win rates").
    avg_win = {}
    for m in METHODS:
        vals = [matrix[r][m] for r in METHODS if r != m and matrix[r][m] == matrix[r][m]]
        avg_win[m] = round(statistics.mean(vals), 3) if vals else None

    results = {
        "matrix": matrix, "average_win_rate": avg_win, "verdicts": verdicts,
        "n_scenarios": len(scenarios),
        "n_scenarios_available": total_available,
        "n_scenarios_paper": 17,
        "n_seeds": n_seeds,
        "scenarios": [s.key for s in scenarios],
    }
    write_json(out / "claim4.json", results)
    write_csv(out / "claim4_verdicts.csv", verdicts)
    log(f"claim4 average win rates: {json.dumps(avg_win)}")
    return results


# -----------------------------------------------------------------------------
# Claim 5: election intervention strategies (Figure 7).
# -----------------------------------------------------------------------------


def stage_claim5(out: Path, args) -> dict:
    """
    Compare the three intervention strategies against the neglectful control.

    Args:
        out: Output directory.
        args: Parsed CLI args.

    Returns:
        Results dict with per-arm malicious-competition counts and dispersion.

    Why dispersion, not just the mean:
        Claim 5 is specifically that interventions "mitigate extreme competitive
        tendencies and foster more balanced cooperation", and the paper's
        supporting evidence is about spread: "Their lower variance and narrower
        ranges across repeated simulations suggest a genuine balancing effect
        rather than random fluctuation", with the control showing "the widest
        fluctuation". So the testable quantity is the VARIANCE/range of malicious
        competition per arm, not only its mean. We record both.
    """
    agent_llm = llm_from_env("agent")
    judge = llm_from_env("judge")
    records: list[dict] = []

    for arm in ELECTION_INTERVENTIONS:
        scenario = election_scenario(arm, n_agents=args.election_agents,
                                     n_steps=args.n_steps)
        for seed in range(args.n_seeds_claim5):
            log(f"claim5: arm={arm} seed={seed}")
            try:
                ep = run_episode(scenario, "EduMirror", agent_llm, seed=seed,
                                 concurrency=args.concurrency)
            except Exception as exc:  # noqa: BLE001
                log(f"  FAILED: {exc}")
                continue
            coded = rate_competition(judge, ep.behaviour_text(), scenario.setting)

            # Also validate the Social Value System: does a Surveyor-measured
            # SVO angle recover each agent's internal target? (Figure 10.)
            svo_rows = []
            for persona in scenario.personas:
                st = ep.internal_states.get(persona.name, {})
                measured = survey_svo(
                    judge, f"{persona.name}: {persona.description} {persona.goal}",
                    st.get("svo_target"),
                )
                svo_rows.append({
                    "agent": persona.name,
                    "target": st.get("svo_target"),
                    "internal_angle": st.get("svo_mean_angle_deg"),
                    "measured_angle": measured["angle"],
                    "valid": measured["valid"],
                })

            records.append({
                "arm": arm, "seed": seed,
                "cooperative": coded["cooperative"],
                "competitive": coded["competitive"],
                "malicious_competition": coded["malicious_competition"],
                "valid": coded["valid"],
                "svo": svo_rows,
            })
            ep.save(out / "episodes" / f"election_{arm}_{seed}.json")

    summary: dict[str, dict] = {}
    for arm in ELECTION_INTERVENTIONS:
        vals = [r["malicious_competition"] for r in records
                if r["arm"] == arm and r["valid"]]
        coop = [r["cooperative"] for r in records if r["arm"] == arm and r["valid"]]
        if vals:
            summary[arm] = {
                "n": len(vals),
                "malicious_mean": round(statistics.mean(vals), 3),
                "malicious_stdev": round(statistics.stdev(vals), 3) if len(vals) > 1 else 0.0,
                "malicious_min": min(vals),
                "malicious_max": max(vals),
                "malicious_range": max(vals) - min(vals),
                "cooperative_mean": round(statistics.mean(coop), 3) if coop else None,
            }

    flat = [{k: v for k, v in r.items() if k != "svo"} for r in records]
    results = {"records": records, "summary": summary}
    write_json(out / "claim5.json", results)
    write_csv(out / "claim5_records.csv", flat)
    log(f"claim5 summary: {json.dumps(summary)}")
    return results


# -----------------------------------------------------------------------------
# Smoke.
# -----------------------------------------------------------------------------


def stage_smoke(out: Path, args) -> dict:
    """
    Tiny end-to-end run over every method and every measurement path.

    Args:
        out: Output directory.
        args: Parsed CLI args.

    Returns:
        A dict of per-method smoke results.

    Why:
        Exercises the exact code path the GPU job will take -- every
        architecture, the GM loop, the Rater, and the Surveyor -- so plumbing
        bugs surface locally in seconds instead of 40 minutes into a paid job.
    """
    agent_llm = llm_from_env("agent")
    judge = llm_from_env("judge")
    scenario = kindergarten_scenario(n_agents=3, n_steps=2)
    results = {}
    for method in METHODS:
        ep = run_episode(scenario, method, agent_llm, seed=0, concurrency=args.concurrency)
        rating = rate_behaviour(judge, ep.behaviour_text(), scenario.setting)
        results[method] = {
            "steps": len(ep.transcript),
            "scores": rating.scores,
            "average": rating.average(list(RATING_METRICS)),
            "usage": ep.usage,
        }
        log(f"smoke {method}: avg={rating.average(list(RATING_METRICS))}")
    write_json(out / "smoke.json", results)
    return results


def stage_judgecheck(out: Path, args) -> dict:
    """
    Test whether the LLM judge can discriminate quality at all, before trusting it.

    Args:
        out: Output directory.
        args: Parsed CLI args.

    Returns:
        {"absolute": {...}, "pairwise": {...}} probe results.

    Why this runs FIRST:
        Our initial GPU run scored every episode exactly 4.0 across all methods
        and seeds -- a broken instrument, not a tie. Reporting that as "the
        methods are equivalent" would be reporting instrument failure as a
        finding. This stage generates one real transcript, corrupts it in ways we
        KNOW make it worse (shuffled order, robotic actions), and checks the
        judge notices. If it does not, every judged claim downstream is
        uninterpretable and the logbook must say so rather than publish numbers.
    """
    judge = llm_from_env("judge")
    rng = random.Random(7)
    scenario = kindergarten_scenario(n_agents=5, n_steps=args.n_steps)

    if args.reference_episode:
        # JUDGE-ONLY MODE. The probe needs one reference transcript, and it does
        # not matter who generated it -- the corruptions are applied to whatever
        # it is, and every judge is compared against the SAME text. Reusing an
        # archived episode therefore costs zero agent calls, which is what makes
        # probing an expensive frontier judge cost cents rather than dollars.
        # It also removes a confound: every judge now grades byte-identical text.
        ep_data = json.loads(Path(args.reference_episode).read_text())
        chunks = []
        for entry in ep_data["transcript"]:
            chunks.append(f"--- Step {entry['step']} ({entry['location']}) ---")
            chunks.append(entry["narration"])
            for name, action in entry["actions"].items():
                chunks.append(f"{name}: {action}")
        transcript = "\n".join(chunks)
        log(f"judgecheck: reusing archived reference transcript "
            f"({args.reference_episode}, {len(transcript)} chars, "
            f"{len(ep_data['transcript'])} steps) -- ZERO agent calls")
    else:
        agent_llm = llm_from_env("agent")
        log("judgecheck: generating one reference transcript (EduMirror) ...")
        ep = run_episode(scenario, "EduMirror", agent_llm, seed=0,
                         concurrency=args.concurrency)
        transcript = ep.behaviour_text()

    log("judgecheck: probing ABSOLUTE rater (real vs corrupted) ...")
    absolute = probe_absolute(judge, transcript, scenario.setting, rng)
    log(f"  ABSOLUTE verdict={absolute['verdict']} real_avg={absolute['real']['average']} "
        f"margins={absolute['margins']}")

    log("judgecheck: probing PAIRWISE judge (real vs corrupted) ...")
    pairwise = probe_pairwise(judge, transcript, scenario.setting, rng,
                              n_trials=args.judge_trials)
    log(f"  PAIRWISE verdict={pairwise['verdict']} "
        f"{ {k: v for k, v in pairwise.items() if k in CORRUPTION_KEYS} }")

    results = {"absolute": absolute, "pairwise": pairwise,
               "reference_transcript_chars": len(transcript),
               "judge_usage": judge.usage.as_dict()}
    write_json(out / "judgecheck.json", results)

    log(f"JUDGECHECK VERDICT: absolute={absolute['verdict']} pairwise={pairwise['verdict']}")
    # An UNREADABLE verdict is OUR bug, not a finding about the model. Say so
    # loudly and show the evidence, so nobody reads it as "the judge is blind".
    for track, res in (("absolute", absolute), ("pairwise", pairwise)):
        if res["verdict"] == "UNREADABLE":
            log(f"  !! {track}: output was UNPARSEABLE -- this is a HARNESS problem, "
                f"NOT evidence the judge cannot discriminate.")
            for s in res.get("unreadable_samples", [])[:1]:
                log(f"     raw sample: {s[:400]!r}")
    u = judge.usage.as_dict()
    if u.get("truncated"):
        log(f"  !! {u['truncated']}/{u['calls']} judge responses hit max_tokens "
            f"(finish_reason=length) -- raise EDUMIRROR_JUDGE_MAX_TOKENS.")
    return results


STAGES = {
    "smoke": stage_smoke,
    "judgecheck": stage_judgecheck,
    "claim2": stage_claim2,
    "claim3": stage_claim3,
    "claim4": stage_claim4,
    "claim5": stage_claim5,
}


def main() -> None:
    """Parse args and run the requested stage(s)."""
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--stage", default="smoke",
                   choices=list(STAGES) + ["all"], help="which experiment to run")
    p.add_argument("--judge-trials", type=int, default=6,
                   help="pairwise trials per corruption in the judgecheck stage")
    p.add_argument("--reference-episode", type=str, default="",
                   help="path to an archived episode JSON to use as the probe's "
                        "reference transcript. Enables JUDGE-ONLY mode: no agent "
                        "calls at all, so probing a paid frontier judge costs "
                        "cents. Also removes a confound -- every judge then "
                        "grades byte-identical text.")
    p.add_argument("--out", type=Path, default=Path("outputs"))
    p.add_argument("--group-sizes", type=int, nargs="+", default=[5, 15, 30],
                   help="kindergarten group sizes (paper: 5 15 30)")
    p.add_argument("--n-steps", type=int, default=8)
    p.add_argument("--n-seeds", type=int, default=3,
                   help="episodes per cell; higher = less noise, more cost")
    p.add_argument("--n-seeds-claim5", type=int, default=8,
                   help="repeats per intervention arm; Claim 5 is about VARIANCE, "
                        "so it needs more repeats than the mean-based claims")
    p.add_argument("--n-seeds-claim4", type=int, default=0,
                   help="seeds for the pairwise heatmap (0 = use --n-seeds). "
                        "Claim 4 is the most expensive stage (scenarios x methods "
                        "x seeds episodes), so it gets its own knob")
    p.add_argument("--election-agents", type=int, default=5)
    p.add_argument("--max-scenarios", type=int, default=0,
                   help="cap scenarios in claim4 (0 = all)")
    p.add_argument("--concurrency", type=int, default=16)
    args = p.parse_args()

    out = args.out
    out.mkdir(parents=True, exist_ok=True)

    stages = ["judgecheck", "claim2", "claim3", "claim4", "claim5"] if args.stage == "all" else [args.stage]
    manifest = {"stages": stages, "args": vars(args), "started": time.time()}
    t0 = time.time()
    for stage in stages:
        log(f"=== STAGE {stage} ===")
        STAGES[stage](out, args)
    manifest["elapsed_s"] = round(time.time() - t0, 1)
    write_json(out / "manifest.json", manifest)
    log(f"DONE in {manifest['elapsed_s']}s -> {out}")


if __name__ == "__main__":
    main()