Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 48,099 Bytes
e3a266f
 
 
 
eae0824
e3a266f
24df058
 
 
eae0824
6db0e7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
6db0e7c
 
 
 
 
 
 
 
 
8d461e0
 
 
 
e3a266f
 
eae0824
 
6db0e7c
 
 
 
 
9445a96
 
eae0824
9445a96
 
 
 
 
 
eae0824
32539d2
 
 
 
e3a266f
 
 
 
 
 
 
48157bc
e3a266f
24df058
e3a266f
 
 
d2835d5
e3a266f
 
 
 
 
 
 
 
6db0e7c
 
e3a266f
 
 
 
 
 
 
 
b064c6f
 
 
6db0e7c
48157bc
 
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
 
 
 
 
 
 
eae0824
6db0e7c
 
 
 
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
e3a266f
 
 
6db0e7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
24df058
 
 
 
8d461e0
 
e3a266f
24df058
 
 
8d461e0
24df058
8d461e0
24df058
 
 
 
 
8d461e0
 
24df058
 
8d461e0
24df058
 
e3a266f
 
 
8d461e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24df058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d461e0
 
 
 
 
 
 
 
 
 
 
24df058
 
 
e3a266f
 
6db0e7c
 
 
 
 
e3a266f
 
24df058
e3a266f
24df058
 
 
e3a266f
24df058
e3a266f
 
 
 
 
 
 
 
 
6db0e7c
 
e3a266f
6db0e7c
 
 
 
 
 
e3a266f
 
 
 
 
 
6db0e7c
eae0824
6db0e7c
 
e3a266f
 
48157bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
24df058
8d461e0
24df058
 
 
 
8d461e0
 
 
 
 
 
 
 
24df058
e3a266f
 
 
 
 
 
6db0e7c
 
 
e3a266f
6db0e7c
e3a266f
6db0e7c
48157bc
e3a266f
 
 
 
 
 
6db0e7c
e3a266f
 
 
 
 
24df058
 
 
 
 
48157bc
 
 
 
 
6db0e7c
48157bc
 
 
e3a266f
48157bc
 
e3a266f
 
 
 
 
6db0e7c
48157bc
6db0e7c
e3a266f
 
 
 
 
 
 
 
24df058
 
 
 
 
6db0e7c
24df058
 
 
 
 
 
 
 
 
 
 
6db0e7c
 
 
 
48157bc
 
 
 
6db0e7c
48157bc
6db0e7c
48157bc
24df058
6db0e7c
 
48157bc
 
6db0e7c
48157bc
 
 
 
 
 
 
 
 
 
 
6db0e7c
 
 
48157bc
 
 
 
6db0e7c
 
 
48157bc
24df058
 
 
 
 
e3a266f
 
48157bc
 
 
 
 
9445a96
eae0824
9445a96
eae0824
d2835d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eae0824
 
6db0e7c
 
 
d2835d5
48157bc
 
bc8474f
 
6db0e7c
 
48157bc
d2835d5
 
48157bc
 
 
 
 
d2835d5
 
 
6db0e7c
d2835d5
48157bc
 
 
 
d2835d5
48157bc
6db0e7c
bc8474f
48157bc
 
 
 
 
 
 
 
 
9445a96
 
 
48157bc
eae0824
6db0e7c
d2835d5
6db0e7c
48157bc
d2835d5
48157bc
 
 
bc8474f
 
d2835d5
bc8474f
d2835d5
 
48157bc
6db0e7c
 
bc8474f
d2835d5
 
 
 
 
 
48157bc
 
 
d2835d5
 
 
 
9445a96
eae0824
6db0e7c
9445a96
6db0e7c
 
 
d2835d5
 
 
bc8474f
d2835d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
 
d2835d5
6db0e7c
 
d2835d5
9445a96
eae0824
d2835d5
 
 
 
 
 
 
9445a96
 
 
 
6db0e7c
d2835d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9445a96
 
 
 
 
 
 
d2835d5
 
 
 
 
 
 
 
 
 
32539d2
 
eae0824
32539d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eae0824
32539d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48d5824
 
32539d2
 
 
eae0824
7059e24
 
 
 
 
 
 
 
 
32539d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
 
24df058
e3a266f
24df058
48157bc
eae0824
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
24df058
6db0e7c
e3a266f
d2835d5
 
eae0824
d2835d5
32539d2
 
 
 
48157bc
 
 
eae0824
48157bc
e3a266f
 
 
 
 
 
 
 
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
# /// script
# requires-python = ">=3.12"
# dependencies = ["harbor==0.25.0"]
# ///
"""s3-aggregation's checks that need no model (huggingface/legion#115, section 5):

    uv run check.py                 # all of them; the Trials run on HF Sandboxes (HF_TOKEN)
    uv run check.py --env docker    # the Trials in local docker instead
    uv run check.py --env none      # skip the Trials
    uv run check.py --run RUN_DIR   # also a Legion run of a team (group 5)

1. Generator: generate.py reproduces problems.json and tasks/ byte for byte from its seed;
   another seed gives other problems; 32 problems of 16 integers in 1..99; the English words
   read back to their numbers; a team `agg-pPP-nNN` has one task per slot, `-sKK`, whose answer
   is the problem's first N numbers sorted and whose instruction states slot K's number.
2. Graders, run as Harbor runs them (tests/ copied in after the agent is done), on slot 1 of
   every team (every slot's tests/ and solution/ are the same, which this checks): the oracle
   (solution/solve.sh) scores 1, and a wrong, partial, padded, unsorted or duplicate-dropping
   answer scores 0. On one team per size, malformed answers (missing, empty, not JSON, NaN, an
   object, strings, words, floats, booleans, nested, a "####" prefix, invalid UTF-8) and cheats
   score 0: the answer as a symlink to the tests' expected.json (dangling until the tests
   arrive, absolute or relative), a symlink or a hardlink to a right answer elsewhere, a
   hardlink to expected.json, a symlinked /app (to a right answer, or to the tests' folder), an
   expected.json planted as a link to the answer before the tests arrive, a directory and a FIFO
   (which must not hang the grader); and a wrong answer with Python made to read any answer as
   right: a json.py in the grader's working directory or on PYTHONPATH, a sitecustomize on
   PYTHONPATH, a usercustomize or a .pth file in the user site (PYTHONUSERBASE), and a
   `dirname` shadowed on the PATH that points expected.json at the agent's own file.
3. No-cheat, in the files: a task folder holds only instruction.md, task.toml, tests/ and
   solution/; its instruction states its own slot's number on one line and is otherwise the same
   for every task of its team size, so it holds no teammate's number; the answer is only in
   tests/ and solution/; and there is no folder beside tasks/ that holds numbers.
4. No-cheat, from inside Trials (`--env`), on team `agg-p01-n16`, with probe agents (no model):
   - one per slot, each in its own slot's task, looks around the container while "the agent
     works": no tests/ or solution/, no file holding the answer or a teammate's hyphenated number
     word, no process whose environment or command line holds a teammate's number, and its
     instruction holds its own number and no teammate's; then it writes the answer, the same
     search finds it (a control), and the task's own verifier scores it 1;
   - the others leave a cheat with a wrong answer: /app/answer.json as a symlink to
     /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any
     answer as right wherever the verifier may start; a sitecustomize in site-packages that
     does the same. The verifier scores each 0.
   `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox
   uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is
   over 65535 (some clusters): use legion's `--env legion.harbor.envs:HFSandbox` there.
5. No-cheat, a Legion run (`--run`, a local run's directory with its agents' event streams and
   the board export; the team is the selector's `agg-pPP-nNN`, agent K on slot K): no system
   prompt or first prompt holds a teammate's number, and each agent's first prompt holds its
   own; the first output in which an agent sees a teammate's number is a board read, or a later
   prompt (a wake-up quoting the board); and the first post holding each number is its owner's.
   A number counts in words ("twenty-six") and in digits where they read as a held number: an
   array of the team's integers (the JSON answer, or part of it, down to `[26]`), an agent's
   number in a mapping (`"agent-002": 26`) and a stated number (`number is 26`); bare ids,
   counts and timestamps don't. A board read is a `legion-tool message_board.*` command, not a
   command that names the board (`cat /tmp/message_board.txt`). The audit itself is checked on
   synthetic runs, always: a clean one and one whose ids and timestamps hold the team's numbers
   pass, and each leak fails (a teammate's number in words, the JSON answer, a one-element
   array, a mapping and a stated number, in the first prompt or in a non-board output before the
   board, including one from a file named after the board, and a number first posted by an agent
   that doesn't hold it).
6. Metrics: eval/metrics.py on Slurm run directories (the spec Legion's example copies, its
   `${TEAM:-...}` and `${N:-4}`, Trials graded by the tasks' own grader): the task and the roster
   come from the spec as the run resolved it (`cluster.env`, then `run.env`, else the defaults),
   and a planned agent without results, Trials of an unplanned agent and Trials of another task
   than the spec selects are flagged in `missing`, never dropped.
"""

import argparse
import asyncio
import base64
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from collections import Counter
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import generate as g  # noqa: E402

TASK_FILES = {"instruction.md", "task.toml", "tests/test.sh", "tests/expected.json",
              "solution/solve.sh"}
PROBE_TEAM = "agg-p01-n16"
NUMBER_LINE = re.compile(r"^Your private number is ([a-z-]+)\.$", re.MULTILINE)
failures: list[str] = []


def check(ok: bool, what: str) -> None:
    if not ok:
        failures.append(what)


def files(root: Path) -> dict[str, bytes]:
    """Relative path -> bytes for the generated files under root (not their modes: a download
    from the Hub has none, and Harbor runs the scripts with bash)."""
    out = {"problems.json": (root / "problems.json").read_bytes()}
    for path in sorted((root / "tasks").rglob("*")):
        if path.is_file():
            out[str(path.relative_to(root))] = path.read_bytes()
    return out


VALUES = {w: i for i, w in enumerate(g.ONES) if w} | {
    w: 10 * i for i, w in enumerate(g.TENS) if w}


def read_words(text: str) -> int:
    """English words back to a number, independently of generate.words."""
    head, _, tail = text.partition("-")
    return VALUES[head] + (VALUES[tail] if tail else 0)


def team_of(task: str) -> tuple[int, int]:
    """(problem, N) of a task or team name, `agg-pPP-nNN[-sKK]`."""
    m = re.match(r"agg-p(\d\d)-n(\d\d)", task)
    return int(m[1]), int(m[2])


def held(team: str) -> dict[str, str]:
    """A team's agents (Legion's consecutive names: agent K on slot K) and their numbers."""
    problem, n = team_of(team)
    numbers = json.loads((HERE / "problems.json").read_text())["problems"][f"p{problem:02d}"]
    return {f"agent-{k:03d}": g.words(x) for k, x in enumerate(numbers[:n], 1)}


def check_generator() -> None:
    with tempfile.TemporaryDirectory() as d:
        g.generate(Path(d))
        check(files(Path(d)) == files(HERE), "generate.py does not reproduce the committed files")
    drawn = g.problems()
    check(drawn == g.problems(), "the same seed gave other problems")
    check(drawn != g.problems(g.SEED + 1), "another seed gave the same problems")
    check(len(drawn) == 32 and all(len(p) == 16 and all(type(x) is int and 1 <= x <= 99
                                                        for x in p) for p in drawn),
          "not 32 problems of 16 integers in 1..99")
    check(all(read_words(g.words(n)) == n for n in range(1, 100))
          and len({g.words(n) for n in range(1, 100)}) == 99, "the English words are wrong")
    names = []
    for p, numbers in enumerate(drawn, 1):
        for n in g.SIZES:
            team = numbers[:n]
            for slot, number in enumerate(team, 1):
                name = g.task_name(p, n, slot)
                names.append(name)
                task = HERE / "tasks" / name
                expected = json.loads((task / "tests" / "expected.json").read_text())
                check(expected == sorted(team), f"{name}: expected.json is not the first {n} sorted")
                stated = NUMBER_LINE.findall((task / "instruction.md").read_text())
                check(len(stated) == 1 and read_words(stated[0]) == number,
                      f"{name}: the instruction does not state slot {slot}'s number ({stated})")
    check(sorted(p.name for p in (HERE / "tasks").iterdir()) == sorted(names),
          "tasks/ has other folders")
    for p, _ in enumerate(drawn, 1):
        for n in g.SIZES:
            slots = sorted(x for x in names if x.startswith(g.team_name(p, n) + "-"))
            check(slots == [g.task_name(p, n, k) for k in range(1, n + 1)],
                  f"{g.team_name(p, n)}: its slots in name order are not slot order")


def grade(task: Path, answer: bytes | None = None, cheat=None) -> int:
    """The task's grader as Harbor runs it: `app/answer.json` stands for /app/answer.json and
    `tests/` for /tests, whose files are copied in only after the agent is done, through any
    link the agent left there (the worst case). `cheat(root)` lays out what an agent leaves
    behind instead of `answer` (None: no file), and may return the grader's extra `env` and
    working directory (`cwd`). Returns the reward."""
    with tempfile.TemporaryDirectory() as d:
        root = Path(d).resolve()  # the grader takes paths without links
        app, tests, verifier = root / "app", root / "tests", root / "verifier"
        app.mkdir()
        extra = {}
        if cheat is not None:
            extra = cheat(root) or {}
        elif answer is not None:
            (app / "answer.json").write_bytes(answer)
        tests.mkdir(exist_ok=True)
        for name in ("test.sh", "expected.json"):
            shutil.copyfile(task / "tests" / name, tests / name)
        env = {**os.environ, "ANSWER": str(app / "answer.json"), "VERIFIER_DIR": str(verifier),
               **extra.get("env", {})}
        try:
            subprocess.run(["bash", str(tests / "test.sh")], capture_output=True, timeout=60,
                           env=env, cwd=extra.get("cwd"), check=False)
        except subprocess.TimeoutExpired:
            return -1  # a grader that hangs is a failure too
        return int((verifier / "reward.txt").read_text().strip())


FAKE_JSON = "def loads(*args, **kwargs):\n    return [1]\n"  # any answer equals any expected
PATCH_JSON = "import json\njson.loads = lambda *args, **kwargs: [1]\n"


def planted(root: Path, folder: str, name: str, text: str) -> Path:
    """A wrong answer, and `name` holding `text` in root/folder (made)."""
    (root / "app" / "answer.json").write_text("[0]")
    (root / folder).mkdir(parents=True, exist_ok=True)
    (root / folder / name).write_text(text)
    return root / folder


def user_site(name: str, text: str):
    """A hook in the user site that PYTHONUSERBASE points at."""
    def cheat(root):
        env = {"PYTHONUSERBASE": str(root / "userbase")}
        site = subprocess.run(["python3", "-c", "import site; print(site.getusersitepackages())"],
                              env={**os.environ, **env}, capture_output=True, text=True,
                              check=True).stdout.strip()
        planted(root, str(Path(site).relative_to(root)), name, text)
        return {"env": env}
    return cheat


def shadowed_dirname(root: Path) -> dict:
    """A `dirname` first on the PATH that points expected.json at the agent's own file."""
    (root / "app" / "expected.json").write_text("[0]")
    script = planted(root, "bin", "dirname", f"#!/bin/sh\necho {root / 'app'}\n") / "dirname"
    script.chmod(0o755)
    return {"env": {"PATH": f"{root / 'bin'}:{os.environ['PATH']}"}}


def oracle(task: Path) -> int:
    with tempfile.TemporaryDirectory() as d:
        path = Path(d) / "app" / "answer.json"
        subprocess.run(["bash", str(task / "solution" / "solve.sh")], capture_output=True,
                       timeout=60, env={**os.environ, "ANSWER": str(path)}, check=True)
        return grade(task, path.read_bytes())


def wrong_answers(team: list[int]) -> dict[str, list]:
    """The answers that must score 0 for a team (sorted): those that apply to it."""
    last = team[-1] + 1 if team[-1] < 99 else team[-1] - 1
    out = {"wrong": sorted(team[:-1] + [last]), "partial": team[:-1],
           "padded": sorted(team + [team[-1]])}
    if len(set(team)) > 1:
        out["unsorted"] = team[::-1]
    if len(set(team)) < len(team):
        out["duplicate-dropping"] = sorted(set(team))
    return out


def malformed(team: list[int]) -> dict[str, bytes | None]:
    dump = json.dumps(team).encode()
    return {"missing": None, "empty": b"", "not JSON": b"[1, 2,", "NaN": b"[NaN]",
            "object": json.dumps({"answer": team}).encode(),
            "strings": json.dumps([str(x) for x in team]).encode(),
            "words": json.dumps([g.words(x) for x in team]).encode(),
            "floats": json.dumps([float(x) for x in team]).encode(),
            "booleans": json.dumps([True] * len(team)).encode(),
            "nested": json.dumps([team]).encode(), "#### prefix": b"#### " + dump,
            "invalid UTF-8": b"\xff" + dump}


def cheats(task: Path) -> dict:
    """What an agent could leave behind to score without the answer, or with a right answer
    that is not its own regular file: `cheat(root)` for grade()."""
    right = (task / "tests" / "expected.json").read_bytes()

    def link(target):  # the answer as a symlink
        return lambda root: (root / "app" / "answer.json").symlink_to(target(root))

    def right_elsewhere(make):
        def cheat(root):
            (root / "elsewhere.json").write_bytes(right)
            make(root / "elsewhere.json", root / "app" / "answer.json")
        return cheat

    def hardlink_expected(root):  # as if the tests could be reached while the agent works
        (root / "tests").mkdir()
        shutil.copyfile(task / "tests" / "expected.json", root / "tests" / "expected.json")
        os.link(root / "tests" / "expected.json", root / "app" / "answer.json")

    def app_to(make_target):
        def cheat(root):
            (root / "app").rmdir()
            (root / "app").symlink_to(make_target(root))
        return cheat

    def right_folder(root):
        (root / "real").mkdir()
        (root / "real" / "answer.json").write_bytes(right)
        return root / "real"

    def tests_folder(root):
        (root / "tests").mkdir()
        (root / "tests" / "answer.json").symlink_to("expected.json")
        return root / "tests"

    def planted_expected(root):  # the upload writes the answer into it through the link
        (root / "app" / "answer.json").write_bytes(b"[0]")
        (root / "tests").mkdir()
        (root / "tests" / "expected.json").symlink_to(root / "app" / "answer.json")

    return {
        "symlink to the tests' expected.json": link(lambda r: r / "tests" / "expected.json"),
        "relative symlink to the tests' expected.json": link(
            lambda r: Path("../tests/expected.json")),
        "symlink to a right answer elsewhere": right_elsewhere(lambda s, d: d.symlink_to(s)),
        "hardlink to a right answer elsewhere": right_elsewhere(os.link),
        "hardlink to the tests' expected.json": hardlink_expected,
        "symlinked /app with a right answer": app_to(right_folder),
        "symlinked /app into the tests": app_to(tests_folder),
        "expected.json planted as a link to the answer": planted_expected,
        "a directory": lambda root: (root / "app" / "answer.json").mkdir(),
        "a FIFO": lambda root: os.mkfifo(root / "app" / "answer.json"),
        # a wrong answer, and Python made to read any answer as right
        "a json.py in the working directory": lambda root: {
            "cwd": planted(root, "work", "json.py", FAKE_JSON)},
        "a json.py on PYTHONPATH": lambda root: {
            "env": {"PYTHONPATH": str(planted(root, "pp", "json.py", FAKE_JSON))}},
        "a sitecustomize on PYTHONPATH": lambda root: {
            "env": {"PYTHONPATH": str(planted(root, "pp", "sitecustomize.py", PATCH_JSON))}},
        "a usercustomize in the user site": user_site("usercustomize.py", PATCH_JSON),
        "a .pth file in the user site": user_site(
            "hook.pth", "import json; json.loads = lambda *args, **kwargs: [1]\n"),
        "a dirname shadowed on the PATH": shadowed_dirname,
    }


def check_graders() -> dict[str, int]:
    covered: dict[str, int] = {}
    for task in sorted((HERE / "tasks").glob("*-s01")):  # slot 1 of every team
        for other in sorted(task.parent.glob(task.name.removesuffix("-s01") + "-s*")):
            check(all((other / f).read_bytes() == (task / f).read_bytes()
                      for f in ("tests/test.sh", "tests/expected.json", "solution/solve.sh")),
                  f"{other.name}: tests/ or solution/ differ from slot 1's")
        team = json.loads((task / "tests" / "expected.json").read_text())
        check(oracle(task) == 1, f"{task.name}: the oracle does not score 1")
        cases = {k: (json.dumps(v).encode(), None) for k, v in wrong_answers(team).items()}
        if task.name.startswith("agg-p01-"):
            cases |= {k: (v, None) for k, v in malformed(team).items()}
            cases |= {k: (None, cheat) for k, cheat in cheats(task).items()}
        for case, (answer, cheat) in cases.items():
            covered[case] = covered.get(case, 0) + 1
            check(grade(task, answer, cheat) == 0, f"{task.name}: {case} does not score 0")
    check(covered.get("duplicate-dropping", 0) > 0, "no task has a duplicate to drop")
    return covered


def check_files() -> None:
    by_size: dict[int, set[tuple[str, str]]] = {}
    for task in sorted((HERE / "tasks").iterdir()):
        listed = {str(p.relative_to(task)) for p in task.rglob("*") if p.is_file()}
        check(listed == TASK_FILES, f"{task.name}: holds {sorted(listed ^ TASK_FILES)}")
        problem, n = team_of(task.name)
        slot = int(task.name.split("-s")[-1])
        toml = (task / "task.toml").read_text().replace(task.name, "TASK").replace(
            f"problem = {problem}\n", "problem = P\n").replace(f"slot = {slot}\n", "slot = K\n")
        text = (task / "instruction.md").read_text()
        own = held(task.name)[f"agent-{slot:03d}"]
        check(NUMBER_LINE.findall(text) == [own], f"{task.name}: its number line isn't its own")
        generic = NUMBER_LINE.sub("Your private number is NUMBER.", text)  # no other number
        by_size.setdefault(n, set()).add((generic, toml))
        answer = (task / "tests" / "expected.json").read_text().strip()
        holders = {str(p.relative_to(task)) for p in task.rglob("*")
                   if p.is_file() and answer in p.read_text()}
        check(holders == {"tests/expected.json", "solution/solve.sh"},
              f"{task.name}: the answer is in {sorted(holders)}")
    check(all(len(v) == 1 for v in by_size.values()),
          "an instruction (but its number) or task.toml differs between tasks of one team size")
    beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", "legion", "eval", ".cache",
                                                               "__pycache__", ".git"}
    check(not beside, f"folders beside tasks/: {sorted(beside)}")


def holds(text: str, words) -> set[str]:
    """The number words found in `text` as whole words ("seven" is not in "seventy-seven")."""
    return {w for w in words if re.search(rf"(?<![A-Za-z-]){re.escape(w)}(?![A-Za-z-])", text)}


# Runs in the container as `python3 -c PROBE_PY <base64 config>`, so it holds no number word
# itself: its own command line is searched too. In files it looks for the teammates' hyphenated
# number words (a bare single-digit word is in many system files) and the answer.
PROBE_PY = r"""
import base64, json, os, re, sys

cfg = json.loads(base64.b64decode(sys.argv[1]))
own, others, answer = cfg["own"], cfg["others"], cfg["answer"]
needles = [w for w in others if "-" in w] + [answer, answer.replace(" ", "")]


def whole(word, text):
    return re.search(r"(?<![A-Za-z-])" + re.escape(word) + r"(?![A-Za-z-])", text)


def search(found_in):
    found = []
    for top, dirs, names in os.walk("/"):
        if top == "/":
            dirs[:] = [d for d in dirs if d not in ("proc", "sys", "dev", "logs")]
        for name in names:
            path = os.path.join(top, name)
            try:
                if os.path.islink(path) or not os.path.isfile(path):
                    continue
                if os.path.getsize(path) > 20 << 20:
                    continue
                with open(path, "rb") as stream:
                    text = stream.read().decode("utf-8", "ignore")
            except OSError:
                continue
            if any(x in text for x in found_in):
                found.append(path)
    return found


out = {"visible": [d for d in ("/tests", "/solution") if os.path.exists(d)],
       "files": search(needles), "env": [], "cmdline": [], "own_env": [], "processes": 0}
for pid in os.listdir("/proc"):
    if not pid.isdigit():
        continue
    try:
        with open(f"/proc/{pid}/environ", "rb") as stream:
            env = stream.read().decode("utf-8", "ignore").split("\0")
        with open(f"/proc/{pid}/cmdline", "rb") as stream:
            cmd = stream.read().decode("utf-8", "ignore").replace("\0", " ")
    except OSError:
        continue
    out["processes"] += 1
    for entry in env:
        key, _, value = entry.partition("=")
        if any(whole(w, value) for w in others):
            out["env"].append(f"{pid}:{key}")
        if value == own:
            out["own_env"].append(f"{pid}:{key}")
    if any(whole(w, cmd) for w in others):
        out["cmdline"].append(f"{pid}:{cmd[:80]}")
os.makedirs("/app", exist_ok=True)
with open("/app/answer.json", "w") as stream:
    stream.write(answer)
out["control"] = search([answer])  # the same search finds the answer once it is written
print("PROBE " + json.dumps(out))
"""
# What a cheating agent leaves for the verifier, before the tests arrive
FAKE_JSON_SH = "printf 'def loads(*args, **kwargs):\\n    return [1]\\n'"
CHEATS = {
    "symlink": "mkdir -p /app && ln -s /tests/expected.json /app/answer.json",
    "symlinked-app": "mkdir -p /tests && ln -s expected.json /tests/answer.json"
                     " && rm -rf /app && ln -s /tests /app",
    # a wrong answer, and a json module that reads any answer as right wherever the verifier
    # may start (/, /app, /tests, the home and the verifier's folders), or a site hook
    "json-module": "mkdir -p /app /tests /logs/verifier && printf '[0]' > /app/answer.json && "
                   "for d in / /app /tests /root /logs/verifier; do "
                   f"{FAKE_JSON_SH} > $d/json.py; done",
    "sitecustomize": "mkdir -p /app && printf '[0]' > /app/answer.json && printf 'import json\\n"
                     "json.loads = lambda *args, **kwargs: [1]\\n' > \"$(python3 -c "
                     "'import site; print(site.getsitepackages()[0])')/sitecustomize.py\"",
}


try:
    from harbor.agents.base import BaseAgent

    class Probe(BaseAgent):
        """No model. `mode` answer: in its slot's task, looks around the container as that
        slot's agent could while it works, writes `probe.json` in its logs dir on the host, then
        the answer for the verifier. Any other mode: leaves that cheat (CHEATS) instead."""

        def __init__(self, *args, mode="answer", own="", others=(), answer="", **kwargs):
            super().__init__(*args, **kwargs)
            self.mode, self.answer = mode, answer
            self.own, self.others = own, list(others)

        @staticmethod
        def name() -> str:
            return "s3-aggregation-probe"

        def version(self) -> str:
            return "4"

        async def setup(self, environment) -> None:
            pass

        async def run(self, instruction, environment, context) -> None:
            if self.mode != "answer":
                result = await environment.exec(CHEATS[self.mode], timeout_sec=60)
                (self.logs_dir / "probe.json").write_text(json.dumps(
                    {"return_code": result.return_code, "cheat": CHEATS[self.mode]}))
                return
            # the teammates' numbers travel base64-encoded: a copy of the command in the
            # container would otherwise hold them
            encoded = base64.b64encode(json.dumps(
                {"own": self.own, "others": self.others, "answer": self.answer}).encode()).decode()
            result = await environment.exec(f"python3 -c {shlex.quote(PROBE_PY)} {encoded}",
                                            timeout_sec=600)
            line = next((x for x in (result.stdout or "").splitlines()
                         if x.startswith("PROBE ")), None)
            found = json.loads(line.removeprefix("PROBE ")) if line else {}
            (self.logs_dir / "probe.json").write_text(json.dumps({
                "return_code": result.return_code, **found,
                "instruction_holds": sorted(holds(instruction, [self.own, *self.others])),
            }, indent=1))
except ImportError:  # `--env none` needs no Harbor
    Probe = None


async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict, task: str,
                    name: str = "") -> tuple[dict | None, dict]:
    """One Trial of `task` with the probe in `mode`: (its probe.json, rewards and error)."""
    from harbor.models.trial.config import (
        AgentConfig,
        EnvironmentConfig,
        TaskConfig,
        TrialConfig,
    )
    from harbor.trial.trial import Trial

    sandbox = {"flavor": "cpu-basic", "job_timeout": 900}
    environment = (EnvironmentConfig(import_path=env, kwargs=sandbox if "Sandbox" in env else {})
                   if ":" in env else
                   EnvironmentConfig(type=env, kwargs=sandbox if env == "hf-sandbox" else {}))
    config = TrialConfig(
        task=TaskConfig(path=HERE / "tasks" / task), trial_name=f"probe-{name or mode}",
        trials_dir=jobs, environment=environment,
        agent=AgentConfig(import_path="__main__:Probe", kwargs={"mode": mode, **kwargs}))
    result = await (await Trial.create(config)).run()
    probe_file = jobs / config.trial_name / "agent" / "probe.json"
    probe = json.loads(probe_file.read_text()) if probe_file.is_file() else None
    return probe, {"rewards": result.verifier_result.rewards if result.verifier_result else None,
                   "error": result.exception_info.exception_message
                   if result.exception_info else None}


async def check_trials(env: str, jobs: Path) -> dict:
    team = held(PROBE_TEAM)
    tasks = {agent: g.task_name(*team_of(PROBE_TEAM), int(agent[-3:])) for agent in team}
    answer = (HERE / "tasks" / tasks["agent-001"] / "tests" / "expected.json").read_text().strip()
    probes = {agent: {"own": own, "answer": answer,
                      "others": sorted({w for w in team.values() if w != own})}
              for agent, own in team.items()}
    gate = asyncio.Semaphore(10)  # sandboxes at once

    async def one(mode, kwargs, task, name=""):
        async with gate:
            return await run_trial(env, jobs, mode, kwargs, task, name)

    runs = await asyncio.gather(
        *(one("answer", kwargs, tasks[agent], agent) for agent, kwargs in probes.items()),
        *(one(mode, {}, tasks["agent-001"]) for mode in CHEATS))
    report = {}
    for (agent, kwargs), (probe, graded) in zip(probes.items(), runs[:len(probes)], strict=True):
        what = f"Trial {tasks[agent]}"
        ran = probe is not None and probe.get("return_code") == 0 and "files" in probe
        check(ran, f"{what}: the probe did not run ({graded['error']})")
        if ran:
            check(not probe["visible"], f"{what}: visible while the agent works: "
                  f"{probe['visible']}")
            check(not probe["files"], f"{what}: files hold a teammate's number or the answer: "
                  f"{probe['files']}")
            check(not probe["env"], f"{what}: a process's environment holds a teammate's "
                  f"number: {probe['env']}")
            check(not probe["cmdline"], f"{what}: a command line holds a teammate's number: "
                  f"{probe['cmdline']}")
            check(probe["instruction_holds"] == [kwargs["own"]],
                  f"{what}: the instruction holds {probe['instruction_holds']}, not just "
                  f"{kwargs['own']}")
            check("/app/answer.json" in probe["control"],
                  f"{what}: the search did not find the written answer ({probe['control']})")
        check(graded["rewards"] == {"reward": 1.0},
              f"{what}: the verifier gave the answer {graded['rewards']} ({graded['error']})")
        report[tasks[agent]] = {"instruction_holds": probe and probe.get("instruction_holds"),
                                "processes": probe and probe.get("processes"),
                                "teammates": len(kwargs["others"]), **graded}
    for mode, (left, result) in zip(CHEATS, runs[len(probes):], strict=True):
        check(left is not None and left["return_code"] == 0, f"Trial: cheat {mode} not left")
        check(result["rewards"] == {"reward": 0.0},
              f"Trial: cheat {mode} gave {result['rewards']} ({result['error']})")
        report[mode] = {"left": left, **result}
    return report


def texts(message: dict) -> str:
    return "\n".join(part.get("text", "") for part in message.get("content") or []
                     if isinstance(part, dict))


ARRAY = re.compile(r"\[\s*\d{1,2}(?:\s*,\s*\d{1,2})*\s*\]")  # one element or more
# a board tool run as a command (Legion's legion-tool CLI, not a path that ends in it), not a file
# or word that merely names the board
BOARD_CALL = re.compile(r"(?<![\w./-])legion-tool\s+message_board\.[a-z_]+")
STATED = (  # digits that read as a number someone holds; bare ids, counts and timestamps don't
    re.compile(r"agent-\d{3}[\"']?\s*[:=]\s*[\"']?(\d{1,2})(?![\d.:])"),  # "agent-002": 26
    re.compile(r"\bnumbers?\b(?:\s+(?:is|are|was|were)|:|=)?\s*[\"']?(\d{1,2})(?![\d.:])",
               re.IGNORECASE),  # number is 26
)


def given_away(text: str, team: dict[str, str]) -> set[int]:
    """The team's numbers that `text` holds: as words ("twenty-six"), or as digits where they
    read as a held number: an array of the team's integers (a whole or partial answer, e.g.
    `[15, 26, 37]`), an agent's number in a mapping or a line (`"agent-002": 26`), or a number
    stated as one (`number is 26`, `numbers: 15`)."""
    values = Counter(read_words(w) for w in team.values())
    out = {read_words(w) for w in holds(text, set(team.values()))}
    for array in ARRAY.findall(text):
        numbers = Counter(int(x) for x in re.findall(r"\d+", array))
        if not numbers - values:  # all of them the team's
            out |= set(numbers)
    for pattern in STATED:
        out |= {int(x) for x in pattern.findall(text)} & set(values)
    return out


def audit_run(run: Path) -> tuple[list[str], dict]:
    """(problems, report) for a Legion run of one team (a local run's `.legion/<swarm>-<time>/`):
    no prompt Legion gave an agent holds a teammate's number, and its first prompt holds its own;
    the first output in which an agent sees a teammate's number is a board read (or a wake-up
    that quotes the board), and the first post holding each number is its owner's. A number
    counts as words or as digits (given_away)."""
    problems = []
    spec = json.loads((run / "run.json").read_text())["spec"]
    harbor = next(t["harbor"] for t in spec["types"].values() if t.get("harbor"))
    selector = harbor["config"]["task"]["selector"]  # agent K on slot K
    task = selector[0] if isinstance(selector, list) else selector
    team = held(task)
    numbers = {agent: read_words(word) for agent, word in team.items()}
    boards = sorted(run.rglob("resources/message_board/board.jsonl"))
    if len(boards) != 1:
        problems.append(f"run {run.name}: {len(boards)} board exports")
    posts = sorted((json.loads(x)["message"] for b in boards[:1]
                    for x in b.read_text().splitlines() if x.strip()),
                   key=lambda m: m["created_at"])
    first = {}
    for post in posts:
        for number in given_away(post["body"], team):
            first.setdefault(number, post["sender"]["external_id"])
    for number, who in first.items():
        if numbers.get(who) != number:
            problems.append(f"run {run.name}: {number} was first posted by {who}")
    report = {"task": task, "posts": len(posts), "first_posts": first}
    for agent, own in team.items():
        path = run / "agents" / "_sessions" / f"{agent}.jsonl"
        if not path.is_file():
            problems.append(f"run {run.name}: no event stream for {agent}")
            continue
        others = set(numbers.values()) - {numbers[agent]}
        seen, calls, prompts, got_own, board_reads = set(), {}, 0, False, 0
        for line in path.read_text().splitlines():
            event = json.loads(line) if line.strip() else {}
            message = event.get("message") or {}
            if event.get("type") != "message":
                continue
            role, text = message.get("role"), texts(message)
            if role == "assistant":
                for part in message.get("content") or []:
                    if isinstance(part, dict) and part.get("type") == "toolCall":
                        arguments = part.get("arguments") or {}
                        calls[part.get("id")] = str(arguments.get("command") or json.dumps(
                            arguments))
            elif role in ("system", "user"):
                if role == "system" or prompts == 0:  # what Legion and the task tell the agent
                    if given := given_away(text, team) & others:
                        problems.append(f"run {agent}: its {role} prompt holds {sorted(given)}")
                    got_own |= role == "user" and own in holds(text, {own})
                else:  # a later prompt may quote the board (a wake-up on a mention)
                    seen |= given_away(text, team) & others
                prompts += role == "user"
            elif role == "toolResult":
                command = calls.get(message.get("toolCallId"), "")
                board_read = bool(BOARD_CALL.search(command))
                board_reads += board_read
                new = given_away(text, team) & others - seen
                if new and not board_read:
                    problems.append(f"run {agent}: first saw {sorted(new)} in the output of "
                                    f"{command[:120]}")
                seen |= new
        if not got_own:
            problems.append(f"run {agent}: its first prompt doesn't hold its own number")
        report[agent] = {"saw": len(seen), "got_own": got_own, "board_reads": board_reads}
    return problems, report


def check_run(run: Path) -> dict:
    problems, report = audit_run(run)
    failures.extend(problems)
    return report


AUDIT_TEAM = "agg-p01-n04"


def synthetic_run(root: Path, prompt: str = "", output: str = "",
                  poster: dict | None = None, command: str = "cat /tmp/notes.json") -> Path:
    """A local run directory of AUDIT_TEAM as Legion leaves it, whose agents behave: each posts
    its number and reads the board. `prompt` joins agent-001's first prompt, `output` is
    the output of a non-board `command` it runs before it reads the board, and `poster` posts a number
    in another agent's name first (agent -> number). Each agent's first prompt is its own slot's
    instruction."""
    team = held(AUDIT_TEAM)
    run = root / f"run-{len(list(root.iterdir()))}"
    (run / "agents" / "_sessions").mkdir(parents=True)
    (run / "run.json").write_text(json.dumps({"spec": {"types": {"agent": {"harbor": {
        "config": {"task": {"selector": [f"{AUDIT_TEAM}-s01", f"{AUDIT_TEAM}-s02"]}}}}}}}))
    board = run / "agents" / "_harbor" / "_worker" / "resources" / "message_board"
    board.mkdir(parents=True)
    lines = [f"{who}: my number is {g.words(number)} ({number})"
             for who, number in (poster or {}).items()]
    lines += [f"{agent}: my number is {word} ({read_words(word)})" for agent, word in team.items()]
    senders = [*(poster or {}), *team]
    board_lines = [json.dumps({"channel_id": 1, "message": {
        "seq": k, "created_at": 1000.0 + k, "body": body, "sender": {"external_id": who}}})
        for k, (who, body) in enumerate(zip(senders, lines, strict=True), 1)]
    (board / "board.jsonl").write_text("\n".join(board_lines) + "\n")

    def message(role, content, **extra):
        return json.dumps({"type": "message", "message": {"role": role, "content": content,
                                                          **extra}})

    def call(k, command):
        return message("assistant", [{"type": "toolCall", "id": f"c{k}",
                                      "arguments": {"command": command}}])

    def result(k, text):
        return message("toolResult", [{"type": "text", "text": text}], toolCallId=f"c{k}")

    for agent in team:
        own = HERE / "tasks" / f"{AUDIT_TEAM}-s{agent[-2:]}" / "instruction.md"
        events = [message("system", [{"type": "text", "text": "You are Pi."}]),
                  message("user", [{"type": "text", "text": own.read_text() + (
                      prompt if agent == "agent-001" else "")}])]
        if agent == "agent-001" and output:
            events += [call(2, command), result(2, output)]
        events += [call(3, "legion-tool message_board.read --json '{}'"),
                   result(3, json.dumps({"messages": lines}))]
        (run / "agents" / "_sessions" / f"{agent}.jsonl").write_text("\n".join(events) + "\n")
    return run


def check_audit() -> int:
    """audit_run on synthetic runs: a clean one passes, ids and timestamps that happen to be
    the team's numbers pass, and each leak fails: words, the JSON answer, a one-element array, a
    mapping and a stated number, in the first prompt or a non-board output before the board
    (a file named after the board is not the board); and a number first posted by an agent that
    doesn't hold it. Returns the cases checked."""
    team = held(AUDIT_TEAM)
    numbers = [read_words(w) for w in team.values()]  # agent-001's first
    answer = json.dumps(sorted(numbers))
    mapping = json.dumps({a: read_words(w) for a, w in team.items()})
    noise = json.dumps({"id": numbers[1], "seq": numbers[2], "count": numbers[3],
                        "created_at": f"2026-11-16T{numbers[2]:02d}:{numbers[3]:02d}:00Z"})
    cases = {
        "clean": ({}, False),
        "ids, counts and a timestamp that hold the numbers": ({"output": noise}, False),
        "a teammate's number in words in the first prompt": (
            {"prompt": f"\nagent-002 holds {team['agent-002']}."}, True),
        "the JSON answer in the first prompt": ({"prompt": f"\nThe answer is {answer}."}, True),
        "the JSON answer in a non-board output": ({"output": answer}, True),
        "a mapping of agents to numbers in a non-board output": ({"output": mapping}, True),
        "a teammate's number stated in digits in a non-board output": (
            {"output": f"agent-003's number is {numbers[2]}"}, True),
        "a stated number from a file whose name mentions the board": (
            {"output": f"agent-002's number is {numbers[1]}",
             "command": "cat /tmp/message_board.txt"}, True),
        "a teammate's number as a one-element array in the first prompt": (
            {"prompt": f"\nagent-002: [{numbers[1]}]"}, True),
        "a teammate's number as a one-element array in a non-board output": (
            {"output": f"[{numbers[1]}]"}, True),
        "a number first posted by an agent that doesn't hold it": (
            {"poster": {"agent-001": numbers[1]}}, True),
    }
    with tempfile.TemporaryDirectory() as d:
        for case, (kwargs, leaks) in cases.items():
            problems, _ = audit_run(synthetic_run(Path(d), **kwargs))
            check(bool(problems) == leaks, f"audit: {case}: {problems or 'no problem found'}")
    return len(cases)


# ------------------------------------------------------------------ metrics

# The lines of Legion's experiments/s3-aggregation/spec.yaml that eval/metrics.py reads
RUN_SPEC = """name: ${TEAM:-agg-p01-n04}
naming: consecutive-id
task:
  repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation
  selector: ${TEAM:-agg-p01-n04}-s*
  revision: REVISION
agents:
  count: ${N:-4}
"""


def metrics_module():
    import importlib.util

    spec = importlib.util.spec_from_file_location("_s3_metrics", HERE / "eval" / "metrics.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def slurm_dir(root: Path, team: str, agents: list[str], env_files: dict[str, str]) -> Path:
    """A Slurm run's directory as `legion init` and the workers leave it: the spec, the env files
    and, per agent in `agents`, one Trial of its own slot of `team`, graded by the task's own
    grader (agent-001 answers right, the others wrong)."""
    (root / "experiment").mkdir(parents=True)
    (root / "experiment" / "spec.yaml").write_text(RUN_SPEC)
    for name, text in env_files.items():
        (root / name).write_text(text)
    for k, agent in enumerate(agents, 1):
        task = HERE / "tasks" / f"{team}-s{int(agent[-3:]):02d}"
        right = json.loads((task / "tests" / "expected.json").read_text())
        reward = grade(task, json.dumps(right if k == 1 else [0]).encode())
        trial = root / "results" / "s3" / agent / "trials" / f"s3-{agent}-t1"
        (trial / "verifier").mkdir(parents=True)
        (trial / "verifier" / "reward.txt").write_text(str(reward))
        (trial / "result.json").write_text(json.dumps({
            "task_name": f"HuggingFaceSwarms/{task.name}", "trial_name": trial.name,
            "started_at": f"2026-11-17T11:38:1{k % 10}+00:00",
            "finished_at": "2026-11-17T11:50:04+00:00",
            "agent_result": {"n_input_tokens": 1000, "n_cache_tokens": 0, "n_output_tokens": 50},
            "verifier_result": {"rewards": {"reward": float(reward)}}}))
    return root


def check_metrics() -> int:
    """eval/metrics.py on Slurm run directories: the spec as the run resolved it (`cluster.env`
    then `run.env`, else the defaults) gives the task and the roster; a planned agent without
    results, Trials of an unplanned agent and Trials of another task are flagged, never dropped.
    Returns the cases checked."""
    metrics = metrics_module()
    four = [f"agent-{k:03d}" for k in range(1, 5)]
    cases = {  # name: (team the Trials ran, agents with Trials, env files, task, agents, missing)
        "defaults": ("agg-p01-n04", four, {}, "agg-p01-n04", 4, []),
        "run.env": ("agg-p02-n02", four[:2],
                    {"cluster.env": "N=3\nTEAM=agg-p05-n04\n",
                     "run.env": "#TEAM=agg-p01-n04\nTEAM=agg-p02-n02\nN=2\n"},
                    "agg-p02-n02", 2, []),
        "an agent's results gone": ("agg-p01-n04", four[:3], {}, "agg-p01-n04", 4,
                                    ["reward: agent-004"]),
        "run.env gone": ("agg-p02-n02", four[:2], {}, "agg-p01-n04", 4,
                         [("task: the spec selects 'agg-p01-n04-s*', the Trials ran "
                           "agg-p02-n02-s01, agg-p02-n02-s02"), "reward: agent-003",
                          "reward: agent-004"]),
        "an unplanned agent": ("agg-p01-n04", four[:3], {"run.env": "N=2\n"}, "agg-p01-n04", 2,
                               ["agents: Trials of agents the spec didn't plan: agent-003"]),
        # inline comments, as Legion's read_env_file reads them: after a quoted value's closing
        # quote, and after whitespace in an unquoted one
        "quoted values with comments": ("agg-p03-n04", four[:3],
                                        {"run.env": 'TEAM="agg-p03-n04" # group\nN="4" # size\n'},
                                        "agg-p03-n04", 4, ["reward: agent-004"]),
        "unquoted values with comments": ("agg-p02-n02", four[:2],
                                          {"cluster.env": "N=3 # size\n",
                                           "run.env": "export TEAM=agg-p02-n02  # group\n"
                                                      "N=2\t# size\n"},
                                          "agg-p02-n02", 2, []),
    }
    with tempfile.TemporaryDirectory() as d:
        for case, (team, agents, env_files, task, count, missing) in cases.items():
            root = Path(d) / ("run-" + re.sub(r"\W+", "-", case))
            r = metrics.row(slurm_dir(root, team, agents, env_files))
            check(r["task"] == task and r["agents"] == count and len(r["rewards"]) == count,
                  f"metrics, {case}: task {r['task']!r}, {r['agents']} agents, not {task!r}, "
                  f"{count}")
            check(sorted(r["missing"]) == sorted([*missing, "board export"]),
                  f"metrics, {case}: missing {r['missing']}")
            expected = {a: 1.0 if a == "agent-001" else 0.0 for a in agents if a in r["rewards"]}
            check({a: v for a, v in r["rewards"].items() if v is not None} == expected
                  and r["success"] is True, f"metrics, {case}: rewards {r['rewards']}")
    return len(cases)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--env", default="hf-sandbox",
                        help="Harbor environment type or import path for the Trials; none: skip")
    parser.add_argument("--jobs-dir", type=Path, default=None,
                        help="keep the Trials' files here (default: a temporary directory)")
    parser.add_argument("--run", type=Path, action="append", default=[],
                        help="also check a Legion run of a team (a local run's directory)")
    args = parser.parse_args()
    check_generator()
    print(f"1. generator: {len(failures)} failures")
    before = len(failures)
    covered = check_graders()
    print(f"2. graders: {len(failures) - before} failures; zero-score cases checked: {covered}")
    before = len(failures)
    check_files()
    print(f"3. no-cheat (files): {len(failures) - before} failures")
    if args.env != "none":
        before = len(failures)
        with tempfile.TemporaryDirectory() as d:
            jobs = args.jobs_dir or Path(d)
            jobs.mkdir(parents=True, exist_ok=True)
            report = asyncio.run(check_trials(args.env, jobs))
        print(f"4. no-cheat (Trials on {args.env}, {PROBE_TEAM}): {len(failures) - before} "
              f"failures; {json.dumps(report)}")
    before = len(failures)
    cases = check_audit()
    print(f"5. no-cheat (the Legion-run audit on {cases} synthetic runs): "
          f"{len(failures) - before} failures")
    before = len(failures)
    cases = check_metrics()
    print(f"6. metrics (eval/metrics.py on {cases} Slurm run directories): "
          f"{len(failures) - before} failures")
    for run in args.run:
        before = len(failures)
        report = check_run(run)
        print(f"5. no-cheat (Legion run {run.name}): {len(failures) - before} failures; "
              f"{json.dumps(report)}")
    for failure in failures:
        print("FAIL:", failure)
    print("all checks passed" if not failures else f"{len(failures)} checks failed")
    return 1 if failures else 0


if __name__ == "__main__":
    sys.exit(main())