Datasets:

Modalities:
Text
Languages:
English
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 30,241 Bytes
e3a266f
 
 
 
eae0824
e3a266f
24df058
 
 
6db0e7c
 
0c2eebf
 
 
 
6db0e7c
 
 
 
 
 
 
 
 
 
 
 
 
0c2eebf
e3a266f
6db0e7c
 
 
 
 
 
 
 
 
8d461e0
 
 
 
d1389e4
e3a266f
 
 
 
 
 
 
48157bc
e3a266f
24df058
e3a266f
 
 
 
 
 
 
 
 
 
 
6db0e7c
 
e3a266f
 
 
 
 
 
 
 
b064c6f
 
 
6db0e7c
48157bc
 
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
 
 
 
 
 
 
d1389e4
6db0e7c
 
 
 
 
e3a266f
 
0c2eebf
 
 
 
 
 
 
 
 
 
e3a266f
 
 
 
 
 
0c2eebf
e3a266f
 
6db0e7c
e3a266f
 
 
6db0e7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
24df058
 
 
 
8d461e0
 
e3a266f
24df058
 
 
8d461e0
24df058
8d461e0
24df058
 
 
 
 
8d461e0
 
24df058
 
8d461e0
24df058
 
e3a266f
 
 
8d461e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
 
 
 
 
 
 
0c2eebf
 
 
 
 
 
 
 
 
 
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24df058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d461e0
 
 
 
 
 
 
 
 
 
 
24df058
 
 
e3a266f
 
6db0e7c
 
 
 
 
e3a266f
 
24df058
e3a266f
0c2eebf
24df058
 
 
e3a266f
24df058
e3a266f
 
 
 
 
 
 
 
 
6db0e7c
 
e3a266f
6db0e7c
 
 
 
 
 
e3a266f
 
 
 
 
 
6db0e7c
d1389e4
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
 
 
 
 
24df058
e3a266f
24df058
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
24df058
6db0e7c
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
# /// 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

1. Generator: generate.py reproduces problems.json and tasks/ byte for byte from its seed;
   another seed gives other problems and is recorded in every task's metadata; 32 problems of
   16 integers in 1..99, with sizes 1, 2, 4, 6, 8, 12 and 16 (224 teams, 1,568 tasks); 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.
   A preexisting reward symlink to a valid answer leaves that answer intact and scores 1.
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.
"""

import argparse
import asyncio
import base64
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
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 slot labels and their private 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:
        root = Path(d)
        g.generate(root)
        check(files(root) == files(HERE), "generate.py does not reproduce the committed files")
        seed = g.SEED + 1
        g.generate(root, seed=seed)
        tasks = sorted((root / "tasks").glob("*/task.toml"))
        check(len(tasks) == 1568, "alternate seed did not generate 1,568 task.toml files")
        for task in tasks:
            check(re.findall(r"^seed = (.+)$", task.read_text(), re.MULTILINE) == [str(seed)],
                  f"{task.parent.name}: task.toml does not record the alternate seed {seed}")
    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(g.SIZES == (1, 2, 4, 6, 8, 12, 16), "team sizes do not match the evaluation grid")
    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 check_reward_symlink(task: Path) -> None:
    def setup(root: Path) -> None:
        answer = root / "app" / "answer.json"
        shutil.copyfile(task / "tests" / "expected.json", answer)
        verifier = root / "verifier"
        verifier.mkdir()
        (verifier / "reward.txt").symlink_to(answer)

    check(grade(task, cheat=setup) == 1, f"{task.name}: preexisting reward symlink clobbered the answer")


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-"):
            check_reward_symlink(task)
            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", ".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 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)")
    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)}")
    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())