Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 54,960 Bytes
161a2d3
 
a43f73c
161a2d3
3421ea2
161a2d3
 
 
 
 
 
a43f73c
 
 
 
 
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
3421ea2
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
 
 
3421ea2
3b6c363
a43f73c
a97bebd
 
a43f73c
3421ea2
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
161a2d3
a43f73c
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
 
 
 
 
 
 
 
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3421ea2
161a2d3
 
 
 
 
 
a43f73c
 
3421ea2
a43f73c
 
 
 
 
 
 
 
 
 
 
 
 
3421ea2
a43f73c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3421ea2
3b6c363
 
 
 
 
 
a43f73c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a97bebd
 
 
 
 
 
 
 
 
 
a43f73c
 
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
 
 
161a2d3
 
 
 
 
a43f73c
161a2d3
 
 
 
 
 
 
 
 
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
# /// script
# requires-python = ">=3.12"
# dependencies = ["harbor==0.25.0", "pyyaml"]
# ///
"""s3-maze's checks that need no model (huggingface/legion#115, section 5):

    uv run check.py --env podman    # all of them; the Trials in rootless podman (README: "Checks")
    uv run check.py --env docker    # the Trials in local docker
    uv run check.py --env none      # without the Trials (no container engine needed)

1. Generator: generate.py reproduces tasks/ byte for byte from its seed, and another seed gives
   other trees, which record that seed in their task.toml and regenerate from it. Each of the
   32 trees has 391 rooms with distinct labels of one fixed length, is a tree (390 two-way
   doors, every room reachable from the start), has 27 dead ends, all 30 moves from the start,
   one of which is the exit; the shortest path is 30 moves and a full depth-first search
   through the service's engine 780. Door orders are shuffled (the way back
   is not always listed in the same place), and the exits fall on many positions of the search
   order. Every task's service, agent and grader files are template/'s, its image tags are its
   files' digests, and the budget is the same in the tree, the grader, the instruction and
   task.toml.
2. The maze service, run as it runs in its container (service.py over HTTP on this machine):
   it starts in the start room with the whole budget; a move into a room that isn't one of the
   current room's doors is refused (the exit from the start, a room two doors away, the room
   itself, a number, an object, a long string, a malformed body) and costs nothing; once the
   budget is spent every move is refused, a door included; at the exit every move is refused.
   No route reveals the tree or the exit: every other path and method answers a bare 404, and
   no answer names a room other than the current one and its doors (or what the agent asked
   for); the exit is named only once the agent stands in it. The move log has one record per
   move request, refused ones included, each with agent, from, to and time, and its accepted
   moves are the walk. success.py (legion's success_check) says false until the exit is reached
   and true after, and false for a missing or linked state file; export.py writes the service's
   record for the grader; a restarted service resumes the walk. The `maze` command prints the
   service's JSON and exits 0, 1 for a refused move, 2 for a usage error.
3. Graders, as Harbor runs them (tests/test.sh on the evidence export.py wrote), on every tree:
   the oracle (solution/solve.sh, walking the shortest path through the `maze` command) scores
   1, and a walk that never reaches the exit scores 0. On one tree, more walks and forgeries
   score 0: the budget spent without the exit, no move at all, a forged final.json (the exit
   claimed but not in the log, no `exported_by`, another tree's hash, another start, another
   budget, the move count changed), a forged log (a jump between rooms that aren't adjacent in
   the walk, the exit reached in more moves than the budget), another tree's winning evidence,
   evidence as a symlink or a hardlink to a winning copy, a symlinked /evidence, a directory, a
   FIFO (which must not hang the grader), a missing file, invalid JSON and NaN; and a losing
   walk with Python made to read any record as a win: 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; and a reward.txt or reward.json left as 1, or as a link, in the verifier's
   folder.
4. No-cheat, in the files: the agent's build context (environment/agent/) holds only its
   Dockerfile and the `maze` command, and names no room; nor do the instruction, task.toml or
   the compose file; the exit is named only in environment/maze/tree.json, tests/expected.json
   and solution/solve.sh; and no folder beside tasks/ holds a tree.
5. Metrics (eval/metrics.py) on Slurm run directories made of real exports and grades, with
   the example spec's `${TREE:-maze-t01}` and `${N:-4}`: with no env files the row's task is
   maze-t01 and its team four agents; `run.env` (over `cluster.env`) sets another tree and team
   size, also with comments after quoted and unquoted values (read as legion reads them); a team
   with one agent's results gone keeps that agent and flags its reward and move
   log as missing; and the row flags Trials of another task than the spec selects (a `run.env`
   gone) and of an agent the spec didn't plan, and a winning move log whose last line was cut
   off.
6. Trials (`--env`), on maze-t01, with agents that need no model:
   - a walker checks legion's success_check in the maze service (false), walks the shortest path
     with `maze move`, checks it again (true), and scores 1; the verifier's folder then holds
     the move log and the export;
   - Harbor's oracle agent (solution/solve.sh) scores 1;
   - a probe looks around the agent's container while it works: no file, process environment
     or command line names any room but the start and its doors, nor the tree's hash; the maze
     service answers only its two routes; there is no tests/ or solution/. Then it plants a
     winning record (from a local walk of this tree) in /evidence, /logs/artifacts and
     /logs/verifier, a reward.txt of 1, a json.py and a sitecustomize, makes three moves
     short of the exit, and scores 0.
   `--env` takes a Harbor environment type (podman, docker) or an import path.
"""

import argparse
import asyncio
import base64
import hashlib
import json
import os
import re
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.dont_write_bytecode = True  # nothing new in tasks/ or template/
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE / "template" / "environment" / "maze"))
sys.path.insert(0, str(HERE / "eval"))
import generate as g  # noqa: E402
import metrics  # noqa: E402
from engine import Maze, Walk  # noqa: E402

LABEL = re.compile(rf"R\d{{{g.DIGITS}}}")
PROBE_TASK = "maze-t01"
failures: list[str] = []


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


def tasks() -> list[Path]:
    return sorted((HERE / "tasks").iterdir())


def tree_of(task: Path) -> dict:
    return json.loads((task / "environment" / "maze" / "tree.json").read_text())


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)."""
    return {str(p.relative_to(root)): p.read_bytes()
            for p in sorted((root / "tasks").rglob("*"))
            if p.is_file() and "__pycache__" not in p.parts}


def distances(t: dict) -> dict[str, int]:
    out, queue = {t["start"]: 0}, [t["start"]]
    for room in queue:
        for door in t["doors"][room]:
            if door not in out:
                out[door] = out[room] + 1
                queue.append(door)
    return out


def full_search(t: dict) -> int:
    """Moves for a depth-first search of the whole tree through the engine, back to the start."""
    walk = Walk(Maze({**t, "exit": None, "budget": 10 ** 6}))
    seen, path = {walk.room}, [walk.room]
    while True:
        unexplored = [d for d in walk.look()["doors"] if d not in seen]
        if unexplored:
            target = unexplored[0]
            path.append(target)
        elif len(path) > 1:
            path.pop()
            target = path[-1]
        else:
            return walk.moves
        _, why = walk.move(target)
        check(why is None, f"the engine refused a search move ({why})")
        seen.add(target)


def check_generator() -> None:
    with tempfile.TemporaryDirectory() as d:
        shutil.copytree(HERE / "template", Path(d) / "template")
        g.generate(Path(d))
        check(files(Path(d)) == files(HERE), "generate.py does not reproduce the committed tasks/")
        other = g.SEED + 1  # the seed a task records regenerates its tree
        g.generate(Path(d), seed=other)
        for t, tree in enumerate(g.trees(other), 1):
            task = Path(d) / "tasks" / g.task_name(t)
            recorded = re.findall(r"^seed = (\d+)$", (task / "task.toml").read_text(), re.M)
            check(recorded == [str(other)] and tree_of(task) == tree
                  and g.trees(int(recorded[0]))[t - 1] == tree,
                  f"seed {other}: {task.name} records seed {recorded}, not its own")
    drawn = g.trees()
    check(drawn == g.trees(), "the same seed gave other trees")
    check(all(a["doors"] != b["doors"] for a, b in zip(drawn, g.trees(g.SEED + 1), strict=True)),
          "another seed gave the same trees")
    check([p.name for p in tasks()] == [g.task_name(t) for t in range(1, 33)],
          "tasks/ is not maze-t01 .. maze-t32")
    template = {f: g.template(f) for f in ("environment/agent", "environment/maze", "tests")}
    exit_ranks, back_positions = set(), set()
    for t, task in enumerate(tasks(), 1):
        tree = tree_of(task)
        name = task.name
        check(tree == drawn[t - 1] | {"budget": g.BUDGET}, f"{name}: tree.json is not generate's")
        doors = tree["doors"]
        rooms = list(doors)
        check(len(rooms) == 391 and len(set(rooms)) == 391, f"{name}: not 391 distinct rooms")
        check(all(LABEL.fullmatch(r) for r in rooms), f"{name}: a label isn't R and digits")
        pairs = {(a, b) for a in rooms for b in doors[a]}
        check(len(pairs) == 2 * 390 and all((b, a) in pairs for a, b in pairs)
              and all(len(set(doors[r])) == len(doors[r]) for r in rooms),
              f"{name}: not 390 two-way doors")
        dist = distances(tree)
        check(len(dist) == 391, f"{name}: not every room is reachable from the start")
        ends = [r for r in rooms if len(doors[r]) == 1 and r != tree["start"]]
        check(len(ends) == 27 and all(dist[r] == 30 for r in ends),
              f"{name}: not 27 dead ends 30 moves from the start")
        check(tree["exit"] in ends, f"{name}: the exit is not a dead end")
        check(len(g.shortest_path(tree)) == 30 == dist[tree["exit"]],
              f"{name}: the shortest path is not 30 moves")
        check(full_search(tree) == 780, f"{name}: a full search is not 780 moves")
        order, stack, seen = [], [tree["start"]], {tree["start"]}
        while stack:  # the dead ends in listed depth-first order, and where the way back is
            room = stack.pop()
            if room in ends:
                order.append(room)
            onward = [d for d in doors[room] if d not in seen]
            for door in onward:
                seen.add(door)
                back_positions.add((len(doors[door]), doors[door].index(room)))
            stack += onward[::-1]
        exit_ranks.add(order.index(tree["exit"]))
        for folder, expected in template.items():
            have = {str(p.relative_to(task / folder)): p.read_bytes()
                    for p in sorted((task / folder).rglob("*")) if p.is_file()}
            extra = {"environment/maze": {"tree.json"}, "tests": {"expected.json"}}.get(
                folder, set())
            check({k: v for k, v in have.items() if k not in extra} == expected,
                  f"{name}: {folder} is not template/'s")
            check(set(have) - set(expected) == extra, f"{name}: {folder} holds {set(have)}")
        compose = (task / "environment" / "docker-compose.yaml").read_text()
        maze = g.template("environment/maze") | {
            "tree.json": (task / "environment" / "maze" / "tree.json").read_bytes()}
        check(f"s3-maze-agent:{g.digest(template['environment/agent'])}" in compose
              and f"s3-maze-service:{name}-{g.digest(maze)}" in compose,
              f"{name}: an image tag is not its files' digest")
        expected = json.loads((task / "tests" / "expected.json").read_text())
        check(expected == {"start": tree["start"], "exit": tree["exit"], "budget": g.BUDGET,
                           "tree_sha256": hashlib.sha256(maze["tree.json"]).hexdigest()},
              f"{name}: expected.json does not match the tree")
        check(f"at most {g.BUDGET} moves" in (task / "instruction.md").read_text()
              and f"move_budget = {g.BUDGET}\n" in (task / "task.toml").read_text()
              and tree["budget"] == g.BUDGET, f"{name}: the budget differs between its files")
    check({(4, k) for k in range(4)} | {(2, 0), (2, 1)} <= back_positions,
          "the way back is not listed in every place a junction or corridor room has")
    check(len(exit_ranks) >= 10, f"the exits fall on only {len(exit_ranks)} search positions")


# ------------------------------------------------------------------ the service, as it runs


def free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


class Service:
    """service.py of a task, on this machine, with its state in `state` (a fresh one each)."""

    def __init__(self, task: Path, state: Path, tree: dict | None = None):
        self.task, self.state = task, state
        maze_dir = task / "environment" / "maze"
        self.tree_path = maze_dir / "tree.json"
        if tree is not None:  # e.g. a smaller budget
            self.tree_path = state.parent / f"{state.name}-tree.json"
            self.tree_path.write_text(json.dumps(tree))
        self.port = free_port()
        self.url = f"http://127.0.0.1:{self.port}"
        self.env = {**os.environ, "MAZE_TREE": str(self.tree_path), "MAZE_STATE_DIR": str(state),
                    "MAZE_PORT": str(self.port), "MAZE_AGENT": "check-maze-t01-agent-001-t1__env"}
        self.process = None
        self.answers: list[tuple[str, int, str]] = []  # (what was asked, status, body)

    def __enter__(self):
        self.start()
        return self

    def start(self):
        script = self.task / "environment" / "maze" / "service.py"
        self.process = subprocess.Popen([sys.executable, "-I", "-S", str(script)], env=self.env,
                                        stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        deadline = time.monotonic() + 15
        while time.monotonic() < deadline:
            try:
                with socket.create_connection(("127.0.0.1", self.port), timeout=1):
                    return
            except OSError:
                time.sleep(0.1)
        raise RuntimeError(f"the service did not start: {self.process.stderr.read()[-500:]}")

    def stop(self):
        self.process.terminate()
        self.process.wait(10)

    def __exit__(self, *exc):
        self.stop()

    def request(self, method: str, path: str, body: bytes | None = None) -> tuple[int, dict]:
        request = urllib.request.Request(self.url + path, data=body, method=method,
                                         headers={"Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(request, timeout=10) as response:
                status, text = response.status, response.read().decode()
        except urllib.error.HTTPError as e:
            status, text = e.code, e.read().decode()
        self.answers.append((f"{method} {path} {body!r}", status, text))
        try:
            return status, json.loads(text) if text else {}
        except ValueError:
            return status, {"raw": text}

    def look(self) -> dict:
        return self.request("GET", "/look")[1]

    def move(self, room) -> tuple[int, dict]:
        return self.request("POST", "/move", json.dumps({"room": room}).encode())

    def export(self, evidence: Path) -> None:
        env = {**self.env, "MAZE_EVIDENCE_DIR": str(evidence)}
        subprocess.run([sys.executable, "-I", "-S",
                        str(self.task / "environment" / "maze" / "export.py")],
                       env=env, check=True, capture_output=True, timeout=30)

    def success(self) -> dict:
        out = subprocess.run([sys.executable, "-I", "-S",
                              str(self.task / "environment" / "maze" / "success.py")],
                             env=self.env, check=True, capture_output=True, text=True, timeout=30)
        return json.loads(out.stdout)

    def log(self) -> list[dict]:
        path = self.state / "moves.jsonl"
        return [json.loads(x) for x in path.read_text().splitlines()] if path.exists() else []


def visible(answer: str, tree: dict) -> set[str]:
    return set(LABEL.findall(answer)) & set(tree["doors"])


def walk_to(service: Service, rooms: list[str]) -> None:
    for room in rooms:
        status, _ = service.move(room)
        check(status == 200, f"a move along the path was refused ({room})")


def dead_end_walk(tree: dict, moves: int) -> list[str]:
    """A walk of `moves` moves that never reaches the exit: into a branch that doesn't hold it,
    back and forth along its corridor."""
    on_path = set(g.shortest_path(tree))
    first = next(d for d in tree["doors"][tree["start"]] if d not in on_path)
    walk = []
    while len(walk) < moves:
        walk += [first, tree["start"]]
    return walk[:moves]


def check_service(work: Path) -> dict:
    task = HERE / "tasks" / PROBE_TASK
    tree = tree_of(task)
    doors, start, exit_room = tree["doors"], tree["start"], tree["exit"]
    path = g.shortest_path(tree)
    report = {}
    with Service(task, work / "state-a") as s:
        here = s.look()
        check(here == {"room": start, "doors": doors[start], "exit": False, "arrived_from": None,
                       "moves_left": g.BUDGET}, f"the start's observation is wrong: {here}")
        check(s.success()["success"] is False, "success_check is true before any move")
        two_away = next(r for r, d in distances(tree).items() if d == 2)
        refused = {"the exit": exit_room, "a room two doors away": two_away, "itself": start,
                   "a number": 5, "an object": {"room": doors[start][0]},
                   "a long string": "R" * 1000, "a list": [doors[start][0]]}
        for case, room in refused.items():
            status, body = s.move(room)
            check(status == 409 and "error" in body and body.get("room") == start,
                  f"a move into {case} was not refused ({status})")
        too_long = json.dumps({"room": "R" * 5000}).encode()
        for case, raw in {"no body": b"", "not JSON": b"{", "no room": b'{"to": "R1"}',
                          "a list": b"[]", "a body over 4 KiB": too_long}.items():
            status, _ = s.request("POST", "/move", raw or None)
            check(status == 400, f"a malformed move ({case}) was not refused ({status})")
        check(s.look()["moves_left"] == g.BUDGET, "a refused move cost a move")
        # every other route answers a bare 404
        for method in ("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"):
            for p in ("/", "/tree", "/state", "/exit", "/doors", "/map", "/private/tree.json",
                      "/look/", "/look?room=" + exit_room, "/move/" + exit_room, "/health",
                      "/../private/tree.json", "/%2e%2e/private/tree.json", "/moves.jsonl"):
                if (method, p) in (("GET", "/look"), ("POST", "/move")):
                    continue
                status, body = s.request(method, p, b"{}" if method in ("POST", "PUT") else None)
                check(status in (404, 501) and not visible(json.dumps(body), tree),
                      f"{method} {p} answered {status} {body}")
        # walk the path; every answer names only the current room and its doors
        walk_to(s, path[:-1])
        check(s.success()["success"] is False, "success_check is true before the exit")
        walk_to(s, path[-1:])
        here = s.look()
        check(here["exit"] is True and here["room"] == exit_room
              and here["moves_left"] == g.BUDGET - 30, f"the exit's observation is wrong: {here}")
        status, body = s.move(here["doors"][0])
        check(status == 409, "a move out of the exit was accepted")
        verdict = s.success()
        check(verdict["success"] is True and verdict["evidence"]["exit_reached"] is True,
              f"success_check is not true at the exit: {verdict}")
        log = s.log()
        requests = sum(1 for asked, _, _ in s.answers if asked.startswith("POST /move "))
        check(len(log) == requests, f"the move log has {len(log)} records for {requests} requests")
        check(all({"agent", "from", "to", "time", "ok"} <= set(r) for r in log)
              and all(r["agent"] == "check-maze-t01-agent-001-t1" for r in log),
              "a move record lacks agent, from, to or time")
        ok = [r for r in log if r["ok"]]
        check([r["to"] for r in ok] == path and [r["from"] for r in ok] == [start] + path[:-1],
              "the log's accepted moves are not the walk")
        # what the service said, at every step: only the room and its doors, or what was asked
        room_then = start
        for asked, status, text in s.answers:
            named = visible(text, tree) - set(LABEL.findall(asked))
            allowed = {room_then, *doors[room_then]}
            if status == 200 and asked.startswith("POST /move"):
                room_then = json.loads(text)["room"]
                allowed |= {room_then, *doors[room_then]}
            check(named <= allowed, f"{asked} named {sorted(named - allowed)}")
            said_exit = '"exit": true' in text
            check(said_exit == (room_then == exit_room and status in (200, 409)),
                  f"{asked}: the service said exit: {said_exit} in {room_then}")
        s.export(work / "evidence-a")
        final = json.loads((work / "evidence-a" / "final.json").read_text())
        check(final["reached"] is True and final["exported_by"] == "maze" and final["moves"] == 30,
              f"the export is wrong: {final}")
        report["requests"] = requests
        # a restart resumes the walk
        s.stop()
        s.start()
        check(s.look()["room"] == exit_room, "a restarted service lost the walk")
    # the budget: a tree with a budget of 4
    with Service(task, work / "state-b", tree | {"budget": 4}) as s:
        walk_to(s, dead_end_walk(tree, 4))
        status, body = s.move(s.look()["doors"][0])
        check(status == 409 and body["moves_left"] == 0 and "No moves left" in body["error"],
              "a move past the budget was not refused")
        check(s.log()[-1]["refused"] == "no_moves_left", "the refused move past the budget "
              "is not logged as such")
    # success_check never counts a missing or linked state
    with tempfile.TemporaryDirectory() as d:
        env = {**os.environ, "MAZE_STATE_DIR": d}
        script = str(task / "environment" / "maze" / "success.py")
        out = json.loads(subprocess.run([sys.executable, "-I", "-S", script], env=env, text=True,
                                        capture_output=True, check=True).stdout)
        check(out["success"] is False, "success_check is true without a state")
        (Path(d) / "state.json").symlink_to(work / "state-a" / "state.json")
        out = json.loads(subprocess.run([sys.executable, "-I", "-S", script], env=env, text=True,
                                        capture_output=True, check=True).stdout)
        check(out["success"] is False, "success_check followed a linked state file")
    # the `maze` command
    with Service(task, work / "state-c") as s:
        cli = [sys.executable, str(task / "environment" / "agent" / "maze")]
        env = {**os.environ, "MAZE_URL": s.url}
        run = lambda *a: subprocess.run(cli + list(a), env=env, capture_output=True, text=True,  # noqa: E731
                                        timeout=60)
        out = run("look")
        check(out.returncode == 0 and json.loads(out.stdout)["room"] == start, "maze look failed")
        out = run("move", path[0])
        check(out.returncode == 0 and json.loads(out.stdout)["room"] == path[0], "maze move failed")
        out = run("move", exit_room)
        check(out.returncode == 1 and "error" in json.loads(out.stdout),
              "a refused maze move did not exit 1")
        check(run("jump").returncode == 2 and run().returncode == 2, "maze's usage is not exit 2")
    return report


# ------------------------------------------------------------------ the graders


def evidence(task: Path, work: Path, name: str, rooms: list[str], tree: dict | None = None,
             cli: bool = False) -> Path:
    """The service's export after a walk through `rooms` (with solution/solve.sh if `cli`)."""
    with Service(task, work / f"state-{name}", tree) as s:
        if cli:
            bin_dir = work / f"bin-{name}"
            bin_dir.mkdir()
            shutil.copy(task / "environment" / "agent" / "maze", bin_dir / "maze")
            (bin_dir / "maze").chmod(0o755)
            env = {**os.environ, "MAZE_URL": s.url, "PATH": f"{bin_dir}:{os.environ['PATH']}"}
            subprocess.run(["bash", str(task / "solution" / "solve.sh")], env=env, check=True,
                           capture_output=True, timeout=300)
        else:
            for room in rooms:
                s.move(room)
        s.export(work / f"evidence-{name}")
    return work / f"evidence-{name}"


def grade(task: Path, source: Path | None, cheat=None, isolated: bool = True) -> int:
    """tests/test.sh as Harbor runs it in the verifier's container: /evidence holds what was
    collected from the maze service (`source`), /tests the task's tests/. `cheat(root)` may
    change what's there first and return the grader's extra `env` and working directory."""
    with tempfile.TemporaryDirectory() as d:
        root = Path(d).resolve()
        evidence_dir, tests, verifier = root / "evidence", root / "tests", root / "verifier"
        if source is not None:
            shutil.copytree(source, evidence_dir)
        shutil.copytree(task / "tests", tests)
        verifier.mkdir()
        extra = cheat(root) if cheat else None
        extra = extra if isinstance(extra, dict) else {}
        env = {**os.environ, "EVIDENCE_DIR": str(evidence_dir), "VERIFIER_DIR": str(verifier),
               **extra.get("env", {})}
        command = ["bash", str(tests / "test.sh")]
        if not isolated:  # the control: test.sh's python3 without -I -S
            command = ["python3", str(tests / "grade.py")]
        try:
            subprocess.run(command, capture_output=True, timeout=60, env=env,
                           cwd=extra.get("cwd"), check=False)
        except subprocess.TimeoutExpired:
            return -1
        reward = verifier / "reward.txt"
        if reward.is_symlink() or not reward.is_file():
            return -2
        if (verifier / "reward.json").exists():
            return -3  # Harbor would read it first
        value = int(reward.read_text().strip())
        if value == 1 and isolated:  # the grader keeps the service's record for the metrics
            check((verifier / "moves.jsonl").read_bytes() == (evidence_dir / "moves.jsonl")
                  .read_bytes(), f"{task.name}: the verifier's moves.jsonl is not the export")
        return value


# Imported by the grader, either would score 1 whatever the evidence: it rewrites the reward
# as the grader's Python exits.
WIN_AT_EXIT = ("import atexit, os; atexit.register(lambda: open(os.path.join(os.environ["
               "'VERIFIER_DIR'], 'reward.txt'), 'w').write('1'))")
FAKE_JSON = WIN_AT_EXIT + "\nfrom _json import *\n"
PATCH_JSON = WIN_AT_EXIT + "\n"


def edited(name: str, change):
    """Change the export's `name` file: `change(text) -> text`."""
    def cheat(root):
        path = root / "evidence" / name
        path.write_text(change(path.read_text()))
    return cheat


def final_with(**fields):
    return edited("final.json", lambda t: json.dumps(json.loads(t) | fields))


def log_with(change):
    def apply(text):
        records = [json.loads(x) for x in text.splitlines()]
        return "".join(json.dumps(r) + "\n" for r in change(records))
    return edited("moves.jsonl", apply)


def replaced(win: Path, *names: str, how: str):
    """Evidence files replaced by links to (or a link to the folder of) a winning copy."""
    def cheat(root):
        target = root / "win"
        shutil.copytree(win, target)
        if how == "folder":
            shutil.rmtree(root / "evidence")
            (root / "evidence").symlink_to(target)
            return
        for name in names:
            (root / "evidence" / name).unlink()
            if how == "symlink":
                (root / "evidence" / name).symlink_to(target / name)
            else:
                os.link(target / name, root / "evidence" / name)
    return cheat


def user_site(name: str, text: str):
    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()
        Path(site).mkdir(parents=True, exist_ok=True)
        (Path(site) / name).write_text(text)
        return {"env": env}
    return cheat


def planted(name: str, text: str):
    def cheat(root):
        folder = root / "work"
        folder.mkdir(exist_ok=True)
        (folder / name).write_text(text)
        return {"cwd": folder, "env": {"PYTHONPATH": str(folder)}}
    return cheat


def left_in_verifier(name: str, link: bool = False):
    def cheat(root):
        if link:
            (root / "elsewhere").write_text("1")
            (root / "verifier" / name).symlink_to(root / "elsewhere")
        else:
            (root / "verifier" / name).write_text('{"reward": 1}' if name.endswith("json") else "1")
    return cheat


def check_graders(work: Path) -> dict:
    covered: dict[str, int] = {}
    for task in tasks():
        tree = tree_of(task)
        win = evidence(task, work, f"{task.name}-oracle", [], cli=True)
        check(grade(task, win) == 1, f"{task.name}: the oracle does not score 1")
        lose = evidence(task, work, f"{task.name}-lost", dead_end_walk(tree, 40))
        check(grade(task, lose) == 0, f"{task.name}: a walk that never reaches the exit scores")
        covered["oracle"] = covered.get("oracle", 0) + 1
        covered["never reaches the exit"] = covered.get("never reaches the exit", 0) + 1
    task, other = HERE / "tasks" / PROBE_TASK, HERE / "tasks" / "maze-t02"
    tree = tree_of(task)
    path = g.shortest_path(tree)
    win = work / f"evidence-{task.name}-oracle"
    spent = evidence(task, work, "spent", dead_end_walk(tree, g.BUDGET + 5))
    none = evidence(task, work, "none", [])
    other_win = work / f"evidence-{other.name}-oracle"
    late = evidence(task, work, "late", dead_end_walk(tree, g.BUDGET - 10) + path,
                    tree | {"budget": g.BUDGET + 100})
    cases = {
        "the budget spent without the exit": (spent, None),
        "no move at all": (none, None),
        "a forged final.json: the exit claimed": (
            spent, final_with(reached=True, room=tree["exit"])),
        "a forged final.json: no exported_by": (win, edited("final.json", lambda t: json.dumps(
            {k: v for k, v in json.loads(t).items() if k != "exported_by"}))),
        "a forged final.json: another tree's hash": (win, final_with(tree_sha256="0" * 64)),
        "a forged final.json: another start": (win, final_with(start=path[0])),
        "a forged final.json: another budget": (win, final_with(budget=g.BUDGET + 1)),
        "a forged final.json: the move count": (win, final_with(moves=29)),
        "a forged log: a jump": (win, log_with(lambda rs: rs[:3] + rs[4:])),
        "a forged log: the exit past the budget": (
            late, final_with(budget=g.BUDGET, tree_sha256=json.loads(
                (task / "tests" / "expected.json").read_text())["tree_sha256"])),
        "another tree's winning evidence": (other_win, None),
        "evidence as symlinks to a winning copy": (spent, replaced(
            win, "final.json", "moves.jsonl", how="symlink")),
        "evidence as hardlinks to a winning copy": (spent, replaced(
            win, "final.json", "moves.jsonl", how="hardlink")),
        "a symlinked /evidence": (spent, replaced(win, how="folder")),
        "a directory": (win, lambda root: (
            (root / "evidence" / "final.json").unlink(),
            (root / "evidence" / "final.json").mkdir())),
        "a FIFO": (win, lambda root: (
            (root / "evidence" / "moves.jsonl").unlink(),
            os.mkfifo(root / "evidence" / "moves.jsonl"))),
        "a missing file": (win, lambda root: (root / "evidence" / "moves.jsonl").unlink()),
        "no evidence": (None, None),
        "invalid JSON": (win, edited("final.json", lambda t: t[:-5])),
        "NaN": (win, edited("final.json", lambda t: t.replace('"moves": 30', '"moves": NaN'))),
        "a json.py in the working directory and on PYTHONPATH": (spent, planted("json.py",
                                                                              FAKE_JSON)),
        "a sitecustomize on PYTHONPATH": (spent, planted("sitecustomize.py", PATCH_JSON)),
        "a usercustomize in the user site": (spent, user_site("usercustomize.py", PATCH_JSON)),
        "a .pth file in the user site": (spent, user_site("hook.pth", WIN_AT_EXIT + "\n")),
        "a reward.txt of 1 left in the verifier": (spent, left_in_verifier("reward.txt")),
        "a reward.json of 1 left in the verifier": (spent, left_in_verifier("reward.json")),
        "a reward.txt left as a link": (spent, left_in_verifier("reward.txt", link=True)),
    }
    for case, (source, cheat) in cases.items():
        covered[case] = 1
        result = grade(task, source, cheat)
        check(result == 0, f"{task.name}: {case} scores {result}")
    # the controls: an unchanged copy of the winning export still wins, and the Python hooks
    # do win when the grader's Python isn't isolated (so it is -I -S that stops them)
    check(grade(task, win, edited("final.json", lambda t: t)) == 1, "the control lost")
    hooks = ["a json.py in the working directory and on PYTHONPATH",
             "a sitecustomize on PYTHONPATH"]
    user_site_on = subprocess.run(["python3", "-c", "import site; print(site.ENABLE_USER_SITE)"],
                                  capture_output=True, text=True).stdout.strip() == "True"
    if user_site_on:  # a venv's python3 has no user site to plant in
        hooks += ["a usercustomize in the user site", "a .pth file in the user site"]
    covered["controls without -I -S"] = len(hooks)
    for case in hooks:
        source, cheat = cases[case]
        check(grade(task, source, cheat, isolated=False) == 1,
              f"control: {case} does not win without -I -S, so the case proves nothing")
    return covered


def check_files() -> None:
    for task in tasks():
        tree = tree_of(task)
        labels = set(tree["doors"])
        agent_files = sorted(p.name for p in (task / "environment" / "agent").iterdir())
        check(agent_files == ["Dockerfile", "maze"], f"{task.name}: the agent's context holds "
                                                     f"{agent_files}")
        for path in [*(task / "environment" / "agent").iterdir(), task / "instruction.md",
                     task / "task.toml", task / "environment" / "docker-compose.yaml"]:
            named = set(LABEL.findall(path.read_text())) & labels
            check(not named, f"{task.name}: {path.relative_to(task)} names {sorted(named)[:3]}")
        holders = {str(p.relative_to(task)) for p in task.rglob("*")
                   if p.is_file() and tree["exit"] in p.read_text(errors="ignore")}
        check(holders == {"environment/maze/tree.json", "tests/expected.json",
                          "solution/solve.sh"}, f"{task.name}: the exit is named in {holders}")
    beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {
        "tasks", "template", "legion", "eval", ".cache", "__pycache__", ".git"}
    check(not beside, f"folders beside tasks/: {sorted(beside)}")
    check(not LABEL.search("".join(p.read_text(errors="ignore")
                                   for p in (HERE / "template").rglob("*") if p.is_file())),
          "template/ names a room")


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

# The example spec's lines that metrics.py reads (Legion's experiments/s3-maze/spec.yaml)
RUN_SPEC = """name: ${RUN_NAME:-s3-maze}
naming: consecutive-id
task:
  repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze
  selector: ${TREE:-maze-t01}
  revision: REVISION
agents:
  count: ${N:-4}
"""


def run_dir(root: Path, work: Path, tree: str, walks: dict[str, bool],
            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 `walks`, one Trial of `tree` (the exit reached or not) graded by the
    task's own grader on the maze service's own export."""
    task = HERE / "tasks" / tree
    layout = tree_of(task)
    (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, wins) in enumerate(walks.items()):
        rooms = g.shortest_path(layout) if wins else dead_end_walk(layout, 20)
        source = evidence(task, work, f"{root.name}-{agent}", rooms)
        trial = root / "results" / "s3-maze" / agent / "trials" / f"s3-maze-{agent}-t1"
        env = {**os.environ, "EVIDENCE_DIR": str(source), "VERIFIER_DIR": str(trial / "verifier")}
        subprocess.run(["bash", str(task / "tests" / "test.sh")], env=env, capture_output=True,
                       timeout=60, check=True)
        reward = float((trial / "verifier" / "reward.txt").read_text())
        (trial / "result.json").write_text(json.dumps({
            "task_name": f"HuggingFaceSwarms/{tree}", "trial_name": trial.name,
            "started_at": f"2026-11-17T11:38:1{k}+00:00",
            "finished_at": "2026-11-17T11:50:04+00:00",
            "agent_result": {"n_input_tokens": 1000, "n_cache_tokens": 800, "n_output_tokens": 50},
            "verifier_result": {"rewards": {"reward": reward}}}))
    return root


def check_metrics(work: Path) -> int:
    team4 = {f"agent-{k:03d}": k == 3 for k in range(1, 5)}
    cases = {  # name: (tree, walks, env files, task, agents, missing besides the board export)
        "defaults": ("maze-t01", team4, {}, "maze-t01", 4, []),
        "run.env": ("maze-t02", {"agent-001": True, "agent-002": False},
                    {"cluster.env": "N=3\nTREE=maze-t05\n",
                     "run.env": "#TREE=maze-t01\nTREE=maze-t02\nN=2\nRUN_NAME=s3-maze-b\n"},
                    "maze-t02", 2, []),
        # comments after values, read as legion's read_env_file does: a quoted value ends at
        # its quote, an unquoted one at ` #`
        "comments in env files": ("maze-t02", {"agent-001": True, "agent-002": False},
                                  {"cluster.env": "export N=3  # three\nTREE=maze-t05 # five\n",
                                   "run.env": "TREE=\"maze-t02\" # group\nN=2  # pair\n"
                                              "RUN_NAME='s3-maze-c' # name\n"},
                                  "maze-t02", 2, []),
        "an agent's results gone": ("maze-t01", {a: w for a, w in team4.items()
                                                 if a != "agent-004"}, {}, "maze-t01", 4,
                                    ["reward: agent-004", "move log: agent-004"]),
        "run.env gone": ("maze-t02", {"agent-001": True, "agent-002": False}, {}, "maze-t01", 4,
                         ["task: the spec selects 'maze-t01', the Trials ran maze-t02",
                          "reward: agent-003", "reward: agent-004", "move log: agent-003",
                          "move log: agent-004"]),
        "an unplanned agent": ("maze-t01", {"agent-001": True, "agent-002": False,
                                            "agent-003": False}, {"run.env": "N=2\n"},
                               "maze-t01", 2,
                               ["agents: Trials of agents the spec didn't plan: agent-003"]),
    }
    for case, (tree, walks, env_files, task, agents, missing) in cases.items():
        name = "run-" + re.sub(r"\W+", "-", case)
        r = metrics.row(run_dir(work / name, work, tree, walks, env_files))
        expected_rewards = {a: float(w) for a, w in walks.items() if a in r["rewards"]}
        check(r["task"] == task and r["agents"] == agents and len(r["rewards"]) == agents,
              f"metrics, {case}: task {r['task']!r}, {r['agents']} agents, not {task!r}, {agents}")
        check(sorted(r["missing"]) == sorted(missing + ["board export"]),
              f"metrics, {case}: missing {r['missing']}")
        check({a: v for a, v in r["rewards"].items() if v is not None} == expected_rewards
              and r["success"] is any(expected_rewards.values()),
              f"metrics, {case}: rewards {r['rewards']}")
        moved = {a: 30 if w else 20 for a, w in walks.items() if a in r["rewards"]}
        check({a: n for a, n in r["moves"].items() if a in moved} == moved,
              f"metrics, {case}: moves {r['moves']}")
    # a winning move log whose last line was cut off (a Trial stopped mid-write): its moves and
    # its exit are unknown, so the row flags it as missing rather than counting 29 moves
    root = run_dir(work / "run-a-cut-off-move-log", work, "maze-t01",
                   {"agent-001": True, "agent-002": False}, {"run.env": "N=2\n"})
    log = root / "results/s3-maze/agent-001/trials/s3-maze-agent-001-t1/verifier/moves.jsonl"
    log.write_text(log.read_text().rstrip("\n")[:-20])
    r = metrics.row(root)
    check(any(m.startswith("move log: agent-001 (line 30 of 30 unreadable)") for m in r["missing"]),
          f"metrics, a cut-off move log: missing {r['missing']}")
    return len(cases) + 1


# ------------------------------------------------------------------ Trials

# Runs in the agent's container as `python3 -c PROBE_PY <base64 config>`; its config travels
# encoded, so the labels it looks for are on no command line in the container.
PROBE_PY = r"""
import base64, json, os, re, sys, urllib.request, urllib.error

cfg = json.loads(base64.b64decode(sys.argv[1]))
hidden = cfg["hidden"]
label = re.compile(r"R\d{4}")


def scan(text):
    return sorted(set(label.findall(text)) & set(hidden))


def search():
    found = {}
    for top, dirs, names in os.walk("/"):
        if top == "/":
            dirs[:] = [d for d in dirs if d not in ("proc", "sys", "dev")]
        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 f:
                    text = f.read().decode("utf-8", "ignore")
            except OSError:
                continue
            hits = scan(text)
            if hits or cfg["sha"] in text:
                found[path] = hits[:3]
    return found


def http(method, path):
    request = urllib.request.Request("http://maze:8000" + path, method=method,
                                     data=b"{}" if method == "POST" else None)
    try:
        with urllib.request.urlopen(request, timeout=10) as r:
            return r.status, r.read().decode()
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()
    except Exception as e:
        return 0, str(e)


out = {"files": search(), "env": [], "cmdline": [], "processes": 0, "routes": {},
       "visible": [d for d in ("/tests", "/solution", "/private", "/evidence")
                   if os.path.exists(d)]}
for pid in os.listdir("/proc"):
    if not pid.isdigit():
        continue
    try:
        with open(f"/proc/{pid}/environ", "rb") as f:
            env = f.read().decode("utf-8", "ignore")
        with open(f"/proc/{pid}/cmdline", "rb") as f:
            cmd = f.read().decode("utf-8", "ignore").replace("\0", " ")
    except OSError:
        continue
    out["processes"] += 1
    if scan(env) or cfg["sha"] in env:
        out["env"].append(pid)
    if scan(cmd):
        out["cmdline"].append(pid)
for method, path in (("GET", "/"), ("GET", "/tree"), ("GET", "/state"), ("GET", "/exit"),
                     ("GET", "/private/tree.json"), ("POST", "/look"), ("GET", "/move"),
                     ("GET", "/health"), ("DELETE", "/move")):
    status, text = http(method, path)
    out["routes"][f"{method} {path}"] = [status, scan(text)]
status, text = http("GET", "/look")
out["look"] = json.loads(text) if status == 200 else text
print("PROBE " + json.dumps(out))
"""


try:
    from harbor.agents.base import BaseAgent

    class Probe(BaseAgent):
        """No model. `walker`: success_check in the maze service, the shortest path through
        `maze move`, success_check again. `probe`: looks around the agent's container, leaves
        forged evidence and three moves short of the exit."""

        def __init__(self, *args, mode="walker", path=(), hidden=(), sha="", forged="",
                     **kwargs):
            super().__init__(*args, **kwargs)
            self.mode, self.path, self.hidden, self.sha = mode, list(path), list(hidden), sha
            self.forged = forged

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

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

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

        async def success(self, environment) -> dict | str:
            result = await environment.service_exec("python3 -I -S /app/success.py",
                                                    service="maze", timeout_sec=30)
            line = next((x for x in (result.stdout or "").splitlines() if x.startswith("{")), "")
            try:
                return json.loads(line)
            except ValueError:
                return f"rc={result.return_code} {(result.stdout or '')[-300:]}"

        async def run(self, instruction, environment, context) -> None:
            report = {}
            if self.mode == "walker":
                report["before"] = await self.success(environment)
                moves = " && ".join(f"maze move {shlex.quote(r)} > /dev/null" for r in self.path)
                result = await environment.exec(moves + " && maze look", timeout_sec=600)
                report["walk"] = [result.return_code, (result.stdout or "")[-500:]]
                report["after"] = await self.success(environment)
            else:
                encoded = base64.b64encode(json.dumps(
                    {"hidden": self.hidden, "sha": self.sha}).encode()).decode()
                result = await environment.exec(f"python3 -c {shlex.quote(PROBE_PY)} {encoded}",
                                                timeout_sec=900)
                line = next((x for x in (result.stdout or "").splitlines()
                             if x.startswith("PROBE ")), None)
                report = json.loads(line.removeprefix("PROBE ")) if line else {
                    "error": (result.stdout or "")[-1000:]}
                report["instruction_names"] = sorted(set(LABEL.findall(instruction))
                                                     & set(self.hidden))
                result = await environment.exec(FORGE_SH.format(forged=self.forged) + " && " +
                                                 " && ".join(f"maze move {shlex.quote(r)}"
                                                             for r in self.path),
                                                 timeout_sec=300)
                report["cheat"] = [result.return_code, (result.stdout or "")[-500:]]
            (self.logs_dir / "probe.json").write_text(json.dumps(report, indent=1))
except ImportError:  # `--env none` needs no Harbor
    Probe = None

# What a cheating agent leaves for a verifier that might read its container: a winning record
# (base64 tar of final.json and moves.jsonl) where the export, Harbor's artifacts and the
# verifier's folder go, a reward of 1, and Python made to read anything as a win.
FORGE_SH = ("for d in /evidence /logs/artifacts/evidence /logs/verifier /tests; do "
            "mkdir -p $d && echo {forged} | base64 -d | tar --no-same-owner -xz -C $d; done && "
            "echo 1 > /logs/verifier/reward.txt && "
            "printf 'def loads(*a, **k):\\n    return {{}}\\n' > /tests/json.py && "
            "printf 'import json\\n' > "
            "\"$(python3 -c 'import site; print(site.getsitepackages()[0])')/sitecustomize.py\"")


async def run_trial(env: str, jobs: Path, task: str, name: str, agent: dict) -> tuple[dict, dict]:
    from harbor.models.trial.config import (
        AgentConfig,
        EnvironmentConfig,
        TaskConfig,
        TrialConfig,
    )
    from harbor.trial.trial import Trial

    environment = (EnvironmentConfig(import_path=env) if ":" in env
                   else EnvironmentConfig(type=env))
    config = TrialConfig(task=TaskConfig(path=HERE / "tasks" / task), trial_name=name,
                         trials_dir=jobs, environment=environment, agent=AgentConfig(**agent))
    result = await (await Trial.create(config)).run()
    probe_file = jobs / name / "agent" / "probe.json"
    probe = json.loads(probe_file.read_text()) if probe_file.is_file() else {}
    verifier = jobs / name / "verifier"
    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,
        "verifier": sorted(p.name for p in verifier.iterdir()) if verifier.is_dir() else []}


async def check_trials(env: str, jobs: Path, work: Path) -> dict:
    task = HERE / "tasks" / PROBE_TASK
    tree = tree_of(task)
    path = g.shortest_path(tree)
    visible = {tree["start"], *tree["doors"][tree["start"]]}
    hidden = sorted(set(tree["doors"]) - visible)
    sha = json.loads((task / "tests" / "expected.json").read_text())["tree_sha256"]
    win = work / f"evidence-{PROBE_TASK}-oracle"
    if not win.is_dir():
        win = evidence(task, work, "trial-oracle", path)
    tar = subprocess.run(["tar", "-cz", "-C", str(win), "final.json", "moves.jsonl"],
                         capture_output=True, check=True).stdout
    forged = base64.b64encode(tar).decode()
    probe_agent = "__main__:Probe"
    report = {}

    walker, result = await run_trial(env, jobs, PROBE_TASK, "walker", {
        "import_path": probe_agent, "kwargs": {"mode": "walker", "path": path}})
    report["walker"] = result | {k: walker.get(k) for k in ("before", "after")}
    check(walker.get("before", {}).get("success") is False if isinstance(
        walker.get("before"), dict) else False, f"walker: success_check before: {walker}")
    check(isinstance(walker.get("after"), dict) and walker["after"].get("success") is True,
          f"walker: success_check after the exit: {walker.get('after')}")
    check(result["rewards"] == {"reward": 1.0}, f"walker: {result}")
    check({"moves.jsonl", "final.json", "reward.txt"} <= set(result["verifier"]),
          f"walker: the verifier's folder holds {result['verifier']}")

    _, result = await run_trial(env, jobs, PROBE_TASK, "oracle", {"name": "oracle"})
    report["oracle"] = result
    check(result["rewards"] == {"reward": 1.0}, f"oracle: {result}")

    probe, result = await run_trial(env, jobs, PROBE_TASK, "probe", {
        "import_path": probe_agent,
        "kwargs": {"mode": "probe", "path": path[:3], "hidden": hidden, "sha": sha,
                   "forged": forged}})
    report["probe"] = result | {"processes": probe.get("processes"),
                                "files_scanned": "error" not in probe}
    check("error" not in probe and probe.get("processes", 0) > 0, f"probe: {probe}")
    check(not probe.get("files"), f"probe: files name hidden rooms: {probe.get('files')}")
    check(not probe.get("env") and not probe.get("cmdline"),
          f"probe: processes name hidden rooms: {probe.get('env')} {probe.get('cmdline')}")
    check(not probe.get("visible"), f"probe: the container holds {probe.get('visible')}")
    check(all(status == 404 and not named for status, named in probe.get("routes", {}).values())
          and len(probe.get("routes", {})) == 9, f"probe: routes: {probe.get('routes')}")
    check(isinstance(probe.get("look"), dict) and probe["look"].get("room") == tree["start"],
          f"probe: maze look: {probe.get('look')}")
    check(not probe.get("instruction_names"), "probe: the instruction names hidden rooms")
    check(probe.get("cheat", [1])[0] == 0, f"probe: the cheat did not run: {probe.get('cheat')}")
    check(result["rewards"] == {"reward": 0.0}, f"probe: the cheat scored {result}")
    return report


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--env", default="podman",
                        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)")
    args = parser.parse_args()
    with tempfile.TemporaryDirectory() as d:
        work = Path(d)
        check_generator()
        print(f"1. generator: {len(failures)} failures")
        before = len(failures)
        report = check_service(work)
        print(f"2. service: {len(failures) - before} failures; {json.dumps(report)}")
        before = len(failures)
        covered = check_graders(work)
        print(f"3. graders: {len(failures) - before} failures; cases: {json.dumps(covered)}")
        before = len(failures)
        check_files()
        print(f"4. no-cheat (files): {len(failures) - before} failures")
        before = len(failures)
        cases = check_metrics(work)
        print(f"5. metrics: {len(failures) - before} failures; {cases} run directories")
        if args.env != "none":
            before = len(failures)
            jobs = args.jobs_dir or work / "jobs"
            jobs.mkdir(parents=True, exist_ok=True)
            report = asyncio.run(check_trials(args.env, jobs, work))
            print(f"6. Trials on {args.env} ({PROBE_TASK}): {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())