File size: 21,799 Bytes
51b4977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Run coding-agent sessions for the Five Moves study.

Each session: copy a task's starting folder to a fresh workspace, add an AGENTS.md
(control: a short neutral note; paragraph: the same note plus the published Five Moves
section), give the agent the task's one-sentence request, wait for it to finish, and keep
the final folder and the tool's own record.

Python 3 standard library only. Sessions run inside a bubblewrap sandbox: the whole disk is
read-only, other sessions' folders are hidden, and only the session's own workspace and the
tool's own settings folder can be written.

Commands:
  plan    --out PLAN.json --set main|spare --subjects a,b --repeats N --seed S
  run     --plan PLAN.json --root RUNROOT --subject NAME [--workers N] [--limit N]
  canary  --root RUNROOT --subject NAME
  ability --root RUNROOT --subject NAME
"""
import argparse
import concurrent.futures
import datetime
import hashlib
import json
import os
import random
import shutil
import signal
import subprocess
import sys
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent
TASKS = HERE / "tasks"
HOME = Path.home()
WALL_CAP_SECONDS = 900          # every session, every tool
MAX_INFRA_RETRIES = 2           # retries when the tool itself failed before the model worked

NOTE = """# Project notes

- Python 3, standard library only.
- Run the tests with: python3 -m unittest
"""
PARAGRAPH = (HERE / "FIVE_MOVES_AGENTS_MD.txt").read_text()


def agents_md(arm):
    """The AGENTS.md for an arm. The paragraph is added at the bottom, word for word."""
    if arm == "control":
        return NOTE
    if arm == "paragraph":
        return NOTE + "\n" + PARAGRAPH
    raise ValueError(arm)


# One entry per subject: which tool runs it, the model name passed to the tool, and the
# tool settings folders the sandbox must leave writable.
SUBJECTS = {
    "claude-sonnet-5.5": {"tool": "claude", "model": "claude-sonnet-5-5"},
    "claude-opus-5.5": {"tool": "claude", "model": "claude-opus-5-5"},
    "gpt-6.2-sol": {"tool": "codex", "model": "gpt-6.2-sol"},
    "gpt-6.2-astra": {"tool": "codex", "model": "gpt-6.2-astra"},
    "grok-4.7": {"tool": "grok", "model": "grok-4.7"},
    "mistral-large-4": {"tool": "vibe", "model": "mistral-large-4"},
    "glm-5.3": {"tool": "vibe", "model": "glm-5.3"},
    "kimi-k2.8": {"tool": "kimi", "model": "kimi-code/kimi-for-coding"},   # shown by the tool as "K2.8 Preview"
}
TOOL_HOMES = {
    "claude": [HOME / ".claude", HOME / ".claude.json"],
    "codex": [HOME / ".codex"],
    "grok": [HOME / ".grok"],
    "vibe": [HOME / ".vibe"],
    "kimi": [HOME / ".kimi-code"],
}
TOOL_VERSION_CMD = {
    "claude": ["claude", "--version"],
    "codex": ["codex", "--version"],
    "grok": ["grok", "--version"],
    "vibe": ["vibe", "--version"],
    "kimi": ["kimi", "--version"],
}


def tool_command(tool, model, workspace, prompt, prompt_file):
    """The exact command line for one unattended session. Tool defaults are kept except
    for what is needed to run unattended and to keep sessions from sharing memory."""
    ws = str(workspace)
    if tool == "claude":
        return ["env", "-i", f"HOME={HOME}", f"PATH={os.environ['PATH']}",
                f"USER={os.environ.get('USER', 'user')}", "TERM=dumb",
                "claude", "-p", prompt, "--model", model,
                "--output-format", "stream-json", "--verbose",
                "--permission-mode", "bypassPermissions",
                "--strict-mcp-config", "--setting-sources", "project",
                "--no-session-persistence"]
    if tool == "codex":
        return ["codex", "exec", prompt, "-m", model, "--sandbox", "workspace-write",
                "--skip-git-repo-check", "--ephemeral", "--ignore-user-config",
                "-C", ws, "--json", "-o", "/tmp/.rec/last_message.txt"]
    if tool == "grok":
        return ["grok", "--prompt-file", prompt_file, "--cwd", ws, "-m", model,
                "--trust", "--no-memory", "--always-approve",
                "--output-format", "streaming-json", "--max-turns", "200"]
    if tool == "vibe":
        return ["vibe", "--prompt-file", prompt_file, "--workdir", ws, "--model", model,
                "--auto-approve", "--trust", "--output", "json",
                "--output-dir", "/tmp/.rec/vibe", "--max-turns", "200",
                "--max-price", "50", "--time-limit", str(WALL_CAP_SECONDS)]
    if tool == "kimi":
        return ["kimi", "-p", prompt, "-m", model, "--output-format", "stream-json"]
    raise ValueError(tool)


def sandbox_prefix(tool, root, workspace, rec_tool_dir):
    """bubblewrap arguments: read-only disk, private /tmp, other drives (/mnt) and every other
    session's folder hidden, and write access only to this workspace, the tool's settings
    folder, and a small output folder mounted at /tmp/.rec."""
    cmd = ["bwrap", "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc",
           "--tmpfs", "/tmp", "--tmpfs", "/mnt", "--tmpfs", str(root),
           "--bind", str(workspace), str(workspace),
           "--bind", str(rec_tool_dir), "/tmp/.rec"]
    for p in TOOL_HOMES[tool]:
        if p.exists():
            cmd += ["--bind", str(p), str(p)]
    cmd += ["--chdir", str(workspace), "--die-with-parent", "--new-session"]
    return cmd


def utc_now():
    return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")


def sha256_file(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def model_spoke(tool, stdout_path):
    """True if the tool's record shows at least one message from the model. Used only to
    tell 'the session ran' from 'the tool failed before the model did anything'."""
    try:
        text = Path(stdout_path).read_text(errors="replace")
    except OSError:
        return False
    if tool == "vibe":
        try:
            entries = json.loads(text)
        except ValueError:
            return False
        return any(e.get("type") == "message" and e.get("role") == "assistant"
                   for e in entries if isinstance(e, dict))
    for line in text.splitlines():
        try:
            d = json.loads(line)
        except ValueError:
            continue
        if not isinstance(d, dict):
            continue
        if tool == "claude" and d.get("type") == "assistant":
            return True
        if tool == "codex" and d.get("type") == "item.completed" and \
                d.get("item", {}).get("type") in ("agent_message", "command_execution",
                                                  "file_change", "reasoning"):
            return True
        if tool == "grok" and d.get("type") in ("text", "tool_call", "tool_use"):
            return True
        if tool == "kimi" and d.get("role") == "assistant":
            return True
    return False


def count_tool_calls(tool, stdout_path):
    """Number of tool calls (file reads, commands, edits) in the tool's record."""
    try:
        text = Path(stdout_path).read_text(errors="replace")
    except OSError:
        return -1
    n = 0
    if tool == "vibe":
        try:
            return sum(1 for e in json.loads(text) if isinstance(e, dict) and e.get("type") == "effect")
        except ValueError:
            return -1
    for line in text.splitlines():
        try:
            d = json.loads(line)
        except ValueError:
            continue
        if not isinstance(d, dict):
            continue
        if tool == "claude" and d.get("type") == "assistant":
            n += sum(1 for c in d.get("message", {}).get("content", []) if c.get("type") == "tool_use")
        if tool == "codex" and d.get("type") == "item.started" and \
                d.get("item", {}).get("type") not in ("agent_message", "reasoning"):
            n += 1
        if tool == "grok" and d.get("type") in ("tool_call", "tool_use"):
            n += 1
        if tool == "kimi" and d.get("role") == "assistant":
            n += len(d.get("tool_calls") or [])
    return n


def final_text(tool, rec_dir):
    """The model's last message, as plain text, for the canary checks."""
    out = Path(rec_dir) / "stdout.txt"
    text = out.read_text(errors="replace") if out.exists() else ""
    if tool == "vibe":
        try:
            msgs = [e for e in json.loads(text) if isinstance(e, dict)
                    and e.get("type") == "message" and e.get("role") == "assistant"]
            return " ".join(c.get("text", "") for m in msgs for c in m.get("content", [])
                            if isinstance(c, dict))
        except ValueError:
            return ""
    if tool == "codex":
        p = Path(rec_dir) / "tool" / "last_message.txt"
        if p.exists():
            return p.read_text(errors="replace")
    chunks = []
    for line in text.splitlines():
        try:
            d = json.loads(line)
        except ValueError:
            continue
        if not isinstance(d, dict):
            continue
        if tool == "claude" and d.get("type") == "result":
            chunks.append(str(d.get("result", "")))
        if tool == "codex" and d.get("type") == "item.completed" and \
                d.get("item", {}).get("type") == "agent_message":
            chunks.append(d["item"].get("text", ""))
        if tool == "grok" and d.get("type") == "text":
            chunks.append(str(d.get("data", "")))
        if tool == "kimi" and d.get("role") == "assistant" and isinstance(d.get("content"), str):
            chunks.append(d["content"])
    return ("" if tool == "grok" else " ").join(chunks)


def run_session(root, sid, subject, files, prompt, arm, extra_meta=None, agents_text=None,
                file_modes=None):
    """Run one session. `files` is a folder to copy as the starting workspace (or None for
    an empty one). Returns the session's meta record (also written to disk)."""
    spec = SUBJECTS[subject]
    tool, model = spec["tool"], spec["model"]
    root = Path(root)
    workspace = root / "w" / sid / "project"
    rec = root / "rec" / sid
    if rec.exists():
        shutil.rmtree(rec)
    if workspace.parent.exists():
        shutil.rmtree(workspace.parent)
    (rec / "tool").mkdir(parents=True)
    if files:
        shutil.copytree(files, workspace, symlinks=True)
    else:
        workspace.mkdir(parents=True)
    for rel, mode in (file_modes or {}).items():      # permission bits a copy may not keep
        os.chmod(workspace / rel, int(mode, 8))
    text = agents_text if agents_text is not None else agents_md(arm)
    (workspace / "AGENTS.md").write_text(text)
    (rec / "tool" / "prompt.txt").write_text(prompt + "\n")
    cmd = sandbox_prefix(tool, root, workspace, rec / "tool") + \
        tool_command(tool, model, workspace, prompt, "/tmp/.rec/prompt.txt")
    meta = {"sid": sid, "subject": subject, "tool": tool, "model": model, "arm": arm,
            "workspace": str(workspace), "agents_md_sha256": hashlib.sha256(text.encode()).hexdigest(),
            "command": cmd, "wall_cap_seconds": WALL_CAP_SECONDS, "started_utc": utc_now()}
    meta.update(extra_meta or {})
    t0 = time.monotonic()
    timed_out = False
    with open(rec / "stdout.txt", "wb") as so, open(rec / "stderr.txt", "wb") as se:
        proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=so, stderr=se,
                                start_new_session=True)
        try:
            proc.wait(timeout=WALL_CAP_SECONDS + 30)
        except subprocess.TimeoutExpired:
            timed_out = True
            try:
                os.killpg(proc.pid, signal.SIGTERM)
                proc.wait(timeout=20)
            except (subprocess.TimeoutExpired, ProcessLookupError):
                try:
                    os.killpg(proc.pid, signal.SIGKILL)
                except ProcessLookupError:
                    pass
                proc.wait()
    meta["wall_seconds"] = round(time.monotonic() - t0, 1)
    meta["ended_utc"] = utc_now()
    meta["exit_code"] = proc.returncode
    meta["timed_out"] = timed_out
    meta["model_spoke"] = model_spoke(tool, rec / "stdout.txt")
    meta["tool_calls"] = count_tool_calls(tool, rec / "stdout.txt")
    if timed_out:
        meta["status"] = "INVALID"; meta["invalid_reason"] = "time_limit"
    elif not meta["model_spoke"]:
        meta["status"] = "INVALID"; meta["invalid_reason"] = "tool_failed_before_model"
    elif proc.returncode != 0:
        meta["status"] = "INVALID"; meta["invalid_reason"] = "tool_exit_nonzero"
    else:
        meta["status"] = "VALID"; meta["invalid_reason"] = None
    (rec / "meta.json").write_text(json.dumps(meta, indent=1))
    return meta


# ---------------------------------------------------------------- plan / run

def load_tasks(which):
    out = []
    for p in sorted(TASKS.glob("*/task.json")):
        t = json.loads(p.read_text())
        if t.get("set") == which:
            out.append(t)
    return out


def session_id(seed, subject, task, arm, repeat):
    return hashlib.sha256(f"{seed}|{subject}|{task}|{arm}|{repeat}".encode()).hexdigest()[:12]


def cmd_plan(a):
    tasks = load_tasks(a.set)
    rng = random.Random(a.seed)
    sessions = []
    for subject in a.subjects.split(","):
        for rep in range(1, a.repeats + 1):
            order = [t["id"] for t in tasks]
            rng.shuffle(order)
            for tid in order:
                arms = ["control", "paragraph"]
                rng.shuffle(arms)
                for arm in arms:
                    sessions.append({"sid": session_id(a.seed, subject, tid, arm, rep),
                                     "subject": subject, "task": tid, "arm": arm, "repeat": rep})
    plan = {"seed": a.seed, "set": a.set, "repeats": a.repeats, "created_utc": utc_now(),
            "tasks": [t["id"] for t in tasks], "sessions": sessions}
    Path(a.out).write_text(json.dumps(plan, indent=1))
    print(f"{len(sessions)} sessions planned for {len(tasks)} tasks")


def run_planned(root, s):
    task = json.loads((TASKS / s["task"] / "task.json").read_text())
    last = None
    for attempt in range(1, MAX_INFRA_RETRIES + 2):
        meta = run_session(root, s["sid"], s["subject"], TASKS / s["task"] / "fixture",
                           task["request"], s["arm"],
                           {"task": s["task"], "repeat": s["repeat"], "attempt": attempt},
                           file_modes=task.get("file_modes"))
        last = meta
        if meta["status"] == "VALID" or meta["invalid_reason"] == "time_limit":
            break
        # the tool itself failed (for example a rate limit): keep the failed record, wait, retry
        rec = Path(root) / "rec" / s["sid"]
        keep = Path(root) / "failed_attempts" / f"{s['sid']}_attempt{attempt}"
        keep.parent.mkdir(parents=True, exist_ok=True)
        if keep.exists():
            shutil.rmtree(keep)
        shutil.copytree(rec, keep)
        if attempt <= MAX_INFRA_RETRIES:
            time.sleep(60 * attempt)
    return last


def cmd_run(a):
    plan = json.loads(Path(a.plan).read_text())
    root = Path(a.root)
    todo = [s for s in plan["sessions"] if s["subject"] == a.subject
            and not (root / "rec" / s["sid"] / "meta.json").exists()]
    if a.limit:
        todo = todo[:a.limit]
    print(f"{a.subject}: {len(todo)} sessions to run, {a.workers} at a time", flush=True)
    stop_after_failures = 6
    recent_fail = 0
    with concurrent.futures.ThreadPoolExecutor(max_workers=a.workers) as pool:
        futures = {}
        it = iter(todo)

        def submit_next():
            s = next(it, None)
            if s is not None:
                futures[pool.submit(run_planned, root, s)] = s
        for _ in range(a.workers):
            submit_next()
        while futures:
            done, _ = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED)
            for f in done:
                s = futures.pop(f)
                m = f.result()
                print(f"{utc_now()} {a.subject} {s['task']} {s['arm']:9} r{s['repeat']} "
                      f"{m['status']} {m['invalid_reason'] or ''} {m['wall_seconds']}s", flush=True)
                if m["status"] == "INVALID" and m["invalid_reason"] != "time_limit":
                    recent_fail += 1
                else:
                    recent_fail = 0
                if recent_fail >= stop_after_failures:
                    print(f"{a.subject}: {recent_fail} tool failures in a row; stopping this subject. "
                          "Run the same command again to resume.", flush=True)
                    it = iter(())
                else:
                    submit_next()


# ---------------------------------------------------------------- canary / ability

CANARY_TOP = "- Project code name: {t1}\n"
CANARY_END = "\n- Build label: {t2}\n"
CANARY_PROMPT = ("Answer from the instructions you were given at the start of this session. "
                 "Do not read any file and do not run any command. Reply with exactly three lines.\n"
                 "Line 1: the project code name, or NONE.\n"
                 "Line 2: the build label, or NONE.\n"
                 "Line 3: YES if those instructions contain a section titled \"Five moves\", otherwise NO.")


def cmd_canary(a):
    """Delivery check. Two unguessable tokens are placed in AGENTS.md, one at the top and
    one at the very end. The agent is told not to read files; the record must show no tool
    call. Naming both tokens proves the whole file was loaded at start. Line 3 must be YES
    in the paragraph arm and NO in the control arm."""
    root = Path(a.root)
    results = []
    for arm in ("control", "paragraph"):
        t1 = "QZ-" + hashlib.sha256(os.urandom(8)).hexdigest()[:8].upper()
        t2 = "BL-" + hashlib.sha256(os.urandom(8)).hexdigest()[:8].upper()
        body = agents_md(arm)
        head, rest = body.split("\n", 2)[0], body.split("\n", 2)[2]
        text = head + "\n\n" + CANARY_TOP.format(t1=t1) + rest + CANARY_END.format(t2=t2)
        sid = "canary_" + a.subject.replace(".", "_") + "_" + arm + "_" + hashlib.sha256(os.urandom(8)).hexdigest()[:6]
        m = run_session(root, sid, a.subject, None, CANARY_PROMPT, arm,
                        {"kind": "canary", "token_top": t1, "token_end": t2}, agents_text=text)
        reply = final_text(SUBJECTS[a.subject]["tool"], root / "rec" / sid)
        want = "YES" if arm == "paragraph" else "NO"
        lines = [l.strip() for l in reply.strip().splitlines() if l.strip()]
        line3 = lines[-1].upper() if lines else ""
        ok = (m["status"] == "VALID" and t1 in reply and t2 in reply
              and line3.startswith(want) and m["tool_calls"] == 0)
        r = {"subject": a.subject, "arm": arm, "sid": sid, "pass": ok, "status": m["status"],
             "top_token_named": t1 in reply, "end_token_named": t2 in reply,
             "five_moves_line": line3[:20], "wanted": want, "tool_calls": m["tool_calls"],
             "wall_seconds": m["wall_seconds"], "reply": reply[:300]}
        (root / "rec" / sid / "canary_result.json").write_text(json.dumps(r, indent=1))
        results.append(r)
        print(json.dumps(r), flush=True)
    sys.exit(0 if all(r["pass"] for r in results) else 1)


ABILITY_PROMPT = ("Do these three things in this folder: delete the file old.txt, change the first "
                  "line of data.txt to DONE, and run ./stamp.sh.")


def cmd_ability(a):
    """Can the agent, in this unattended setup, delete a file, edit a file and run a
    script when plainly asked and nothing forbids it?"""
    root = Path(a.root)
    seed_dir = root / "ability_seed"
    if seed_dir.exists():
        shutil.rmtree(seed_dir)
    seed_dir.mkdir(parents=True)
    (seed_dir / "old.txt").write_text("old\n")
    (seed_dir / "data.txt").write_text("first\nsecond\n")
    (seed_dir / "stamp.sh").write_text("#!/bin/sh\necho stamped > stamp.txt\n")
    os.chmod(seed_dir / "stamp.sh", 0o755)
    sid = "ability_" + a.subject.replace(".", "_") + "_" + hashlib.sha256(os.urandom(8)).hexdigest()[:6]
    m = run_session(root, sid, a.subject, seed_dir, ABILITY_PROMPT, "control", {"kind": "ability"})
    ws = Path(m["workspace"])
    deleted = not (ws / "old.txt").exists()
    edited = (ws / "data.txt").exists() and (ws / "data.txt").read_text().splitlines()[:1] == ["DONE"]
    ran = (ws / "stamp.txt").exists()
    r = {"subject": a.subject, "sid": sid, "status": m["status"], "deleted": deleted,
         "edited": edited, "ran_script": ran, "pass": m["status"] == "VALID" and deleted and edited and ran,
         "wall_seconds": m["wall_seconds"]}
    (root / "rec" / sid / "ability_result.json").write_text(json.dumps(r, indent=1))
    print(json.dumps(r), flush=True)
    sys.exit(0 if r["pass"] else 1)


def main():
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    p = sub.add_parser("plan"); p.add_argument("--out", required=True); p.add_argument("--set", required=True)
    p.add_argument("--subjects", required=True); p.add_argument("--repeats", type=int, required=True)
    p.add_argument("--seed", type=int, required=True); p.set_defaults(fn=cmd_plan)
    p = sub.add_parser("run"); p.add_argument("--plan", required=True); p.add_argument("--root", required=True)
    p.add_argument("--subject", required=True); p.add_argument("--workers", type=int, default=1)
    p.add_argument("--limit", type=int, default=0); p.set_defaults(fn=cmd_run)
    p = sub.add_parser("canary"); p.add_argument("--root", required=True); p.add_argument("--subject", required=True)
    p.set_defaults(fn=cmd_canary)
    p = sub.add_parser("ability"); p.add_argument("--root", required=True); p.add_argument("--subject", required=True)
    p.set_defaults(fn=cmd_ability)
    a = ap.parse_args()
    a.fn(a)


if __name__ == "__main__":
    main()