Reversible clean-root candidate rebuilt from oak/benchmarks main@009dead264ca; original repository retained.

scripts/agent_workflow.py in oak/benchmarks

scripts/agent_workflow.py 2188 lines · 92.3 KB · python
1
#!/usr/bin/env python3
2
"""Run real local coding-agent workflows against Git and Oak subjects.
3
4
This runner is intentionally separate from workflow_ab.py. workflow_ab.py runs
5
deterministic agent-shaped command recipes; this file runs actual CLI coding
6
agents such as Codex, Claude Code, and Cursor Agent, then normalizes their
7
transcripts into scripts/agent_metrics_schema.py rows.
8
"""
9
10
from __future__ import annotations
11
12
import argparse
13
import hashlib
14
import json
15
import math
16
import os
17
import platform
18
import random
19
import re
20
import shutil
21
import statistics
22
import subprocess
23
import sys
24
import tempfile
25
import time
26
from dataclasses import dataclass
27
from datetime import datetime, timezone
28
from pathlib import Path, PurePosixPath
29
from typing import Callable, Any
30
31
import workflow_ab
32
from agent_metrics_schema import SCHEMA_VERSION, validate_row
33
from oakbench import workflow_oracles
34
from oakbench.agent_execution import DEFAULT_OUTPUT_LIMIT_BYTES, EXECUTION_VERSION, run_captured
35
from oakbench.environment import ENV_ISOLATION_VERSION, base_env as shared_base_env
36
from oakbench.runner import runner_fields
37
from oakbench.cachectl import cache_fields
38
from oakbench.agent_environment import agent_environment as filtered_agent_environment
39
from oakbench.classify import classify_command, unwrap_shell_command, vcs_invocations
40
from oakbench.command_semantics import semantics
41
from oakbench.configio import load_toml
42
from oakbench.results import ResultsStore
43
from oakbench.rows import token_total as shared_token_total
44
from oakbench.stream_adapters import adapter_for, analyze_stream, first_number, walk_json
45
from oakbench.thrash import agent_blocked_on_vcs_ms, thrash_events, vcs_share_of_task_wall
46
from oakbench.vcs_shim import create_shim_dir, measure_shim_overhead, read_sidecar_rows
47
from oakbench.tokens import (
48
    CACHE_READ_TOKEN_WEIGHT,
49
    COST_WEIGHTS_NOTE,
50
    EMITTED_TOKEN_WEIGHT,
51
    INGESTED_TOKEN_WEIGHT,
52
)
53
54
55
ROOT = Path(__file__).resolve().parents[1]
56
DEFAULT_WORKDIR = Path(tempfile.gettempdir()) / "oak-agent-workflow"
57
# 2026-11-09.1: wide_config_refactor names the replacement value. The trusted
58
# oracle requires `timeout_ms = 3000` but 2026-06-09.2 never said so, so every
59
# real agent failed regardless of VCS (first cloud canary, 2026-11-09).
60
PROMPT_VERSION = "2026-11-09.1"
61
ATTRIBUTION_VERSION = "2026-09-18.1"
62
ORACLE_VERSION = workflow_oracles.VERSION
63
COMMAND_SEMANTICS_VERSION = semantics().version
64
TRACKS = ("agent-default", "core-equivalent")
65
INSTRUCTION_LEVELS = ("zero-shot", "cheat-sheet", "full-docs")
66
VCS_DIR_NAMES = {".git", ".oak", ".hg", ".svn"}
67
GENERATED_ARTIFACT_DIR_NAMES = {"__pycache__"}
68
GENERATED_ARTIFACT_SUFFIXES = (".pyc", ".pyo")
69
70
71
@dataclass(frozen=True)
72
class AgentConfig:
73
    name: str
74
    adapter: str
75
    provider: str | None
76
    bin: Path | None
77
    model: str | None
78
    version: str | None
79
80
81
@dataclass(frozen=True)
82
class AgentExecution:
83
    returncode: int
84
    timed_out: bool
85
    elapsed_ms: float
86
    stdout_path: Path
87
    stderr_path: Path
88
    prompt_path: Path
89
    output_limited: bool = False
90
    capture_complete: bool = True
91
    capture_metadata: dict[str, Any] | None = None
92
93
94
@dataclass(frozen=True)
95
class OracleResult:
96
    elapsed_ms: float
97
    test_ms: float
98
    vcs_ms: float
99
    success: bool
100
    outcome: str
101
    failure_reason: str | None
102
    checks: dict[str, bool | None]
103
    test_returncode: int
104
    test_output_bytes: int
105
    status_output: str
106
    dirty_files_at_end: int | None
107
    changed_files: list[str]
108
    bytes_written: int
109
    commit_delta: int
110
    artifact_paths: list[Path]
111
    evidence: dict[str, Any] | None = None
112
113
114
def parse_args() -> argparse.Namespace:
115
    parser = argparse.ArgumentParser(description=__doc__)
116
    parser.add_argument(
117
        "--workflows",
118
        default="bugfix_test_loop",
119
        help="Comma-separated workflow_ab workflow names, or 'all'. Default keeps real-agent runs cheap.",
120
    )
121
    parser.add_argument("--subjects", help="Comma-separated subject names from config/subjects.toml")
122
    parser.add_argument(
123
        "--agents",
124
        default="mock",
125
        help="Comma-separated agent names, 'available', or 'all'. Default is mock to avoid accidental model spend.",
126
    )
127
    parser.add_argument("--runs", type=int, default=1)
128
    parser.add_argument("--config", type=Path, default=ROOT / "config" / "subjects.toml")
129
    parser.add_argument("--agents-config", type=Path, default=ROOT / "config" / "agents.toml")
130
    parser.add_argument("--workdir", type=Path, default=DEFAULT_WORKDIR)
131
    parser.add_argument("--results", type=Path, default=ROOT / "results" / "agent-workflow")
132
    parser.add_argument(
133
        "--oak-repo",
134
        type=Path,
135
        default=workflow_ab.DEFAULT_OAK_REPO,
136
        help="Optional Oak source checkout for provenance metadata. Defaults to $OAK_REPO or ../oak.",
137
    )
138
    parser.add_argument("--keep-workdirs", action="store_true")
139
    parser.add_argument("--timeout-seconds", type=float, default=900.0)
140
    parser.add_argument("--output-limit-bytes", type=int, default=DEFAULT_OUTPUT_LIMIT_BYTES,
141
                        help="Maximum combined real-agent stdout/stderr bytes retained per trial.")
142
    parser.add_argument(
143
        "--agent-environment",
144
        choices=("minimal", "local-default"),
145
        default="minimal",
146
        help=(
147
            "minimal asks CLIs to avoid user/project customizations when supported; "
148
            "local-default measures the normal local agent environment."
149
        ),
150
    )
151
    parser.add_argument("--git-bin", type=Path)
152
    parser.add_argument("--oak-installed-bin", type=Path)
153
    parser.add_argument("--oak-local-bin", type=Path)
154
    parser.add_argument("--oak-aa-bin", type=Path, help="A/A control: the baseline Oak binary under subject oak_installed_aa.")
155
    parser.add_argument(
156
        "--track",
157
        choices=TRACKS,
158
        default="agent-default",
159
        help="Command semantics prompt track. Real agent runs normally use agent-default.",
160
    )
161
    parser.add_argument(
162
        "--instruction-level",
163
        choices=INSTRUCTION_LEVELS,
164
        default="full-docs",
165
        help=(
166
            "How much VCS-specific instruction the prompt and AGENTS.md carry. "
167
            "zero-shot names the VCS but gives no commands, measuring the model-familiarity tax; "
168
            "cheat-sheet gives a one-line command list; full-docs is the historical default."
169
        ),
170
    )
171
    parser.add_argument(
172
        "--vcs-shim",
173
        action="store_true",
174
        help=(
175
            "Wrap git/oak with PATH shim executables that record per-call VCS timing "
176
            "to a sidecar JSONL. Shim overhead is measured and recorded per run, never subtracted."
177
        ),
178
    )
179
    parser.add_argument("--randomize-subject-order", action="store_true")
180
    parser.add_argument("--randomize-agent-order", action="store_true")
181
    parser.add_argument("--list-agents", action="store_true", help="Print configured/discovered agents and exit.")
182
    return parser.parse_args()
183
184
185
def resolve_bin(raw: str | None) -> Path | None:
186
    if not raw:
187
        return None
188
    path = Path(raw).expanduser()
189
    if path.is_absolute() and path.exists():
190
        return path
191
    found = shutil.which(raw)
192
    return Path(found) if found else path
193
194
195
def sanitized_agent_env(env: dict[str, str]) -> dict[str, str]:
196
    return filtered_agent_environment(env)
197
198
199
def trial_agent_env(artifacts: Path, home_root: Path | None = None) -> tuple[dict[str, str], dict[str, Any]]:
200
    if home_root is not None:
201
        home_root.mkdir(parents=True, exist_ok=True)
202
    home = Path(tempfile.mkdtemp(prefix="agent-home-", dir=home_root))
203
    env = sanitized_agent_env(shared_base_env(home=home))
204
    override_names = ("CODEX_HOME", "CLAUDE_CONFIG_DIR", "CURSOR_CONFIG_DIR", "SSH_AUTH_SOCK")
205
    return env, {
206
        "fresh_agent_home": str(home), "environment_policy": "fresh-home-explicit-agent-allowlist-v2",
207
        "preserved_config_override_names": [name for name in override_names if name in env],
208
        "provider_environment_preserved": True,
209
        "os_sandbox_enforced": False,
210
        "limitations": "Provider/config overrides remain usable; HOME is not filesystem or network containment. "
211
                       "POSIX descendants creating new sessions can escape group cleanup; other platforms own only the direct child.",
212
    }
213
214
215
def command_output(command: list[str], cwd: Path | None = None, timeout: float = 10.0) -> str | None:
216
    try:
217
        return subprocess.check_output(
218
            command,
219
            cwd=cwd,
220
            env=sanitized_agent_env(workflow_ab.base_env()),
221
            text=True,
222
            stderr=subprocess.STDOUT,
223
            timeout=timeout,
224
        ).strip()
225
    except Exception:
226
        return None
227
228
229
def agent_version(agent: AgentConfig) -> str | None:
230
    if agent.adapter == "deterministic_mock":
231
        return "deterministic-mock-" + PROMPT_VERSION
232
    if agent.bin is None or not agent.bin.exists():
233
        return None
234
    return command_output([str(agent.bin), "--version"])
235
236
237
def load_agents(path: Path, selector: str) -> list[AgentConfig]:
238
    data = load_toml(path)
239
    raw_agents = data.get("agents", {})
240
    configured: dict[str, AgentConfig] = {}
241
    for key, raw in raw_agents.items():
242
        if not raw.get("enabled", False):
243
            continue
244
        name = str(raw.get("name") or key)
245
        adapter = str(raw["adapter"])
246
        resolved = resolve_bin(raw.get("bin"))
247
        if adapter != "deterministic_mock" and (resolved is None or not resolved.exists()):
248
            configured[name] = AgentConfig(
249
                name=name,
250
                adapter=adapter,
251
                provider=raw.get("provider"),
252
                bin=resolved,
253
                model=raw.get("model") or None,
254
                version=None,
255
            )
256
            continue
257
        agent = AgentConfig(
258
            name=name,
259
            adapter=adapter,
260
            provider=raw.get("provider"),
261
            bin=resolved,
262
            model=raw.get("model") or None,
263
            version=None,
264
        )
265
        configured[name] = AgentConfig(
266
            name=agent.name,
267
            adapter=agent.adapter,
268
            provider=agent.provider,
269
            bin=agent.bin,
270
            model=agent.model,
271
            version=agent_version(agent),
272
        )
273
274
    if selector == "all":
275
        selected = list(configured.values())
276
    elif selector == "available":
277
        selected = [
278
            agent
279
            for agent in configured.values()
280
            if agent.adapter != "deterministic_mock" and agent.bin is not None and agent.bin.exists()
281
        ]
282
    else:
283
        wanted = [item.strip() for item in selector.split(",") if item.strip()]
284
        missing = [name for name in wanted if name not in configured]
285
        if missing:
286
            raise SystemExit("Unknown agents: " + ", ".join(missing))
287
        selected = [configured[name] for name in wanted]
288
289
    unavailable = [
290
        agent.name
291
        for agent in selected
292
        if agent.adapter != "deterministic_mock" and (agent.bin is None or not agent.bin.exists())
293
    ]
294
    if unavailable:
295
        raise SystemExit("Selected agents are not installed or not executable: " + ", ".join(unavailable))
296
    if not selected:
297
        raise SystemExit("No agents selected")
298
    return selected
299
300
301
def print_agents(agents: list[AgentConfig]) -> None:
302
    print("| Agent | Adapter | Provider | Binary | Version |")
303
    print("| --- | --- | --- | --- | --- |")
304
    for agent in agents:
305
        print(
306
            f"| `{agent.name}` | `{agent.adapter}` | `{agent.provider or ''}` | "
307
            f"`{agent.bin or ''}` | `{agent.version or ''}` |"
308
        )
309
310
311
def select_workflows(raw: str) -> list[workflow_ab.Workflow]:
312
    return workflow_ab.select_workflows(raw)
313
314
315
def vcs_mode(subject: workflow_ab.Subject) -> str:
316
    if subject.kind == "git":
317
        return "git_single_checkout"
318
    if subject.kind == "oak":
319
        return "oak_single_mount"
320
    return "git_single_checkout"
321
322
323
def strip_ansi(text: str) -> str:
324
    return re.sub(r"\x1b\[[0-9;]*m", "", text)
325
326
327
def is_workspace_file(path: Path, root: Path) -> bool:
328
    try:
329
        rel = path.relative_to(root)
330
    except ValueError:
331
        return False
332
    rel_posix = rel.as_posix()
333
    return not any(part in VCS_DIR_NAMES for part in rel.parts) and not is_generated_artifact(rel_posix)
334
335
336
def is_generated_artifact(path: str) -> bool:
337
    rel = PurePosixPath(path)
338
    return any(part in GENERATED_ARTIFACT_DIR_NAMES for part in rel.parts) or rel.name.endswith(
339
        GENERATED_ARTIFACT_SUFFIXES
340
    )
341
342
343
def workspace_manifest(root: Path) -> dict[str, dict[str, Any]]:
344
    manifest: dict[str, dict[str, Any]] = {}
345
    for path in sorted(root.rglob("*")):
346
        if not (path.is_file() or path.is_symlink()) or not is_workspace_file(path, root):
347
            continue
348
        rel = path.relative_to(root).as_posix()
349
        if path.is_symlink():
350
            target = os.readlink(path)
351
            target_bytes = os.fsencode(target)
352
            manifest[rel] = {
353
                "sha256": hashlib.sha256(target_bytes).hexdigest(),
354
                "bytes": len(target_bytes),
355
                "kind": "symlink",
356
                "target": target,
357
            }
358
            continue
359
        digest = hashlib.sha256()
360
        size = 0
361
        with path.open("rb") as fh:
362
            for chunk in iter(lambda: fh.read(1024 * 1024), b""):
363
                size += len(chunk)
364
                digest.update(chunk)
365
        manifest[rel] = {
366
            "sha256": digest.hexdigest(),
367
            "bytes": size,
368
            "kind": "file",
369
            "executable": bool(path.stat().st_mode & 0o111),
370
        }
371
    return manifest
372
373
374
def changed_files(before: dict[str, dict[str, Any]], after: dict[str, dict[str, Any]]) -> list[str]:
375
    names = sorted(set(before) | set(after))
376
    return [name for name in names if before.get(name) != after.get(name)]
377
378
379
def allowed_change(workflow: workflow_ab.Workflow, path: str) -> bool:
380
    if workflow.name == "bugfix_test_loop":
381
        return path == "app/pricing.py"
382
    if workflow.name == "wide_config_refactor":
383
        return path.startswith("services/") and path.endswith("/config.toml")
384
    if workflow.name == "large_asset_manifest":
385
        return path == "manifest.json"
386
    if workflow.name == "history_archaeology":
387
        return False
388
    if workflow.name == "vcs_error_recovery":
389
        return path == "README.md"
390
    return True
391
392
393
def expected_change_ok(workflow: workflow_ab.Workflow, changed: list[str]) -> bool:
394
    changed = [path for path in changed if not is_generated_artifact(path)]
395
    # Read-only scenarios must leave the tree untouched; everything else must
396
    # change something, and only within the allowed shape.
397
    if workflow.name == "history_archaeology":
398
        return not changed
399
    return bool(changed) and all(allowed_change(workflow, path) for path in changed)
400
401
402
def write_workspace_instructions(
403
    repo: Path, subject: workflow_ab.Subject, track: str, instruction_level: str
404
) -> None:
405
    if instruction_level == "zero-shot":
406
        vcs_name = "Git" if subject.kind == "git" else "Oak (a version control system, not Git)"
407
        text = "\n".join(
408
            [
409
                "# AGENTS.md",
410
                "",
411
                f"This benchmark workspace uses {vcs_name}.",
412
                "Use the current checkout; do not create another workspace.",
413
                "Snapshot your final work with the workspace's VCS and leave the tree clean.",
414
                "",
415
            ]
416
        )
417
    elif instruction_level == "cheat-sheet":
418
        if subject.kind == "git":
419
            cheat = "`git status --short`, `git diff --stat`, `git add . && git commit -m \"agent task\"`"
420
            header = "This benchmark workspace uses Git."
421
        else:
422
            cheat = "`oak status`, `oak diff`, `oak commit --no-verify`"
423
            header = "This benchmark workspace uses Oak, not Git. Do not run `git` commands."
424
        text = "\n".join(
425
            [
426
                "# AGENTS.md",
427
                "",
428
                header,
429
                f"VCS cheat sheet: {cheat}.",
430
                "Use the current checkout; do not create another workspace.",
431
                "Leave the working tree clean after the final snapshot.",
432
                "",
433
            ]
434
        )
435
    elif subject.kind == "git":
436
        sem = semantics()
437
        status_command = sem.status_display("git", track)
438
        diff_command = sem.diff_display("git", track)
439
        text = "\n".join(
440
            [
441
                "# AGENTS.md",
442
                "",
443
                "This benchmark workspace uses Git.",
444
                "Use the current checkout; do not create another clone or worktree.",
445
                f"Before snapshotting, inspect `{status_command}` and `{diff_command}`.",
446
                "Snapshot final work with `git add .` and `git commit -m \"agent task\"`.",
447
                "Leave the working tree clean.",
448
                "",
449
            ]
450
        )
451
    else:
452
        text = "\n".join(
453
            [
454
                "# AGENTS.md",
455
                "",
456
                "This benchmark workspace uses Oak, not Git.",
457
                "Do not run `git` commands.",
458
                "Use the current Oak checkout; do not create another mount or space.",
459
                "Before snapshotting, inspect `oak status` and `oak diff`.",
460
                "Snapshot final work with `oak commit --no-verify`.",
461
                "Leave the working tree clean.",
462
                "",
463
            ]
464
        )
465
    (repo / "AGENTS.md").write_text(text)
466
467
468
def run_command(
469
    command: list[str],
470
    cwd: Path,
471
    timeout: float = 120.0,
472
    env: dict[str, str] | None = None,
473
) -> subprocess.CompletedProcess[str]:
474
    return subprocess.run(
475
        command,
476
        cwd=cwd,
477
        env=sanitized_agent_env(env if env is not None else workflow_ab.base_env()),
478
        text=True,
479
        stdout=subprocess.PIPE,
480
        stderr=subprocess.PIPE,
481
        timeout=timeout,
482
        check=False,
483
    )
484
485
486
def initialize_repo(subject: workflow_ab.Subject, repo: Path) -> tuple[float, str, int]:
487
    start = time.perf_counter()
488
    output: list[str] = []
489
    commands: list[list[str]]
490
    if subject.kind == "git":
491
        vcs = str(subject.bin)
492
        commands = [
493
            [vcs, "init"],
494
            [vcs, "add", "."],
495
            [vcs, "commit", "-m", "initial"],
496
        ]
497
    else:
498
        vcs = str(subject.bin)
499
        commands = [
500
            [vcs, "init", "."],
501
            [vcs, "commit", "--no-verify"],
502
        ]
503
504
    returncode = 0
505
    for command in commands:
506
        proc = run_command(command, repo)
507
        output.append("$ " + workflow_ab.command_display(command))
508
        if proc.stdout:
509
            output.append(proc.stdout)
510
        if proc.stderr:
511
            output.append(proc.stderr)
512
        if proc.returncode != 0:
513
            returncode = proc.returncode
514
            break
515
    return (time.perf_counter() - start) * 1000.0, "\n".join(output), returncode
516
517
518
def commit_count(subject: workflow_ab.Subject, repo: Path) -> int | None:
519
    if subject.kind == "git":
520
        text = command_output([str(subject.bin), "rev-list", "--count", "HEAD"], repo)
521
        if text and text.isdigit():
522
            return int(text)
523
        return None
524
    text = command_output([str(subject.bin), "log", "--json"], repo)
525
    if text is None:
526
        return None
527
    try:
528
        commits = json.loads(text)
529
    except (ValueError, TypeError):
530
        return None
531
    if not isinstance(commits, list) or any(
532
        not isinstance(commit, dict)
533
        or not isinstance(commit.get("hash"), str)
534
        or not re.fullmatch(r"[0-9a-f]{64}", commit["hash"])
535
        for commit in commits
536
    ):
537
        return None
538
    return len(commits)
539
540
541
def vcs_status(subject: workflow_ab.Subject, repo: Path) -> tuple[str, int | None, float]:
542
    start = time.perf_counter()
543
    if subject.kind == "git":
544
        proc = run_command([str(subject.bin), "status", "--porcelain=v1"], repo)
545
        text = proc.stdout + proc.stderr
546
        dirty = len([line for line in text.splitlines() if line.strip()]) if proc.returncode == 0 else None
547
    else:
548
        proc = run_command([str(subject.bin), "status", "--json"], repo)
549
        text = proc.stdout + proc.stderr
550
        dirty = None
551
        if proc.returncode == 0:
552
            try:
553
                state = json.loads(proc.stdout)
554
            except (ValueError, TypeError):
555
                state = None
556
            changes = state.get("changes") if isinstance(state, dict) else None
557
            if isinstance(changes, list) and all(
558
                isinstance(change, dict)
559
                and isinstance(change.get("path"), str)
560
                and isinstance(change.get("status"), str)
561
                for change in changes
562
            ):
563
                dirty = len(changes)
564
    return text, dirty, (time.perf_counter() - start) * 1000.0
565
566
567
def test_command_for(workflow: workflow_ab.Workflow, subject: workflow_ab.Subject | None = None) -> list[str]:
568
    if workflow.name in workflow_oracles.SCENARIOS:
569
        return [sys.executable, "-I", str(Path(workflow_oracles.__file__).resolve()), workflow.name, ".",
570
                "--evidence-json", *(["--git-head", "--binary", str(subject.bin)] if subject is not None and subject.kind == "git"
571
                else ["--oak-head", "--binary", str(subject.bin)] if subject is not None and subject.kind == "oak" else []),
572
                *(["--git-instrument", os.environ["OAK_BENCH_GIT_INSTRUMENT"]] if os.environ.get("OAK_BENCH_GIT_INSTRUMENT") else []),
573
                *(["--oak-reader-python", os.environ["OAK_BENCH_OAK_READER_PYTHON"]] if os.environ.get("OAK_BENCH_OAK_READER_PYTHON") else []),
574
                *(["--oak-reader-deadline-scale", os.environ["OAK_BENCH_READER_DEADLINE_SCALE"]] if os.environ.get("OAK_BENCH_READER_DEADLINE_SCALE") else [])]
575
    return ["python3", "-c", "raise SystemExit(0)"]
576
577
578
def build_prompt(
579
    subject: workflow_ab.Subject,
580
    workflow: workflow_ab.Workflow,
581
    track: str,
582
    instruction_level: str,
583
) -> str:
584
    if instruction_level == "zero-shot":
585
        if subject.kind == "git":
586
            vcs_lines = [
587
                "This repository uses Git.",
588
                "Do not create another workspace.",
589
                "Snapshot your final work and leave the working tree clean.",
590
            ]
591
        else:
592
            vcs_lines = [
593
                "This repository uses Oak (a version control system), not Git.",
594
                "Do not run `git` commands and do not create another workspace.",
595
                "Snapshot your final work with Oak and leave the working tree clean.",
596
            ]
597
    elif instruction_level == "cheat-sheet":
598
        if subject.kind == "git":
599
            vcs_lines = [
600
                "This repository uses Git. Do not create another workspace.",
601
                "Cheat sheet: `git status --short`, `git diff --stat`, "
602
                "`git add . && git commit -m \"agent task\"`.",
603
            ]
604
        else:
605
            vcs_lines = [
606
                "This repository uses Oak, not Git. Do not run `git` commands.",
607
                "Cheat sheet: `oak status`, `oak diff`, `oak commit --no-verify`.",
608
            ]
609
    elif subject.kind == "git":
610
        sem = semantics()
611
        status_command = sem.status_display("git", track)
612
        diff_command = sem.diff_display("git", track)
613
        vcs_lines = [
614
            "This repository uses Git.",
615
            "Do not create another clone or worktree.",
616
            f"Before the final commit, inspect `{status_command}` and `{diff_command}`.",
617
            "Commit with `git add .` and `git commit -m \"agent task\"`.",
618
        ]
619
    else:
620
        vcs_lines = [
621
            "This repository uses Oak, not Git.",
622
            "Do not run `git` commands.",
623
            "Do not create another mount or space.",
624
            "Before the final snapshot, inspect `oak status` and `oak diff`.",
625
            "Snapshot with `oak commit --no-verify`.",
626
        ]
627
628
    if workflow.name == "bugfix_test_loop":
629
        task = (
630
            "Fix the failing pricing unit test by making the smallest reasonable code change. "
631
            "Run the test before changing code if possible, make the fix, then rerun the test."
632
        )
633
        success = [
634
            "`python3 -m unittest discover -s tests` passes.",
635
            "Only the necessary source file changes.",
636
        ]
637
    elif workflow.name == "wide_config_refactor":
638
        task = (
639
            "Update all service configs using the deprecated timeout value so validation passes: "
640
            "replace the deprecated value with `timeout_ms = 3000`. Avoid unrelated file changes."
641
        )
642
        success = ["`python3 validate_configs.py` passes.", "Only matching service config files change."]
643
    elif workflow.name == "large_asset_manifest":
644
        task = (
645
            "Inspect the manifest and mark every listed asset reviewed without rewriting binary assets. "
646
            "Avoid dumping large binary files into context."
647
        )
648
        success = ["`python3 validate_manifest.py` passes.", "Only manifest.json changes."]
649
    else:
650
        task = workflow.description
651
        success = ["The fixture validator passes.", "Unrelated files are not changed."]
652
653
    lines = [
654
        "You are running inside an isolated benchmark workspace.",
655
        "Use local files and local commands only. Do not use network access.",
656
        "Keep the final answer concise; the benchmark oracle checks the repository state.",
657
        "",
658
        "Task:",
659
        task,
660
        "",
661
        "Version-control rules:",
662
        *vcs_lines,
663
        "",
664
        "Success criteria:",
665
        *["- " + item for item in success],
666
        "- The final VCS state is clean after the commit/snapshot.",
667
        "",
668
        "Do the work now.",
669
    ]
670
    return "\n".join(lines) + "\n"
671
672
673
def provider_api_error(adapter: str, stdout_text: str) -> str | None:
674
    """Provider-side failure reported by the agent CLI, e.g. auth, rate limit, overload.
675
676
    The provider, not the agent or the VCS, ended such a trial, so it is an
677
    infrastructure error and must never count as a task failure. Only the
678
    Claude stream-json result event reports this today; other adapters return
679
    None (unmeasured, not "no error").
680
    """
681
    if adapter != "claude_print_stream_json":
682
        return None
683
    for line in reversed(stdout_text.splitlines()):
684
        line = line.strip()
685
        if not line.startswith("{") or '"result"' not in line:
686
            continue
687
        try:
688
            event = json.loads(line)
689
        except ValueError:
690
            continue
691
        if not isinstance(event, dict) or event.get("type") != "result":
692
            continue
693
        status = event.get("api_error_status")
694
        if status is not None or event.get("terminal_reason") == "api_error":
695
            return f"provider_api_error:{status if status is not None else 'unknown'}"
696
        return None
697
    return None
698
699
700
def build_agent_command(
701
    agent: AgentConfig,
702
    repo: Path,
703
    prompt: str,
704
    agent_environment: str,
705
) -> tuple[list[str], str | None]:
706
    if agent.adapter == "deterministic_mock":
707
        return [], None
708
    if agent.bin is None:
709
        raise RuntimeError(f"Agent {agent.name} has no binary")
710
711
    model_args: list[str] = []
712
    if agent.model:
713
        model_args = ["--model", agent.model]
714
    minimal = agent_environment == "minimal"
715
716
    if agent.adapter == "codex_exec_json":
717
        command = [
718
            str(agent.bin),
719
            "exec",
720
            "--json",
721
            "--color",
722
            "never",
723
            "-C",
724
            str(repo),
725
            "--skip-git-repo-check",
726
            "--ephemeral",
727
            "--sandbox",
728
            "danger-full-access",
729
            "--dangerously-bypass-approvals-and-sandbox",
730
            *(["--ignore-user-config", "--ignore-rules"] if minimal else []),
731
            *model_args,
732
            "-",
733
        ]
734
        return command, prompt
735
736
    if agent.adapter == "claude_print_stream_json":
737
        command = [
738
            str(agent.bin),
739
            "-p",
740
            "--output-format",
741
            "stream-json",
742
            # Required by the CLI for stream-json with --print; verified
743
            # against claude 2.1.170 (without it the run exits immediately).
744
            "--verbose",
745
            "--permission-mode",
746
            "bypassPermissions",
747
            "--dangerously-skip-permissions",
748
            "--no-session-persistence",
749
            *(["--safe-mode", "--disable-slash-commands"] if minimal else []),
750
            *model_args,
751
            prompt,
752
        ]
753
        return command, None
754
755
    if agent.adapter == "cursor_agent_stream_json":
756
        command = [
757
            str(agent.bin),
758
            "--print",
759
            "--output-format",
760
            "stream-json",
761
            "--force",
762
            "--trust",
763
            "--sandbox",
764
            "disabled",
765
            "--workspace",
766
            str(repo),
767
            *model_args,
768
            prompt,
769
        ]
770
        return command, None
771
772
    raise RuntimeError(f"Unsupported adapter: {agent.adapter}")
773
774
775
def run_mock_agent(
776
    subject: workflow_ab.Subject,
777
    workflow: workflow_ab.Workflow,
778
    repo: Path,
779
    track: str,
780
    artifacts: Path,
781
    prompt_path: Path,
782
    env: dict[str, str] | None = None,
783
) -> AgentExecution:
784
    stdout_path = artifacts / "agent.stdout.log"
785
    stderr_path = artifacts / "agent.stderr.log"
786
    start = time.perf_counter()
787
    stdout_parts: list[str] = []
788
    stderr_parts: list[str] = []
789
    returncode = 0
790
    for step in workflow.steps(subject, track):
791
        proc = run_command(step.command, repo, env=workflow_ab.step_env(step, env))
792
        stdout_parts.append("$ " + workflow_ab.command_display(step.command))
793
        if proc.stdout:
794
            stdout_parts.append(proc.stdout)
795
        if proc.stderr:
796
            stderr_parts.append(proc.stderr)
797
        if proc.returncode not in step.expected_returncodes:
798
            returncode = proc.returncode or 1
799
            break
800
    elapsed_ms = (time.perf_counter() - start) * 1000.0
801
    stdout_path.write_text("\n".join(stdout_parts))
802
    stderr_path.write_text("\n".join(stderr_parts))
803
    return AgentExecution(returncode, False, elapsed_ms, stdout_path, stderr_path, prompt_path)
804
805
806
def run_real_agent(
807
    agent: AgentConfig,
808
    repo: Path,
809
    prompt: str,
810
    artifacts: Path,
811
    timeout_seconds: float,
812
    agent_environment: str,
813
    env: dict[str, str] | None = None,
814
    output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES,
815
) -> AgentExecution:
816
    artifacts.mkdir(parents=True, exist_ok=True)
817
    prompt_path = artifacts / "prompt.txt"
818
    stdout_path = artifacts / "agent.stdout.log"
819
    stderr_path = artifacts / "agent.stderr.log"
820
    prompt_path.write_text(prompt)
821
822
    if agent.adapter == "deterministic_mock":
823
        raise RuntimeError("mock agent is handled separately")
824
825
    command, stdin_text = build_agent_command(agent, repo, prompt, agent_environment)
826
    if env is None:
827
        env, environment_metadata = trial_agent_env(artifacts)
828
    else:
829
        env = sanitized_agent_env(env)
830
        environment_metadata = {"fresh_agent_home": env.get("HOME"),
831
                                "environment_policy": "caller-supplied-sanitized-git",
832
                                "os_sandbox_enforced": False}
833
    result = run_captured(command, repo, env, stdin_text, stdout_path, stderr_path,
834
                          timeout_seconds, output_limit_bytes)
835
    capture_metadata = {
836
        "execution_version": EXECUTION_VERSION, "timeout_seconds": timeout_seconds,
837
        "output_limit_bytes": output_limit_bytes, "command": command,
838
        "stdout_observed_bytes": result.stdout_observed_bytes,
839
        "stderr_observed_bytes": result.stderr_observed_bytes,
840
        "stdout_retained_bytes": result.stdout_retained_bytes,
841
        "stderr_retained_bytes": result.stderr_retained_bytes,
842
        "capture_complete": result.capture_complete,
843
        "output_limited": result.output_limited,
844
        "byte_measurement": "observed_pipe_bytes; lower_bound_if_capture_incomplete",
845
        "cleanup_scope": "owned_posix_process_group" if os.name == "posix" else "direct_child_only",
846
        **environment_metadata,
847
    }
848
    (artifacts / "execution.json").write_text(json.dumps(capture_metadata, sort_keys=True) + "\n")
849
    return AgentExecution(result.returncode, result.timed_out, result.elapsed_ms,
850
                          stdout_path, stderr_path, prompt_path, result.output_limited,
851
                          result.capture_complete, capture_metadata)
852
853
854
def read_text(path: Path, byte_limit: int = DEFAULT_OUTPUT_LIMIT_BYTES) -> str:
855
    try:
856
        with path.open("rb") as handle:
857
            return handle.read(byte_limit).decode("utf-8", "replace")
858
    except FileNotFoundError:
859
        return ""
860
861
862
def parse_json_lines(text: str) -> list[Any]:
863
    events: list[Any] = []
864
    for line in text.splitlines():
865
        stripped = line.strip()
866
        if not stripped or not stripped.startswith(("{", "[")):
867
            continue
868
        try:
869
            events.append(json.loads(stripped))
870
        except json.JSONDecodeError:
871
            continue
872
    return events
873
874
875
def collect_usage(events: list[Any]) -> dict[str, int | None]:
876
    """Provider-reported usage, snake_case first.
877
878
    camelCase keys (cursor-agent 2026.06 reports {inputTokens, outputTokens,
879
    cacheReadTokens, cacheWriteTokens}) are a FALLBACK pass, never merged with
880
    snake_case: claude's result event carries both `usage` (snake_case) and a
881
    per-model `modelUsage` (camelCase) breakdown of the same tokens, and
882
    summing both would double-count.
883
    """
884
    snake = _collect_usage_with_keys(
885
        events,
886
        input_keys=("input_tokens", "prompt_tokens", "inputTokenCount", "promptTokens"),
887
        output_keys=("output_tokens", "completion_tokens", "outputTokenCount", "completionTokens"),
888
        reasoning_keys=("reasoning_tokens", "reasoning_output_tokens", "reasoningTokenCount"),
889
        cache_read_keys=("cache_read_input_tokens", "cache_read_tokens", "cached_tokens", "cached_input_tokens"),
890
        cache_write_keys=("cache_creation_input_tokens", "cache_write_tokens"),
891
        total_keys=("total_tokens", "totalTokens", "tokens"),
892
    )
893
    if any(value is not None for value in snake.values()):
894
        return snake
895
    return _collect_usage_with_keys(
896
        events,
897
        input_keys=("inputTokens",),
898
        output_keys=("outputTokens",),
899
        reasoning_keys=("reasoningTokens",),
900
        cache_read_keys=("cacheReadTokens", "cacheReadInputTokens"),
901
        cache_write_keys=("cacheWriteTokens", "cacheCreationInputTokens"),
902
        total_keys=(),
903
    )
904
905
906
def _collect_usage_with_keys(
907
    events: list[Any],
908
    *,
909
    input_keys: tuple[str, ...],
910
    output_keys: tuple[str, ...],
911
    reasoning_keys: tuple[str, ...],
912
    cache_read_keys: tuple[str, ...],
913
    cache_write_keys: tuple[str, ...],
914
    total_keys: tuple[str, ...],
915
) -> dict[str, int | None]:
916
917
    # Per-field None until that field is actually observed: a stream that
918
    # exposes only total_tokens must not report input/output/reasoning/cache
919
    # as 0 — that is a fabricated zero (ADR-0002) and silently corrupts
920
    # cost_weighted_total.
921
    totals: dict[str, int | None] = {
922
        "input_tokens_reported": None,
923
        "output_tokens_reported": None,
924
        "reasoning_tokens_reported": None,
925
        "cache_read_tokens_reported": None,
926
        "cache_write_tokens_reported": None,
927
        "total_tokens_reported": None,
928
    }
929
930
    result_totals = _collect_result_usage_with_keys(
931
        events,
932
        input_keys=input_keys,
933
        output_keys=output_keys,
934
        reasoning_keys=reasoning_keys,
935
        cache_read_keys=cache_read_keys,
936
        cache_write_keys=cache_write_keys,
937
        total_keys=total_keys,
938
    )
939
    if result_totals is not None:
940
        return result_totals
941
942
    for event in events:
943
        for item in walk_json(event):
944
            if not isinstance(item, dict):
945
                continue
946
            direct_keys = set(item)
947
            known = set(input_keys + output_keys + reasoning_keys + cache_read_keys + cache_write_keys + total_keys)
948
            if not direct_keys.intersection(known):
949
                continue
950
            values = {
951
                "input_tokens_reported": first_number(item, input_keys),
952
                "output_tokens_reported": first_number(item, output_keys),
953
                "reasoning_tokens_reported": first_number(item, reasoning_keys),
954
                "cache_read_tokens_reported": first_number(item, cache_read_keys),
955
                "cache_write_tokens_reported": first_number(item, cache_write_keys),
956
                "total_tokens_reported": first_number(item, total_keys),
957
            }
958
            for key, value in values.items():
959
                if value is not None:
960
                    totals[key] = (totals[key] or 0) + value
961
962
    if totals["total_tokens_reported"] is None:
963
        components = [
964
            totals["input_tokens_reported"],
965
            totals["output_tokens_reported"],
966
            totals["reasoning_tokens_reported"],
967
        ]
968
        if any(component is not None for component in components):
969
                totals["total_tokens_reported"] = sum(component or 0 for component in components)
970
    return totals
971
972
973
def _collect_result_usage_with_keys(
974
    events: list[Any],
975
    *,
976
    input_keys: tuple[str, ...],
977
    output_keys: tuple[str, ...],
978
    reasoning_keys: tuple[str, ...],
979
    cache_read_keys: tuple[str, ...],
980
    cache_write_keys: tuple[str, ...],
981
    total_keys: tuple[str, ...],
982
) -> dict[str, int | None] | None:
983
    """Return cumulative provider totals from top-level result.usage.
984
985
    Claude repeats the same message.usage across assistant content-block
986
    events, then emits the cumulative run total in result.usage. That result
987
    usage may also contain per-iteration usage beneath it, so this intentionally
988
    reads only direct keys from the top-level usage object.
989
    """
990
991
    for event in reversed(events):
992
        if not isinstance(event, dict) or str(event.get("type") or "").lower() != "result":
993
            continue
994
        usage = event.get("usage")
995
        if not isinstance(usage, dict):
996
            continue
997
        values = {
998
            "input_tokens_reported": first_number(usage, input_keys),
999
            "output_tokens_reported": first_number(usage, output_keys),
1000
            "reasoning_tokens_reported": first_number(usage, reasoning_keys),
1001
            "cache_read_tokens_reported": first_number(usage, cache_read_keys),
1002
            "cache_write_tokens_reported": first_number(usage, cache_write_keys),
1003
            "total_tokens_reported": first_number(usage, total_keys),
1004
        }
1005
        if not any(value is not None for value in values.values()):
1006
            continue
1007
        if values["total_tokens_reported"] is None:
1008
            components = [
1009
                values["input_tokens_reported"],
1010
                values["output_tokens_reported"],
1011
                values["reasoning_tokens_reported"],
1012
            ]
1013
            if any(component is not None for component in components):
1014
                values["total_tokens_reported"] = sum(component or 0 for component in components)
1015
        return values
1016
    return None
1017
1018
1019
def extract_text_chars(events: list[Any], fallback: str) -> int:
1020
    texts: list[str] = []
1021
    text_keys = {"text", "message", "delta", "summary", "result", "final_response"}
1022
    for event in events:
1023
        for item in walk_json(event):
1024
            if not isinstance(item, dict):
1025
                continue
1026
            for key, value in item.items():
1027
                if key in text_keys and isinstance(value, str):
1028
                    texts.append(value)
1029
                elif key == "content" and isinstance(value, str):
1030
                    texts.append(value)
1031
    if texts:
1032
        return sum(len(text) for text in texts)
1033
    return len(fallback)
1034
1035
1036
def cost_weighted_total_from_usage(
1037
    usage: dict[str, int | None],
1038
    *,
1039
    cache_read_included_in_input: bool,
1040
) -> float | None:
1041
    has_direction_components = any(
1042
        usage.get(key) is not None
1043
        for key in ("input_tokens_reported", "output_tokens_reported", "reasoning_tokens_reported")
1044
    )
1045
    if not has_direction_components:
1046
        return None
1047
1048
    emitted = (usage.get("output_tokens_reported") or 0) + (usage.get("reasoning_tokens_reported") or 0)
1049
    ingested = usage.get("input_tokens_reported") or 0
1050
    cache_read = usage.get("cache_read_tokens_reported") or 0
1051
    cache_write = usage.get("cache_write_tokens_reported") or 0
1052
    if cache_read_included_in_input:
1053
        ingested = max(0, ingested - cache_read)
1054
    return round(
1055
        emitted * EMITTED_TOKEN_WEIGHT
1056
        + ingested * INGESTED_TOKEN_WEIGHT
1057
        + cache_read * CACHE_READ_TOKEN_WEIGHT
1058
        + cache_write * INGESTED_TOKEN_WEIGHT,
1059
        1,
1060
    )
1061
1062
1063
def cursor_tool_call_parts(event: Any) -> tuple[str, str | None] | None:
1064
    if not isinstance(event, dict) or str(event.get("type") or "").lower() != "tool_call":
1065
        return None
1066
    tool_call = event.get("tool_call")
1067
    if not isinstance(tool_call, dict):
1068
        return None
1069
    tool_name = next((key for key in tool_call if key.endswith("ToolCall")), None)
1070
    if tool_name is None:
1071
        return None
1072
    payload = tool_call.get(tool_name)
1073
    if not isinstance(payload, dict):
1074
        return tool_name, None
1075
    args = payload.get("args")
1076
    if isinstance(args, dict) and isinstance(args.get("command"), str):
1077
        return tool_name, unwrap_shell_command(args["command"])
1078
    result = payload.get("result")
1079
    if isinstance(result, dict):
1080
        shell_result = result.get("success") or result.get("failure")
1081
        if isinstance(shell_result, dict) and isinstance(shell_result.get("command"), str):
1082
            return tool_name, unwrap_shell_command(shell_result["command"])
1083
    return tool_name, None
1084
1085
1086
def collect_tool_metrics(stdout_text: str, stderr_text: str, events: list[Any]) -> tuple[dict[str, int], dict[str, int]]:
1087
    """One tool call counts exactly once.
1088
1089
    A Claude-style tool_use block carries name + input.command in one item;
1090
    the old walker counted the name, the input command, and the inner input
1091
    dict's command again — 3 tool_calls_total per actual call. Commands that
1092
    belong to a counted tool_use go to attached_commands: classified for
1093
    kind/VCS/help counts but never re-counted as separate calls.
1094
    """
1095
    tool_names: list[str] = []
1096
    commands: list[str] = []
1097
    attached_commands: list[str] = []
1098
    consumed_input_ids: set[int] = set()
1099
1100
    for event in events:
1101
        cursor_call = cursor_tool_call_parts(event)
1102
        if cursor_call is not None:
1103
            if str(event.get("subtype") or "").lower() == "started":
1104
                tool_name, command = cursor_call
1105
                tool_names.append(tool_name)
1106
                if command is not None:
1107
                    attached_commands.append(command)
1108
            continue
1109
1110
        for item in walk_json(event):
1111
            if not isinstance(item, dict):
1112
                continue
1113
            item_type = str(item.get("type") or item.get("event") or "").lower()
1114
            name = item.get("name") or item.get("tool_name") or item.get("tool")
1115
            if item_type == "file_change" and str(item.get("status") or "").lower() == "completed":
1116
                tool_names.append("file_change")
1117
            is_tool_call_item = isinstance(name, str) and (
1118
                "tool" in item_type or item_type in {"function_call", "function"}
1119
            )
1120
            if is_tool_call_item:
1121
                tool_names.append(name)
1122
            input_value = item.get("input")
1123
            if isinstance(input_value, dict):
1124
                inner_command = input_value.get("command") or input_value.get("cmd")
1125
                if isinstance(inner_command, str):
1126
                    # The walker will visit this input dict again; mark it so
1127
                    # its command is not re-counted as a standalone call.
1128
                    consumed_input_ids.add(id(input_value))
1129
                    if is_tool_call_item:
1130
                        attached_commands.append(unwrap_shell_command(inner_command))
1131
                    else:
1132
                        commands.append(unwrap_shell_command(inner_command))
1133
            if id(item) in consumed_input_ids:
1134
                continue
1135
            command = item.get("command") or item.get("cmd")
1136
            if isinstance(command, str):
1137
                status = str(item.get("status") or "").lower()
1138
                exit_code = item.get("exit_code")
1139
                if item.get("type") != "command_execution" or status not in {"in_progress", "queued"} or exit_code is not None:
1140
                    if is_tool_call_item:
1141
                        attached_commands.append(unwrap_shell_command(command))
1142
                    else:
1143
                        commands.append(unwrap_shell_command(command))
1144
1145
    for line in (stdout_text + "\n" + stderr_text).splitlines():
1146
        if line.startswith("$ "):
1147
            commands.append(unwrap_shell_command(line[2:]))
1148
1149
    counts = {
1150
        "tool_calls_total": 0,
1151
        "terminal_commands_total": 0,
1152
        "file_read_calls": 0,
1153
        "file_write_calls": 0,
1154
        "search_calls": 0,
1155
        "edit_calls": 0,
1156
        "vcs_commands_total": 0,
1157
        "test_commands_total": 0,
1158
        "network_calls_total": 0,
1159
        "privileged_calls_total": 0,
1160
        "help_calls_total": 0,
1161
    }
1162
    by_kind: dict[str, int] = {}
1163
1164
    for name in tool_names:
1165
        lowered = name.lower()
1166
        by_kind[lowered] = by_kind.get(lowered, 0) + 1
1167
        counts["tool_calls_total"] += 1
1168
        if lowered in {"bash", "shell", "terminal", "exec_command", "run_terminal_cmd"} or "shell" in lowered:
1169
            counts["terminal_commands_total"] += 1
1170
        if "read" in lowered:
1171
            counts["file_read_calls"] += 1
1172
        if "edit" in lowered or "write" in lowered or lowered == "file_change":
1173
            counts["edit_calls"] += 1
1174
            counts["file_write_calls"] += 1
1175
        if "search" in lowered or "grep" in lowered or "glob" in lowered:
1176
            counts["search_calls"] += 1
1177
1178
    def classify_into_counts(command: str, counts_as_call: bool) -> None:
1179
        kinds = classify_command(command)
1180
        if counts_as_call:
1181
            counts["tool_calls_total"] += 1
1182
            for kind in kinds:
1183
                by_kind[kind] = by_kind.get(kind, 0) + 1
1184
            if "terminal" in kinds:
1185
                counts["terminal_commands_total"] += 1
1186
        if "read" in kinds:
1187
            counts["file_read_calls"] += 1
1188
        if "file_write" in kinds:
1189
            counts["file_write_calls"] += 1
1190
        if "search" in kinds:
1191
            counts["search_calls"] += 1
1192
        if "edit" in kinds:
1193
            counts["edit_calls"] += 1
1194
        if "vcs" in kinds:
1195
            counts["vcs_commands_total"] += 1
1196
        if "test" in kinds:
1197
            counts["test_commands_total"] += 1
1198
        if "help" in kinds:
1199
            counts["help_calls_total"] += 1
1200
        if re.search(r"\b(curl|wget|gh api|npm install|pip install)\b", command):
1201
            counts["network_calls_total"] += 1
1202
        if re.search(r"\b(sudo|su\s+-)\b", command):
1203
            counts["privileged_calls_total"] += 1
1204
1205
    for command in commands:
1206
        classify_into_counts(command, counts_as_call=True)
1207
    for command in attached_commands:
1208
        # The call was already counted via its tool_use name; only the
1209
        # command's nature (VCS/test/help/...) still needs attribution.
1210
        classify_into_counts(command, counts_as_call=False)
1211
1212
    return counts, by_kind
1213
1214
1215
# PATH-shim VCS attribution fields, merged into vcs_metrics. Metric nulls carry
1216
# explicit reasons (ADR-0002: unmeasured is null, never zero). Shim overhead is
1217
# recorded, never subtracted.
1218
SHIM_REASON_FIELDS = (
1219
    "shim_sidecar_path_unavailable_reason",
1220
    "shim_overhead_unavailable_reason",
1221
    "vcs_ms_unavailable_reason",
1222
    "vcs_call_count_shim_unavailable_reason",
1223
    "agent_blocked_on_vcs_ms_unavailable_reason",
1224
    "vcs_share_of_task_wall_unavailable_reason",
1225
    "thrash_events_count_unavailable_reason",
1226
    "polling_loop_count_unavailable_reason",
1227
)
1228
1229
SHIM_NULL_VALUES: dict[str, Any] = {
1230
    "shim_sidecar_path": None,
1231
    "shim_overhead": None,
1232
    "shim_overhead_ms": None,
1233
    "vcs_ms": None,
1234
    "vcs_call_count_shim": None,
1235
    "agent_blocked_on_vcs_ms": None,
1236
    "vcs_share_of_task_wall": None,
1237
    "thrash_events_count": None,
1238
    "polling_loop_count": None,
1239
}
1240
1241
1242
def shim_metrics_unavailable(reason: str) -> dict[str, Any]:
1243
    fields = dict(SHIM_NULL_VALUES)
1244
    for key in SHIM_REASON_FIELDS:
1245
        fields[key] = reason
1246
    return fields
1247
1248
1249
def shim_real_binaries(subject: workflow_ab.Subject) -> dict[str, str]:
1250
    """Real binaries to wrap: the subject's VCS, plus git if discoverable."""
1251
    real: dict[str, str] = {}
1252
    from oakbench.subjects import which_measured_git
1253
    git_found = which_measured_git()
1254
    if git_found:
1255
        real["git"] = git_found
1256
    if subject.kind in ("git", "oak") and subject.bin is not None and Path(subject.bin).exists():
1257
        real[subject.kind] = str(subject.bin)
1258
    return real
1259
1260
1261
def shim_metrics_from_sidecar(
1262
    sidecar: Path,
1263
    shim_overhead_ms: float | None,
1264
    task_wall_ms: float,
1265
) -> dict[str, Any]:
1266
    """Shim-attributed VCS fields from the sidecar JSONL, with null reasons."""
1267
    fields = shim_metrics_unavailable("sidecar_empty")
1268
    fields["shim_sidecar_path"] = str(sidecar)
1269
    fields["shim_sidecar_path_unavailable_reason"] = None
1270
    fields["shim_overhead"] = shim_overhead_ms
1271
    fields["shim_overhead_ms"] = shim_overhead_ms
1272
    fields["shim_overhead_unavailable_reason"] = (
1273
        None if shim_overhead_ms is not None else "shim_overhead_unmeasured"
1274
    )
1275
    rows = read_sidecar_rows(sidecar)
1276
    if not rows:
1277
        return fields
1278
1279
    fields["vcs_call_count_shim"] = len(rows)
1280
    fields["vcs_call_count_shim_unavailable_reason"] = None
1281
1282
    elapsed = [row.get("elapsed_ms") for row in rows]
1283
    measured = [value for value in elapsed if isinstance(value, (int, float)) and not isinstance(value, bool)]
1284
    if measured:
1285
        fields["vcs_ms"] = round(sum(measured), 3)
1286
        fields["vcs_ms_unavailable_reason"] = None
1287
    else:
1288
        fields["vcs_ms_unavailable_reason"] = "sidecar_rows_missing_elapsed_ms"
1289
1290
    blocked = agent_blocked_on_vcs_ms(rows)
1291
    fields["agent_blocked_on_vcs_ms"] = blocked
1292
    fields["agent_blocked_on_vcs_ms_unavailable_reason"] = (
1293
        None if blocked is not None else "sidecar_rows_missing_vcs_timing_or_command"
1294
    )
1295
    fields["vcs_share_of_task_wall"] = vcs_share_of_task_wall(blocked, task_wall_ms)
1296
    if fields["vcs_share_of_task_wall"] is not None:
1297
        fields["vcs_share_of_task_wall_unavailable_reason"] = None
1298
    elif blocked is None:
1299
        fields["vcs_share_of_task_wall_unavailable_reason"] = "agent_blocked_on_vcs_ms_unavailable"
1300
    else:
1301
        fields["vcs_share_of_task_wall_unavailable_reason"] = "task_wall_ms_unavailable"
1302
1303
    events = thrash_events(rows)
1304
    if events is None:
1305
        fields["thrash_events_count_unavailable_reason"] = "sidecar_rows_missing_vcs_timestamp_or_command"
1306
        fields["polling_loop_count_unavailable_reason"] = "sidecar_rows_missing_vcs_timestamp_or_command"
1307
    else:
1308
        fields["thrash_events_count"] = len(events)
1309
        fields["polling_loop_count"] = sum(1 for event in events if event.get("type") == "vcs_polling_loop")
1310
        fields["thrash_events_count_unavailable_reason"] = None
1311
        fields["polling_loop_count_unavailable_reason"] = None
1312
    return fields
1313
1314
1315
def vcs_metrics_from_tools(
1316
    subject: workflow_ab.Subject,
1317
    stdout_text: str,
1318
    stderr_text: str,
1319
    dirty_files: int | None,
1320
    commit_delta: int,
1321
) -> dict[str, Any]:
1322
    text = stdout_text + "\n" + stderr_text
1323
    commands = [unwrap_shell_command(line[2:]) for line in text.splitlines() if line.startswith("$ ")]
1324
    events = parse_json_lines(text)
1325
    for event in events:
1326
        cursor_call = cursor_tool_call_parts(event)
1327
        if cursor_call is not None:
1328
            if str(event.get("subtype") or "").lower() == "started":
1329
                _, command = cursor_call
1330
                if command is not None:
1331
                    commands.append(command)
1332
            continue
1333
1334
        for item in walk_json(event):
1335
            if not isinstance(item, dict):
1336
                continue
1337
            if str(item.get("type") or "").lower() == "tool_use":
1338
                name = str(item.get("name") or item.get("tool_name") or item.get("tool") or "").lower()
1339
                input_value = item.get("input")
1340
                command = input_value.get("command") if isinstance(input_value, dict) else None
1341
                if isinstance(command, str) and name in {"bash", "shell", "terminal"}:
1342
                    commands.append(unwrap_shell_command(command))
1343
                continue
1344
            if item.get("type") != "command_execution":
1345
                continue
1346
            status = str(item.get("status") or "").lower()
1347
            if status in {"in_progress", "queued"} and item.get("exit_code") is None:
1348
                continue
1349
            command = item.get("command")
1350
            if isinstance(command, str):
1351
                commands.append(unwrap_shell_command(command))
1352
    commands_available = bool(commands)
1353
    # One classification authority: every count below derives from the SAME
1354
    # command list through oakbench.classify.vcs_invocations, so sub-counts can
1355
    # never disagree with the total (the reviewer-found vcs_commands_total=0
1356
    # alongside status_commands=1). Sub-counts are a family breakdown, not a
1357
    # partition — add/log/etc. count in the total only.
1358
    invocations = [
1359
        (segment, subcommand)
1360
        for command in commands
1361
        for segment, subcommand in vcs_invocations(command)
1362
    ]
1363
    subcommands = [subcommand for _, subcommand in invocations]
1364
    commands_total = sum(1 for subcommand in subcommands if subcommand is not None) if commands_available else None
1365
    status_commands = sum(1 for subcommand in subcommands if subcommand == "status") if commands_available else None
1366
    diff_commands = sum(1 for subcommand in subcommands if subcommand == "diff") if commands_available else None
1367
    snapshot_commands = sum(1 for subcommand in subcommands if subcommand == "commit") if commands_available else None
1368
    branch_commands = sum(
1369
        1
1370
        for command, subcommand in invocations
1371
        if subcommand in {"checkout", "switch"} and re.search(r"\s-[bc]\b", command)
1372
    ) if commands_available else None
1373
    merge_commands = sum(1 for subcommand in subcommands if subcommand == "merge") if commands_available else None
1374
    cleanup_commands = sum(
1375
        1
1376
        for command, subcommand in invocations
1377
        if subcommand is not None and re.search(r"\b(clean|end|remove)\b", command)
1378
    ) if commands_available else None
1379
    return {
1380
        "commands_total": commands_total,
1381
        "status_commands": status_commands,
1382
        "diff_commands": diff_commands,
1383
        "snapshot_commands": snapshot_commands,
1384
        "branch_commands": branch_commands,
1385
        "merge_commands": merge_commands,
1386
        "cleanup_commands": cleanup_commands,
1387
        "commits_created": max(0, commit_delta),
1388
        "branches_created": branch_commands or 0,
1389
        "conflicts_total": None,
1390
        "conflicts_resolved": None,
1391
        "dirty_files_at_end": dirty_files,
1392
        "cleanup_success": dirty_files == 0,
1393
        "measurement_source": (
1394
            "transcript_command_classification_plus_oracle_state"
1395
            if commands_available
1396
            else "oracle_state_only; transcript_vcs_commands_unavailable"
1397
        ),
1398
    }
1399
1400
1401
def run_oracle(
1402
    subject: workflow_ab.Subject,
1403
    workflow: workflow_ab.Workflow,
1404
    repo: Path,
1405
    before_manifest: dict[str, dict[str, Any]],
1406
    initial_commit_count: int | None,
1407
    artifacts: Path,
1408
) -> OracleResult:
1409
    start = time.perf_counter()
1410
    artifact_paths: list[Path] = []
1411
1412
    test_start = time.perf_counter()
1413
    # The oracle may run the independent Oak reader, whose own budget scales
1414
    # with the bytes it verifies; never cut it off with a smaller outer limit.
1415
    oracle_timeout = 300.0
1416
    if workflow.name in workflow_oracles.SCENARIOS:
1417
        oracle_timeout = max(oracle_timeout, workflow_oracles.reader_timeout_s(
1418
            repo, workflow_oracles.reader_deadline_scale()) + 120.0)
1419
    test_proc = run_command(
1420
        test_command_for(workflow, subject),
1421
        repo,
1422
        timeout=oracle_timeout,
1423
        env=workflow_ab.python_no_bytecode_env(),
1424
    )
1425
    test_ms = (time.perf_counter() - test_start) * 1000.0
1426
    test_log = artifacts / "oracle.test.log"
1427
    test_log.write_text(test_proc.stdout + test_proc.stderr)
1428
    artifact_paths.append(test_log)
1429
    evidence = None
1430
    if workflow.name in workflow_oracles.SCENARIOS:
1431
        try:
1432
            evidence = json.loads(test_proc.stdout)
1433
            passed = evidence.get("workflow_integrity_passed") if isinstance(evidence, dict) else "invalid"
1434
            valid = (isinstance(evidence, dict) and evidence.get("oracle_version") == ORACLE_VERSION
1435
                     and isinstance(evidence.get("workflow_integrity_source"), str)
1436
                     and (passed is True or passed is False or passed is None)
1437
                     and ((passed is None and bool(evidence.get("workflow_integrity_unmeasured_reason")))
1438
                          or (passed is False and bool(evidence.get("workflow_integrity_failure_reason")))
1439
                          or passed is True)
1440
                     and test_proc.returncode == (77 if passed is None else 0 if passed else 1))
1441
            if not valid:
1442
                evidence = None
1443
        except ValueError:
1444
            evidence = None
1445
        if evidence is None:
1446
            evidence = {"oracle_version": ORACLE_VERSION,
1447
                        "workflow_integrity_source": "trusted_oracle_instrument_unavailable",
1448
                        "workflow_integrity_passed": None,
1449
                        "workflow_integrity_failure_reason": None,
1450
                        "workflow_integrity_unmeasured_reason": "trusted_oracle_evidence_invalid_or_missing"}
1451
1452
    if test_proc.returncode == 77 and evidence is None:
1453
        evidence = {"oracle_version": ORACLE_VERSION,
1454
                    "workflow_integrity_source": "subject_status;required_check_unavailable",
1455
                    "workflow_integrity_evidence_class": "subject_status_only",
1456
                    "workflow_integrity_passed": None,
1457
                    "workflow_integrity_failure_reason": None,
1458
                    "workflow_integrity_unmeasured_reason": "required_check_instrument_unavailable"}
1459
1460
    behavior_passed = None
1461
    if workflow.name == "bugfix_test_loop":
1462
        behavior_start = time.perf_counter()
1463
        # This command runs agent-edited code, so its exit status is
1464
        # subject-controlled: any nonzero (including 77) is a measured failure.
1465
        # "Unmeasured" is only ever decided by the harness itself, here when
1466
        # the interpreter could not be launched at all.
1467
        try:
1468
            behavior = run_command(["python3", "-m", "unittest", "discover", "-s", "tests"], repo,
1469
                                   timeout=300.0, env=workflow_ab.python_no_bytecode_env())
1470
            behavior_passed = behavior.returncode == 0
1471
            behavior_text = behavior.stdout + behavior.stderr
1472
        except OSError as exc:
1473
            behavior_passed = None
1474
            behavior_text = f"harness could not launch behavior tests: {exc}\n"
1475
            evidence = {**(evidence or {}), "workflow_integrity_passed": None,
1476
                        "workflow_integrity_failure_reason": None,
1477
                        "workflow_integrity_unmeasured_reason": "behavior_test_instrument_unavailable"}
1478
        except subprocess.TimeoutExpired as exc:
1479
            behavior_passed = False
1480
            behavior_text = f"behavior tests exceeded {exc.timeout}s\n"
1481
        test_ms += (time.perf_counter() - behavior_start) * 1000
1482
        behavior_log = artifacts / "oracle.behavior.log"
1483
        behavior_log.write_text(behavior_text)
1484
        artifact_paths.append(behavior_log)
1485
1486
    status_text, dirty_count, status_ms = vcs_status(subject, repo)
1487
    status_log = artifacts / "oracle.status.log"
1488
    status_log.write_text(status_text)
1489
    artifact_paths.append(status_log)
1490
1491
    after_manifest = workspace_manifest(repo)
1492
    changed = changed_files(before_manifest, after_manifest)
1493
    expected_change_shape = expected_change_ok(workflow, changed)
1494
    bytes_written = sum(int(after_manifest.get(path, {}).get("bytes", 0)) for path in changed)
1495
1496
    final_commit_count = commit_count(subject, repo)
1497
    commit_delta = 0
1498
    if initial_commit_count is not None and final_commit_count is not None:
1499
        commit_delta = final_commit_count - initial_commit_count
1500
1501
    checks = {
1502
        "required_checks_passed": None if (evidence is not None and evidence.get("workflow_integrity_passed") is None) else test_proc.returncode == 0,
1503
        "expected_change_shape": expected_change_shape,
1504
        "final_vcs_clean": dirty_count == 0,
1505
        "snapshot_created": workflow.name == "history_archaeology" or commit_delta > 0,
1506
    }
1507
    if workflow.name == "bugfix_test_loop":
1508
        checks["behavior_tests_passed"] = behavior_passed
1509
    success = all(checks.values())
1510
    failure_reason = None
1511
    for key, passed in checks.items():
1512
        if passed is False:
1513
            failure_reason = key
1514
            break
1515
1516
    elapsed_ms = (time.perf_counter() - start) * 1000.0
1517
    return OracleResult(
1518
        elapsed_ms=elapsed_ms,
1519
        test_ms=test_ms,
1520
        vcs_ms=status_ms,
1521
        success=success,
1522
        outcome="pass" if success else "fail",
1523
        failure_reason=failure_reason,
1524
        checks=checks,
1525
        test_returncode=test_proc.returncode,
1526
        test_output_bytes=len((test_proc.stdout + test_proc.stderr).encode("utf-8", "replace")),
1527
        status_output=status_text,
1528
        dirty_files_at_end=dirty_count,
1529
        changed_files=changed,
1530
        bytes_written=bytes_written,
1531
        commit_delta=commit_delta,
1532
        artifact_paths=artifact_paths,
1533
        evidence=evidence,
1534
    )
1535
1536
1537
def fixture_shape(workflow: workflow_ab.Workflow) -> str:
1538
    if workflow.name == "bugfix_test_loop":
1539
        return "small Python app with one failing unit test"
1540
    if workflow.name == "wide_config_refactor":
1541
        return "600 small service config files plus validator"
1542
    if workflow.name == "large_asset_manifest":
1543
        return "binary-heavy repo with 64 MiB assets plus JSON manifest"
1544
    return workflow.description
1545
1546
1547
def make_row(
1548
    bench_id: str,
1549
    timestamp_utc: str,
1550
    profile: str,
1551
    agent: AgentConfig,
1552
    subject: workflow_ab.Subject,
1553
    workflow: workflow_ab.Workflow,
1554
    track: str,
1555
    run_index: int,
1556
    repo: Path,
1557
    artifacts: Path,
1558
    setup_ms: float,
1559
    setup_output_bytes: int,
1560
    execution: AgentExecution,
1561
    oracle: OracleResult,
1562
    prompt: str,
1563
    before_manifest: dict[str, dict[str, Any]],
1564
    source: dict[str, Any],
1565
    host_meta: dict[str, str],
1566
    agent_environment: str,
1567
    instruction_level: str,
1568
    shim_info: dict[str, Any] | None = None,
1569
    agent_launched: bool = True,
1570
    setup_returncode: int = 0,
1571
) -> dict[str, Any]:
1572
    capture_metadata = dict(execution.capture_metadata or {})
1573
    parsing_limit = capture_metadata.get("output_limit_bytes", DEFAULT_OUTPUT_LIMIT_BYTES)
1574
    if type(parsing_limit) is not int or parsing_limit < 1:
1575
        raise ValueError("invalid configured output limit")
1576
    stdout_text = read_text(execution.stdout_path, parsing_limit)
1577
    stderr_text = read_text(execution.stderr_path, parsing_limit)
1578
    stored_stdout_bytes = execution.stdout_path.stat().st_size if execution.stdout_path.exists() else 0
1579
    stored_stderr_bytes = execution.stderr_path.stat().st_size if execution.stderr_path.exists() else 0
1580
    stdout_bytes = capture_metadata.get("stdout_observed_bytes", stored_stdout_bytes)
1581
    stderr_bytes = capture_metadata.get("stderr_observed_bytes", stored_stderr_bytes)
1582
    output_truncated = (execution.output_limited or not execution.capture_complete
1583
                        or stored_stdout_bytes + stored_stderr_bytes > parsing_limit)
1584
    usage_complete = agent_launched and not (output_truncated or execution.timed_out or execution.returncode != 0)
1585
    events = parse_json_lines(stdout_text) + parse_json_lines(stderr_text)
1586
    usage = collect_usage(events)
1587
    if not usage_complete:
1588
        # A terminal or cumulative event in a partial transcript is not proof
1589
        # of the complete run's usage, including any in-flight provider work.
1590
        usage = {key: None for key in usage}
1591
    output_chars = extract_text_chars(events, stdout_text + stderr_text)
1592
    transcript_chars = len(prompt) + len(stdout_text) + len(stderr_text)
1593
    token_source = "provider_reported" if usage["total_tokens_reported"] is not None else "char_only"
1594
    if not usage_complete:
1595
        token_source = "unknown"
1596
1597
    analysis = analyze_stream(events, agent.adapter)
1598
    turn_timeline_path: str | None = None
1599
    if analysis.turns:
1600
        timeline_file = artifacts / "turn_timeline.jsonl"
1601
        with timeline_file.open("w") as fh:
1602
            for turn in analysis.turns:
1603
                fh.write(json.dumps(turn, sort_keys=True) + "\n")
1604
        turn_timeline_path = str(timeline_file)
1605
1606
    # Billing-direction cost. Provider-reported when available, otherwise a
1607
    # char/4 estimate split by direction: assistant output is model-emitted
1608
    # (expensive), prompt plus tool results are model-ingested.
1609
    # Direction components must actually be reported: a stream exposing only
1610
    # total_tokens has no direction split, and weighting Nones as zeros would
1611
    # produce cost_weighted_total = 0 for a run that cost real money.
1612
    has_direction_components = any(
1613
        usage[key] is not None
1614
        for key in ("input_tokens_reported", "output_tokens_reported", "reasoning_tokens_reported")
1615
    )
1616
    if not usage_complete:
1617
        cost_weighted_total = None
1618
    elif has_direction_components:
1619
        cost_weighted_total = cost_weighted_total_from_usage(
1620
            usage,
1621
            cache_read_included_in_input=adapter_for(agent.adapter).cache_read_included_in_input,
1622
        )
1623
    else:
1624
        emitted_est = output_chars / 4.0
1625
        ingested_est = max(0, transcript_chars - output_chars) / 4.0
1626
        cost_weighted_total = round(
1627
            emitted_est * EMITTED_TOKEN_WEIGHT + ingested_est * INGESTED_TOKEN_WEIGHT, 1
1628
        )
1629
1630
    tool_counts, by_kind = collect_tool_metrics(stdout_text, stderr_text, events)
1631
    total_ms = setup_ms + execution.elapsed_ms + oracle.elapsed_ms
1632
    logical_bytes = sum(int(item["bytes"]) for item in before_manifest.values())
1633
    logical_file_count = len(before_manifest)
1634
    output_bytes = stdout_bytes + stderr_bytes
1635
    process_ok = (execution.returncode == 0 and not execution.timed_out
1636
                  and not execution.output_limited and execution.capture_complete)
1637
    success = process_ok and oracle.success
1638
    evidence = getattr(oracle, "evidence", None) or {
1639
        "oracle_version": ORACLE_VERSION, "workflow_integrity_source": "fixture_tests_and_subject_status",
1640
        "workflow_integrity_passed": oracle.success,
1641
        "workflow_integrity_failure_reason": oracle.failure_reason,
1642
        "workflow_integrity_unmeasured_reason": None,
1643
    }
1644
    if workflow.name in workflow_oracles.SCENARIOS and getattr(oracle, "evidence", None) is None:
1645
        evidence = {"oracle_version": ORACLE_VERSION,
1646
                    "workflow_integrity_source": "trusted_oracle_instrument_unavailable",
1647
                    "workflow_integrity_passed": None, "workflow_integrity_failure_reason": None,
1648
                    "workflow_integrity_unmeasured_reason": "trusted_oracle_evidence_invalid_or_missing"}
1649
    unmeasured = evidence.get("workflow_integrity_passed") is None
1650
    measured_other_failure = any(value is False for key, value in oracle.checks.items()
1651
                                 if key != "required_checks_passed")
1652
    skipped_instrument = unmeasured and process_ok and not measured_other_failure
1653
    harness_capture_failure = execution.output_limited or (output_truncated and not execution.timed_out)
1654
    provider_error = provider_api_error(agent.adapter, stdout_text)
1655
    skipped_measurement = (skipped_instrument or harness_capture_failure or not agent_launched
1656
                           or provider_error is not None)
1657
    outcome = "timeout" if execution.timed_out else (
1658
        "error" if execution.output_limited or not execution.capture_complete else ("pass" if success else "fail"))
1659
    failure_reason = None
1660
    if execution.timed_out:
1661
        failure_reason = "agent_timeout"
1662
    elif execution.output_limited:
1663
        failure_reason = "agent_output_limit"
1664
    elif not execution.capture_complete:
1665
        failure_reason = "agent_capture_incomplete"
1666
    elif execution.returncode != 0:
1667
        failure_reason = "agent_exit_nonzero"
1668
    elif not oracle.success:
1669
        failure_reason = oracle.failure_reason
1670
    if skipped_measurement:
1671
        outcome = "error"
1672
        success = False
1673
        failure_reason = ("agent_setup_failed" if not agent_launched else
1674
                          provider_error if provider_error is not None else
1675
                          "agent_output_limit" if execution.output_limited else
1676
                          "agent_capture_incomplete" if harness_capture_failure else evidence.get("workflow_integrity_unmeasured_reason"))
1677
1678
    row = {
1679
        "schema_version": SCHEMA_VERSION,
1680
        "bench_id": bench_id,
1681
        "timestamp_utc": timestamp_utc,
1682
        "profile": profile,
1683
        "scenario": workflow.name,
1684
        "env_isolation_version": ENV_ISOLATION_VERSION,
1685
        **runner_fields(),
1686
        **cache_fields(None, None),
1687
        "calibration_version": None,
1688
        "calibration_unmeasured_reason": "no_token_calibration_artifact_bound_to_this_trial",
1689
        "scenario_version": f"{PROMPT_VERSION}/oracle-{ORACLE_VERSION}/execution-{EXECUTION_VERSION}/outcomes-{ATTRIBUTION_VERSION}",
1690
        "operation": "agent.workflow" if agent_launched else "agent.setup",
1691
        "agent_launched": agent_launched,
1692
        "outcome_attribution": "harness" if skipped_measurement else "agent",
1693
        "setup_returncode": setup_returncode,
1694
        "benchmark_track": track,
1695
        "command_semantics_version": COMMAND_SEMANTICS_VERSION,
1696
        "elapsed_ms": round(total_ms, 3),
1697
        "returncode": 77 if skipped_measurement else 0 if success else 1,
1698
        "skipped": skipped_measurement,
1699
        "skip_reason": failure_reason if skipped_measurement else None,
1700
        **evidence,
1701
        "workflow_integrity_evidence_class": evidence.get("workflow_integrity_evidence_class", "tests_and_subject_status" if workflow.name not in workflow_oracles.SCENARIOS else None),
1702
        "raw_output_bytes": output_bytes,
1703
        "stdout_bytes": stdout_bytes,
1704
        "stderr_bytes": stderr_bytes,
1705
        "output_truncated": output_truncated,
1706
        "task_id": None,
1707
        "task_prompt_id": f"real-agent-{workflow.name}-{track}-{instruction_level}-{PROMPT_VERSION}",
1708
        "run": run_index,
1709
        "subject": subject.name,
1710
        "subject_kind": subject.kind,
1711
        "subject_label": subject.label,
1712
        "vcs_mode": vcs_mode(subject),
1713
        "agent": {
1714
            "name": agent.name,
1715
            "adapter": agent.adapter,
1716
            "provider": agent.provider,
1717
            "model": agent.model,
1718
            "version": agent.version,
1719
            "environment": agent_environment,
1720
            "instruction_level": instruction_level,
1721
            "temperature": None,
1722
            "max_output_tokens": None,
1723
        },
1724
        "fixture": {
1725
            "id": workflow.name,
1726
            "repo_shape": fixture_shape(workflow),
1727
            "fixture_version": workflow_ab.FIXTURE_VERSION,
1728
            "logical_file_count": logical_file_count,
1729
            "logical_bytes": logical_bytes,
1730
        },
1731
        "source": {**source, "agent_execution": {
1732
            **capture_metadata, "execution_version": EXECUTION_VERSION,
1733
            "usage_complete": usage_complete,
1734
            "transcript_metrics_complete": usage_complete,
1735
            "counters_coverage": "complete" if usage_complete else "observed_lower_bounds",
1736
            "stdout_retained_bytes": stored_stdout_bytes,
1737
            "stderr_retained_bytes": stored_stderr_bytes,
1738
            "parsing_limit_bytes_per_stream": parsing_limit,
1739
        }},
1740
        "outcome": outcome,
1741
        "success": success,
1742
        "failure_reason": failure_reason,
1743
        "success_criteria": {
1744
            "passed": success,
1745
            "checks": {
1746
                "agent_exit_zero": process_ok if agent_launched else None,
1747
                **oracle.checks,
1748
            },
1749
            "notes": None if success else f"changed_files={oracle.changed_files[:20]}",
1750
        },
1751
        "token_metrics": {
1752
            "token_source": token_source,
1753
            "tokenizer": None,
1754
            **usage,
1755
            "normalized_input_chars": len(prompt),
1756
            "normalized_output_chars": output_chars if usage_complete else None,
1757
            "transcript_chars": transcript_chars if usage_complete else None,
1758
            "context_truncation_events": analysis.context_truncation_events if usage_complete else None,
1759
            "token_budget": None,
1760
            "cost_weighted_total": cost_weighted_total,
1761
            "cost_weights": f"{COST_WEIGHTS_NOTE},cache_write={INGESTED_TOKEN_WEIGHT}",
1762
        },
1763
        "turn_metrics": {
1764
            "turn_source": analysis.turn_source if usage_complete else "unmeasured",
1765
            "assistant_turns_total": analysis.assistant_turns_total if usage_complete else None,
1766
            "tool_calls_per_turn_avg": analysis.tool_calls_per_turn_avg if usage_complete else None,
1767
            "max_tool_calls_per_turn": analysis.max_tool_calls_per_turn if usage_complete else None,
1768
            "cumulative_input_tokens_reported": analysis.cumulative_input_tokens if usage_complete else None,
1769
            "peak_input_tokens_reported": analysis.peak_input_tokens if usage_complete else None,
1770
            "turn_timeline_path": turn_timeline_path,
1771
        },
1772
        "tool_call_metrics": {
1773
            **tool_counts,
1774
            "tool_calls_by_kind": by_kind,
1775
            "unknown_command_failures_total": analysis.unknown_command_failures_total,
1776
            "vcs_info_followup_calls_total": analysis.vcs_info_followup_calls_total,
1777
            "parallel_batches_total": analysis.parallel_batches_total,
1778
            "max_concurrency": analysis.max_concurrency,
1779
            "measurement_source": ("adapter_stream_events_and_transcript_lines" if usage_complete
1780
                                   else "partial_adapter_events_observed_lower_bounds"),
1781
        },
1782
        "failed_command_retry_metrics": {
1783
            "failed_tool_calls_total": analysis.failed_tool_calls_total,
1784
            "failed_commands_total": analysis.failed_tool_calls_total,
1785
            "failed_vcs_commands_total": analysis.failed_vcs_commands_total,
1786
            "failed_test_commands_total": analysis.failed_test_commands_total,
1787
            "retry_attempts_total": analysis.same_command_retries_total,
1788
            "retry_chains_total": None,
1789
            "same_command_retries_total": analysis.same_command_retries_total,
1790
            "retry_after_failure_ms": None,
1791
            "recoverable_failures_total": None,
1792
            "unrecoverable_failures_total": None,
1793
            "turns_to_recovery": analysis.turns_to_recovery,
1794
            "tokens_to_recovery": analysis.tokens_to_recovery,
1795
            "failed_command_examples": analysis.failed_command_examples or [],
1796
            "measurement_source": (
1797
                "adapter_stream_exit_codes" if analysis.failed_tool_calls_total is not None else "not_adapter_visible"
1798
            ),
1799
        },
1800
        "wall_clock_metrics": {
1801
            "total_ms": round(total_ms, 3),
1802
            "setup_ms": round(setup_ms, 3),
1803
            "agent_active_ms": round(execution.elapsed_ms, 3) if agent_launched else None,
1804
            "tool_wait_ms": None,
1805
            "vcs_ms": round(oracle.vcs_ms, 3),
1806
            "test_ms": round(oracle.test_ms, 3),
1807
            "merge_ms": None,
1808
            "cleanup_ms": None,
1809
            "idle_ms": None,
1810
            "timeout_ms": (capture_metadata["timeout_seconds"] * 1000
1811
                           if capture_metadata.get("timeout_seconds") is not None else None),
1812
            "measurement_source": "outer_cli_wall_clock_plus_oracle_phases",
1813
        },
1814
        "bytes_metrics": {
1815
            "workspace_logical_bytes": logical_bytes,
1816
            "workspace_materialized_bytes": logical_bytes,
1817
            # Read-tool payload bytes are not adapter-visible in this lane;
1818
            # the transcript output bytes some dashboards want are already in
1819
            # command_output_bytes. A proxy here would corrupt hydration and
1820
            # read-efficiency comparisons (ADR-0002: null, never a stand-in).
1821
            "bytes_read_by_agent": None,
1822
            "bytes_written_by_agent": oracle.bytes_written,
1823
            "bytes_hydrated": None,
1824
            "files_hydrated": None,
1825
            "hydration_events": None,
1826
            "large_file_bytes_scanned": None,
1827
            "binary_bytes_touched": None,
1828
            "command_output_bytes": output_bytes + oracle.test_output_bytes + setup_output_bytes,
1829
            "measurement_source": "agent_cli_transcript_and_workspace_manifest; read-tool bytes and hydration not adapter-visible in this lane",
1830
        },
1831
        "vcs_metrics": {
1832
            **vcs_metrics_from_tools(
1833
                subject,
1834
                stdout_text,
1835
                stderr_text,
1836
                oracle.dirty_files_at_end,
1837
                oracle.commit_delta,
1838
            ),
1839
            # Shim attribution is additive: null fields when --vcs-shim is off
1840
            # (unmeasured, ADR-0002), populated from the sidecar when on.
1841
            **(shim_info if shim_info is not None else shim_metrics_unavailable("vcs_shim_disabled")),
1842
        },
1843
        "test_metrics": {
1844
            # Harness oracle commands: the trusted payload check, plus the
1845
            # behavior test run for bugfix_test_loop.
1846
            "commands_total": tool_counts["test_commands_total"] + (2 if workflow.name == "bugfix_test_loop" else 1),
1847
            "passed_commands": None if unmeasured else int(oracle.test_returncode == 0),
1848
            "failed_commands": None if unmeasured else int(oracle.test_returncode != 0),
1849
            "assertions_total": None,
1850
            "assertions_failed": None,
1851
            "required_checks_passed": None if unmeasured else oracle.test_returncode == 0,
1852
        },
1853
        "parallel_metrics": {
1854
            "tasks_total": 1,
1855
            "tasks_completed": 1 if success else 0,
1856
            "max_parallel_tasks": 1,
1857
            "overlapping_files_count": None,
1858
            "lost_updates_detected": None,
1859
            "lock_wait_ms": None,
1860
            "commit_throughput_per_s": None,
1861
            "integrity_check_passed": None,
1862
            "measurement_source": "single_task_run; see parallel_contention.py for the contention lane",
1863
        },
1864
        "artifacts": {
1865
            "transcript_path": str(execution.stdout_path),
1866
            "command_log_path": str(execution.stderr_path),
1867
            "diff_path": None,
1868
            "workspace_path": str(repo),
1869
            "extra_paths": [str(execution.prompt_path), *[str(path) for path in oracle.artifact_paths],
1870
                            *([str(artifacts / "execution.json")] if (artifacts / "execution.json").exists() else [])],
1871
        },
1872
        "notes": (
1873
            "agent_active_ms is the outer CLI wall time and may include model time plus hidden tool wait; "
1874
            "tool counts are limited to adapter-visible transcript events. Null metric values mean "
1875
            "unmeasured, never zero. tokens_to_recovery attribution is approximate for adapters that "
1876
            "emit turn boundaries after tool results (codex-style streams)."
1877
        ),
1878
        **host_meta,
1879
    }
1880
    if not usage_complete:
1881
        for key in row["tool_call_metrics"]:
1882
            if key != "measurement_source":
1883
                row["tool_call_metrics"][key] = None
1884
        row["tool_call_metrics"]["measurement_source"] = "incomplete_transcript; aggregates_unmeasured"
1885
        for key in row["failed_command_retry_metrics"]:
1886
            if key not in {"measurement_source", "failed_command_examples"}:
1887
                row["failed_command_retry_metrics"][key] = None
1888
        row["failed_command_retry_metrics"]["measurement_source"] = "incomplete_transcript; examples_are_observed_only"
1889
        for key in ("commands_total", "status_commands", "diff_commands", "snapshot_commands",
1890
                    "branch_commands", "merge_commands", "cleanup_commands", "branches_created"):
1891
            row["vcs_metrics"][key] = None
1892
        row["vcs_metrics"]["measurement_source"] = "transcript_commands_unmeasured; final_state_from_oracle; shim_separate"
1893
        row["test_metrics"]["commands_total"] = None
1894
    return row
1895
1896
1897
def copy_fixture(src: Path, dest: Path) -> None:
1898
    if dest.exists():
1899
        shutil.rmtree(dest)
1900
    shutil.copytree(src, dest)
1901
1902
1903
def run_one(
1904
    agent: AgentConfig,
1905
    subject: workflow_ab.Subject,
1906
    workflow: workflow_ab.Workflow,
1907
    fixture: Path,
1908
    run_index: int,
1909
    run_root: Path,
1910
    artifacts_root: Path,
1911
    timeout_seconds: float,
1912
    track: str,
1913
    agent_environment: str,
1914
    instruction_level: str,
1915
    bench_id: str,
1916
    timestamp_utc: str,
1917
    source: dict[str, Any],
1918
    host_meta: dict[str, str],
1919
    vcs_shim: bool = False,
1920
    output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES,
1921
    fixture_copy_validator: Callable[[Path], None] | None = None,
1922
    fixture_prepared: bool = False,
1923
) -> dict[str, Any]:
1924
    repo = run_root / workflow.name / agent.name / subject.name / f"run-{run_index}"
1925
    artifacts = artifacts_root / workflow.name / agent.name / subject.name / f"run-{run_index}"
1926
    artifacts.mkdir(parents=True, exist_ok=True)
1927
    if not fixture_prepared:
1928
        copy_fixture(fixture, repo)
1929
    if fixture_copy_validator is not None:
1930
        fixture_copy_validator(repo)
1931
    write_workspace_instructions(repo, subject, track, instruction_level)
1932
    setup_ms, setup_output, setup_returncode = initialize_repo(subject, repo)
1933
1934
    # Workflows with prepare steps (seeded history, pre-broken state) need them
1935
    # in the agent lane too, and untimed: they are setup, not agent work. The
1936
    # baseline manifest is taken AFTER prepare so prepare edits are not
1937
    # miscounted as agent changes.
1938
    if setup_returncode == 0 and workflow.prepare is not None:
1939
        prepare_start = time.perf_counter()
1940
        prepare_lines: list[str] = []
1941
        for step in workflow.prepare(subject, track):
1942
            proc = run_command(step.command, repo)
1943
            prepare_lines.append("$ " + workflow_ab.command_display(step.command))
1944
            if proc.stdout:
1945
                prepare_lines.append(proc.stdout)
1946
            if proc.stderr:
1947
                prepare_lines.append(proc.stderr)
1948
            if proc.returncode not in step.expected_returncodes:
1949
                setup_returncode = proc.returncode or 1
1950
                break
1951
        setup_ms += (time.perf_counter() - prepare_start) * 1000.0
1952
        setup_output = setup_output + "\n" + "\n".join(prepare_lines)
1953
1954
    before_manifest = workspace_manifest(repo)
1955
    setup_log = artifacts / "setup.log"
1956
    setup_log.write_text(setup_output)
1957
    initial_commit_count = commit_count(subject, repo) if setup_returncode == 0 else None
1958
    prompt = build_prompt(subject, workflow, track, instruction_level)
1959
    prompt_path = artifacts / "prompt.txt"
1960
    prompt_path.write_text(prompt)
1961
1962
    # VCS PATH shim: wrapper git/oak executables prepended to the agent's
1963
    # PATH record per-call timing to a sidecar JSONL. The overhead calibration
1964
    # runs first against the same sidecar, which is then reset so calibration
1965
    # rows are never attributed to the agent. Overhead is recorded, never
1966
    # subtracted (ADR-0002).
1967
    agent_env, environment_metadata = trial_agent_env(artifacts, home_root=run_root.parent / "agent-homes")
1968
    sidecar: Path | None = None
1969
    shim_overhead_ms: float | None = None
1970
    if vcs_shim and setup_returncode == 0:
1971
        real_binaries = shim_real_binaries(subject)
1972
        sidecar = artifacts / "vcs_shim_sidecar.jsonl"
1973
        shim_dir = create_shim_dir(
1974
            artifacts / "vcs-shim", real_binaries=real_binaries, sidecar_path=sidecar
1975
        )
1976
        real_git = real_binaries.get("git")
1977
        if real_git:
1978
            shim_overhead_ms = measure_shim_overhead(shim_dir, sidecar, real_git)
1979
        sidecar.write_text("")
1980
        agent_env["PATH"] = str(shim_dir) + os.pathsep + agent_env.get("PATH", "")
1981
1982
    if setup_returncode != 0:
1983
        stdout_path = artifacts / "agent.stdout.log"
1984
        stderr_path = artifacts / "agent.stderr.log"
1985
        stdout_path.write_text("")
1986
        stderr_path.write_text("setup failed\n")
1987
        execution = AgentExecution(setup_returncode, False, 0.0, stdout_path, stderr_path, prompt_path)
1988
    elif agent.adapter == "deterministic_mock":
1989
        execution = run_mock_agent(subject, workflow, repo, track, artifacts, prompt_path, env=agent_env)
1990
    else:
1991
        execution = run_real_agent(
1992
            agent, repo, prompt, artifacts, timeout_seconds, agent_environment, env=agent_env,
1993
            output_limit_bytes=output_limit_bytes,
1994
        )
1995
    if execution.capture_metadata is not None:
1996
        execution.capture_metadata.update(environment_metadata)
1997
        (artifacts / "execution.json").write_text(json.dumps(execution.capture_metadata, sort_keys=True) + "\n")
1998
1999
    shim_info: dict[str, Any] | None = None
2000
    if vcs_shim and sidecar is not None:
2001
        shim_info = shim_metrics_from_sidecar(sidecar, shim_overhead_ms, execution.elapsed_ms)
2002
2003
    if setup_returncode != 0:
2004
        oracle = OracleResult(0, 0, 0, False, "error", "agent_setup_failed", {}, 77, 0, "", None, [], 0, 0, [],
2005
            evidence={"oracle_version": ORACLE_VERSION, "workflow_integrity_source": "setup_failed_no_oracle",
2006
                      "workflow_integrity_passed": None, "workflow_integrity_failure_reason": None,
2007
                      "workflow_integrity_evidence_class": None, "workflow_integrity_unmeasured_reason": "agent_setup_failed"})
2008
    else:
2009
        oracle = run_oracle(subject, workflow, repo, before_manifest, initial_commit_count, artifacts)
2010
    return make_row(
2011
        bench_id=bench_id,
2012
        timestamp_utc=timestamp_utc,
2013
        profile="agent-workflow",
2014
        agent=agent,
2015
        subject=subject,
2016
        workflow=workflow,
2017
        track=track,
2018
        run_index=run_index,
2019
        repo=repo,
2020
        artifacts=artifacts,
2021
        setup_ms=setup_ms,
2022
        setup_output_bytes=len(setup_output.encode("utf-8", "replace")),
2023
        execution=execution,
2024
        oracle=oracle,
2025
        prompt=prompt,
2026
        before_manifest=before_manifest,
2027
        source=source,
2028
        host_meta=host_meta,
2029
        agent_environment=agent_environment,
2030
        instruction_level=instruction_level,
2031
        shim_info=shim_info,
2032
        agent_launched=setup_returncode == 0, setup_returncode=setup_returncode,
2033
    )
2034
2035
2036
def metric_average(rows: list[dict[str, Any]], metric_getter: Any) -> dict[tuple[str, str, str], float]:
2037
    grouped: dict[tuple[str, str, str], list[float]] = {}
2038
    for row in rows:
2039
        # Harness-aborted/unmeasured rows are not agent measurements; averaging
2040
        # them in would contradict the success cell that reads unmeasured.
2041
        if row.get("skipped") or row.get("outcome_attribution") in {"harness", "subject"}:
2042
            continue
2043
        value = metric_getter(row)
2044
        if value is None:
2045
            continue
2046
        key = (str(row["agent"]["name"]), str(row["subject"]), str(row["scenario"]))
2047
        grouped.setdefault(key, []).append(float(value))
2048
    return {key: statistics.mean(values) for key, values in grouped.items()}
2049
2050
2051
def token_total(row: dict[str, Any]) -> float | None:
2052
    return shared_token_total(row)
2053
2054
2055
def summary_text(rows: list[dict[str, Any]]) -> str:
2056
    avg_ms = metric_average(rows, lambda row: row.get("elapsed_ms"))
2057
    avg_tokens = metric_average(rows, token_total)
2058
    avg_tools = metric_average(rows, lambda row: row["tool_call_metrics"]["tool_calls_total"])
2059
    avg_output = metric_average(rows, lambda row: row.get("raw_output_bytes"))
2060
    avg_turns = metric_average(rows, lambda row: row["turn_metrics"]["assistant_turns_total"])
2061
    avg_cost = metric_average(rows, lambda row: row["token_metrics"]["cost_weighted_total"])
2062
    avg_help = metric_average(rows, lambda row: row["tool_call_metrics"]["help_calls_total"])
2063
    success_rate = metric_average(rows, lambda row: (1.0 if row.get("success") else 0.0)
2064
        if row.get("agent_launched") is True and row.get("outcome_attribution") == "agent" and not row.get("skipped") else None)
2065
    keys = sorted(set(avg_ms) | set(avg_tokens) | set(avg_tools) | set(avg_output) | set(success_rate))
2066
2067
    def cell(values: dict[tuple[str, str, str], float], key: tuple[str, str, str], precision: int = 1) -> str:
2068
        value = values.get(key)
2069
        if value is None:
2070
            return "unmeasured"
2071
        return f"{value:.{precision}f}"
2072
2073
    instruction_levels = sorted({str(row["agent"].get("instruction_level")) for row in rows})
2074
    lines = [
2075
        "# Oak Real Agent Workflow Summary",
2076
        "",
2077
        "Rows include agent attempts and setup/instrument skips. Success rates use measured agent-attributed outcomes only. Token estimates require a complete transcript.",
2078
        f"Instruction levels in this run: {', '.join(f'`{level}`' for level in instruction_levels)}.",
2079
        "Cost-weighted tokens use billing direction: " + COST_WEIGHTS_NOTE + ".",
2080
        "`unmeasured` means the adapter did not expose the signal; it is not zero.",
2081
        "",
2082
        "| Agent | Scenario | Subject | Success rate | Avg ms | Avg tokens | Avg cost-weighted | Avg turns | Avg tool calls | Avg help calls | Avg output bytes |",
2083
        "| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
2084
    ]
2085
    for agent_name, subject, scenario in keys:
2086
        key = (agent_name, subject, scenario)
2087
        lines.append(
2088
            f"| `{agent_name}` | `{scenario}` | `{subject}` | "
2089
            f"{format(success_rate[key] * 100, '.1f') + '%' if key in success_rate else 'unmeasured'} | "
2090
            f"{cell(avg_ms, key)} | "
2091
            f"{cell(avg_tokens, key)} | "
2092
            f"{cell(avg_cost, key)} | "
2093
            f"{cell(avg_turns, key)} | "
2094
            f"{cell(avg_tools, key)} | "
2095
            f"{cell(avg_help, key)} | "
2096
            f"{cell(avg_output, key, 0)} |"
2097
        )
2098
    return "\n".join(lines) + "\n"
2099
2100
2101
def main() -> int:
2102
    args = parse_args()
2103
    agents = load_agents(args.agents_config, args.agents if not args.list_agents else "all")
2104
    if args.list_agents:
2105
        print_agents(agents)
2106
        return 0
2107
2108
    subjects = workflow_ab.load_subjects(args)
2109
    workflows = select_workflows(args.workflows)
2110
2111
    timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
2112
    timestamp_iso = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
2113
    args.results.mkdir(parents=True, exist_ok=True)
2114
    args.workdir.mkdir(parents=True, exist_ok=True)
2115
    run_root = args.workdir / "runs" / timestamp
2116
    artifacts_root = args.results / "artifacts" / timestamp
2117
    source = workflow_ab.source_metadata(args.oak_repo)
2118
    host_meta = {
2119
        "host": platform.node(),
2120
        "platform": platform.platform(),
2121
        "machine": platform.machine(),
2122
    }
2123
2124
    rows: list[dict[str, Any]] = []
2125
    for workflow in workflows:
2126
        fixture = workflow_ab.prepare_fixture(args.workdir, workflow)
2127
        print(f"[fixture] {workflow.name}: {workflow.description}", flush=True)
2128
        for run_index in range(args.runs):
2129
            run_agents = list(agents)
2130
            run_subjects = list(subjects)
2131
            if args.randomize_agent_order:
2132
                random.Random(f"{timestamp}:{workflow.name}:{run_index}:agents").shuffle(run_agents)
2133
            if args.randomize_subject_order:
2134
                random.Random(f"{timestamp}:{workflow.name}:{run_index}:subjects").shuffle(run_subjects)
2135
            for agent in run_agents:
2136
                for subject in run_subjects:
2137
                    print(
2138
                        f"[run] {workflow.name} run={run_index} agent={agent.name} subject={subject.name}",
2139
                        flush=True,
2140
                    )
2141
                    row = run_one(
2142
                        agent=agent,
2143
                        subject=subject,
2144
                        workflow=workflow,
2145
                        fixture=fixture,
2146
                        run_index=run_index,
2147
                        run_root=run_root,
2148
                        artifacts_root=artifacts_root,
2149
                        timeout_seconds=args.timeout_seconds,
2150
                        track=args.track,
2151
                        agent_environment=args.agent_environment,
2152
                        instruction_level=args.instruction_level,
2153
                        bench_id=timestamp,
2154
                        timestamp_utc=timestamp_iso,
2155
                        source=source,
2156
                        host_meta=host_meta,
2157
                        vcs_shim=args.vcs_shim,
2158
                        output_limit_bytes=args.output_limit_bytes,
2159
                    )
2160
                    row["randomized_subject_order"] = args.randomize_subject_order
2161
                    row["subject_order"] = [item.name for item in run_subjects]
2162
                    rows.append(row)
2163
2164
    store = ResultsStore(args.results, lane="agent")
2165
    raw_path, summary_path = store.write(timestamp, rows, summary_text(rows))
2166
2167
    # The agent lane's full contract is the versioned schema, validated on
2168
    # every run so emitter drift fails the producing run, not the dashboard.
2169
    schema_errors: list[str] = []
2170
    for index, row in enumerate(rows, 1):
2171
        for error in validate_row(row):
2172
            schema_errors.append(f"row {index}: {error}")
2173
2174
    if not args.keep_workdirs and run_root.exists():
2175
        shutil.rmtree(run_root)
2176
2177
    print(f"[result] {raw_path}")
2178
    print(f"[summary] {summary_path}")
2179
    print(f"[artifacts] {artifacts_root}")
2180
    if schema_errors:
2181
        preview = "\n  ".join(schema_errors[:20])
2182
        print(f"[schema] FAILED agent row schema validation:\n  {preview}")
2183
        return 1
2184
    return 0
2185
2186
2187
if __name__ == "__main__":
2188
    raise SystemExit(main())