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

scripts/workflow_ab.py in oak/benchmarks

scripts/workflow_ab.py 1876 lines · 77.8 KB · python
1
#!/usr/bin/env python3
2
"""Run deterministic agent-shaped workflow A/B tests across Git and Oak.
3
4
This complements scripts/bench.py. The core benchmark times isolated VCS
5
commands; this script runs whole task recipes that look more like common agent
6
work: search, read, edit, test/validate, status, diff, and snapshot. The
7
fixtures and edits are deterministic so different subjects only vary by VCS.
8
"""
9
10
from __future__ import annotations
11
12
import argparse
13
import json
14
import platform
15
import random
16
import shlex
17
import shutil
18
import statistics
19
import subprocess
20
import tempfile
21
import time
22
from dataclasses import dataclass, field
23
from datetime import datetime, timezone
24
from pathlib import Path
25
from typing import Any, Callable
26
27
from oakbench import environment as oakbench_environment
28
from oakbench import envwatch as oakbench_envwatch
29
from oakbench import fixtures as oakbench_fixtures
30
from oakbench import loadgen as oakbench_loadgen
31
from oakbench import integrity as oakbench_integrity
32
from oakbench import workflow_oracles
33
from oakbench import remotes as oakbench_remotes
34
from oakbench import tokens as oakbench_tokens
35
from oakbench.command_semantics import semantics
36
from oakbench.environment import command_display
37
from oakbench.execution import run_timed
38
from oakbench.reporting import fmt_delta_lower_better, fmt_num
39
from oakbench.results import ResultsStore
40
from oakbench.rows import SKIP_RETURNCODE, row_returncode
41
from oakbench.runlock import measurement_lock
42
from oakbench.subjects import (
43
    DEFAULT_OAK_REPO,
44
    Subject,
45
    load_subjects,
46
    source_metadata,
47
    subject_details,
48
    subject_version,
49
)
50
51
ROOT = Path(__file__).resolve().parents[1]
52
DEFAULT_WORKDIR = Path(tempfile.gettempdir()) / "oak-workflow-ab"
53
DEFAULT_ADMITTED_OUTPUT_CHARS = 20_000
54
FIXTURE_VERSION = "2026-06-09.2"
55
TRACKS = ("agent-default", "core-equivalent")
56
57
# Compatibility re-exports: agent_workflow.py and tests reference these
58
# through this module. The definitions live in oakbench (the measurement core).
59
COST_WEIGHTS_NOTE = oakbench_tokens.COST_WEIGHTS_NOTE
60
COMMAND_SEMANTICS_VERSION = semantics().version
61
_OAK_COMMIT_PUSH_SUPPORT_CACHE: dict[str, str | None] = {}
62
63
64
def base_env() -> dict[str, str]:
65
    return oakbench_environment.base_env(
66
        author_name="Oak Workflow Bench",
67
        author_email="workflow-bench@oak.local",
68
        oak_author="oak-workflow-bench",
69
    )
70
71
72
def python_no_bytecode_env(base: dict[str, str] | None = None) -> dict[str, str]:
73
    env = dict(base) if base is not None else base_env()
74
    env["PYTHONDONTWRITEBYTECODE"] = "1"
75
    return env
76
77
78
def step_env(step: "Step", base: dict[str, str] | None = None) -> dict[str, str]:
79
    if step.kind == "test":
80
        return python_no_bytecode_env(base)
81
    return dict(base) if base is not None else base_env()
82
83
84
def oak_commit_push_skip_reason(subject: Subject) -> str | None:
85
    if subject.kind != "oak":
86
        return None
87
    key = str(subject.bin)
88
    if key in _OAK_COMMIT_PUSH_SUPPORT_CACHE:
89
        return _OAK_COMMIT_PUSH_SUPPORT_CACHE[key]
90
    try:
91
        probe = subprocess.run(
92
            [key, "commit", "--help"],
93
            capture_output=True,
94
            text=True,
95
            env=base_env(),
96
            timeout=15,
97
            check=False,
98
        )
99
    except FileNotFoundError:
100
        reason = f"missing_binary:{key}"
101
        _OAK_COMMIT_PUSH_SUPPORT_CACHE[key] = reason
102
        return reason
103
    except subprocess.TimeoutExpired:
104
        reason = "oak_commit_push_capability_timeout"
105
        _OAK_COMMIT_PUSH_SUPPORT_CACHE[key] = reason
106
        return reason
107
    help_text = (probe.stdout or "") + "\n" + (probe.stderr or "")
108
    if probe.returncode != 0:
109
        reason = "oak_commit_push_capability_failed"
110
    elif "--push" not in help_text:
111
        reason = "oak_commit_push_not_supported:requires_current_oak"
112
    else:
113
        reason = None
114
    _OAK_COMMIT_PUSH_SUPPORT_CACHE[key] = reason
115
    return reason
116
117
118
@dataclass(frozen=True)
119
class Workflow:
120
    name: str
121
    description: str
122
    make_fixture: Callable[[Path], None]
123
    steps: Callable[..., list["Step"]]
124
    # Optional untimed-phase steps (run in the setup phase, after repo init)
125
    # for workflows that need pre-built history or pre-broken state.
126
    prepare: Callable[..., list["Step"]] | None = None
127
    # Workflows that exercise a remote set the oakbench.remotes purpose here.
128
    # Their steps/prepare callables take (subject, track, ctx); ctx carries the
129
    # per-run disposable branch and remote/clone paths. Oak subjects without
130
    # the purpose env var configured emit a skip row (returncode 77).
131
    remote_purpose: str | None = None
132
133
134
@dataclass(frozen=True)
135
class Step:
136
    operation: str
137
    kind: str
138
    command: list[str]
139
    expected_returncodes: tuple[int, ...] = (0,)
140
    # For expected-failure steps: the literal recovery command the workflow
141
    # runs next. The row records whether the error text actually mentions it —
142
    # the "error output is a prompt" actionability measurement. A misleading
143
    # hint (error suggests something other than the real fix) is a finding,
144
    # not a harness bug.
145
    recovery_hint: str | None = None
146
    # Optional answer oracle over the step's stdout. The row records
147
    # answer_correct True/False, or None (unmeasured) when stdout was
148
    # truncated by the admitted-output cap. A wrong answer fails the step:
149
    # a fast, cheap command that answers the question wrongly is not a win.
150
    answer_check: Callable[[str], bool] | None = field(default=None, compare=False)
151
    answer_description: str | None = None
152
153
154
def parse_args() -> argparse.Namespace:
155
    parser = argparse.ArgumentParser(description=__doc__)
156
    parser.add_argument(
157
        "--workflows",
158
        default="bugfix_test_loop,wide_config_refactor,large_asset_manifest",
159
        help="Comma-separated workflow names, or 'all'.",
160
    )
161
    parser.add_argument("--subjects", help="Comma-separated subject names")
162
    parser.add_argument("--runs", type=int, default=1)
163
    parser.add_argument("--config", type=Path, default=ROOT / "config" / "subjects.toml")
164
    parser.add_argument("--workdir", type=Path, default=DEFAULT_WORKDIR)
165
    parser.add_argument("--results", type=Path, default=ROOT / "results" / "workflow-ab")
166
    parser.add_argument(
167
        "--oak-repo",
168
        type=Path,
169
        default=DEFAULT_OAK_REPO,
170
        help="Optional Oak source checkout for provenance metadata. Defaults to $OAK_REPO or ../oak.",
171
    )
172
    parser.add_argument("--keep-workdirs", action="store_true")
173
    parser.add_argument("--git-bin", type=Path)
174
    parser.add_argument("--oak-installed-bin", type=Path)
175
    parser.add_argument("--oak-local-bin", type=Path)
176
    parser.add_argument("--oak-aa-bin", type=Path, help="A/A control: the baseline Oak binary under subject oak_installed_aa.")
177
    parser.add_argument(
178
        "--track",
179
        choices=TRACKS,
180
        default="agent-default",
181
        help=(
182
            "agent-default measures natural current commands; core-equivalent "
183
            "uses the closest matching semantic output level across VCSs."
184
        ),
185
    )
186
    parser.add_argument(
187
        "--randomize-subject-order",
188
        action="store_true",
189
        help="Shuffle subject order per workflow run to reduce cache/order bias.",
190
    )
191
    parser.add_argument(
192
        "--admitted-output-chars",
193
        type=int,
194
        default=DEFAULT_ADMITTED_OUTPUT_CHARS,
195
        help="Per-command stdout/stderr characters counted as agent-visible output.",
196
    )
197
    parser.add_argument(
198
        "--load-tier",
199
        choices=sorted(oakbench_loadgen.LOAD_TIERS),
200
        default="none",
201
        help=(
202
            "Inject a machine-independent stress-ng background load tier while "
203
            "measuring (noisy-neighbor realism). Requires the optional stress-ng "
204
            "binary; when it is missing under a non-none tier every row becomes "
205
            "an explicit skip row — load that was not applied is never claimed."
206
        ),
207
    )
208
    return parser.parse_args()
209
210
211
def shell(script: str) -> list[str]:
212
    return ["/bin/zsh", "-c", script]
213
214
215
def search_command(pattern: str, target: str) -> str:
216
    # rg is not guaranteed on benchmark runners; grep -rnE has the same exit
217
    # contract (0 match, 1 no match). The row's command field records which ran.
218
    # rg skips hidden directories by default; grep must be told to skip VCS
219
    # internals or its match scope (and token counts) diverge.
220
    if shutil.which("rg"):
221
        return f"rg -n {shlex.quote(pattern)} {target}"
222
    return f"grep -rnE --exclude-dir=.git --exclude-dir=.oak {shlex.quote(pattern)} {target}"
223
224
225
def snapshot_steps(subject: Subject, operation_prefix: str, message: str) -> list[Step]:
226
    """Snapshot via the command-semantics contract: git pays stage+commit as two
227
    tool calls, oak one. Operation names follow the historical .add/.commit split."""
228
    sem = semantics()
229
    vcs = str(subject.bin)
230
    stage = sem.stage_args(subject.kind)
231
    if stage is not None:
232
        return [
233
            Step(f"{operation_prefix}.add", "vcs", [vcs, *stage]),
234
            Step(f"{operation_prefix}.commit", "vcs", [vcs, *sem.commit_args(subject.kind, message)]),
235
        ]
236
    return [Step(operation_prefix, "vcs", [vcs, *sem.commit_args(subject.kind, message)])]
237
238
239
def vcs_init_steps(subject: Subject) -> list[Step]:
240
    sem = semantics()
241
    vcs = str(subject.bin)
242
    return [
243
        Step("setup.repo_init", "vcs", [vcs, *sem.init_args(subject.kind)]),
244
        *snapshot_steps(subject, "setup.snapshot", "initial"),
245
    ]
246
247
248
def vcs_workflow_steps(subject: Subject, track: str) -> list[Step]:
249
    sem = semantics()
250
    vcs = str(subject.bin)
251
    return [
252
        Step("vcs.branch", "vcs", [vcs, *sem.branch_create_args(subject.kind)]),
253
        Step("vcs.status", "vcs", [vcs, *sem.status_args(subject.kind, track)]),
254
        Step("vcs.diff", "vcs", [vcs, *sem.diff_args(subject.kind, track)]),
255
        *snapshot_steps(subject, "vcs.snapshot", "agent task"),
256
    ]
257
258
259
def make_bugfix_fixture(path: Path) -> None:
260
    (path / "app").mkdir(parents=True)
261
    (path / "tests").mkdir()
262
    (path / "app" / "__init__.py").write_text("")
263
    (path / "app" / "pricing.py").write_text(
264
        "\n".join(
265
            [
266
                "def apply_discount(cents: int, percent: int) -> int:",
267
                "    \"\"\"Return discounted cents rounded down.\"\"\"",
268
                "    # BUG: this subtracts the percent value, not the percentage.",
269
                "    return cents - percent",
270
                "",
271
            ]
272
        )
273
    )
274
    (path / "tests" / "test_pricing.py").write_text(
275
        "\n".join(
276
            [
277
                "import unittest",
278
                "from app.pricing import apply_discount",
279
                "",
280
                "",
281
                "class PricingTest(unittest.TestCase):",
282
                "    def test_apply_discount(self):",
283
                "        self.assertEqual(apply_discount(1000, 25), 750)",
284
                "        self.assertEqual(apply_discount(999, 10), 900)",
285
                "",
286
                "",
287
                "if __name__ == '__main__':",
288
                "    unittest.main()",
289
                "",
290
            ]
291
        )
292
    )
293
    (path / "README.md").write_text("Pricing service fixture for agent workflow benchmarks.\n")
294
295
296
def bugfix_steps(subject: Subject, track: str) -> list[Step]:
297
    return [
298
        Step("search.locate_symbol", "search", shell(search_command("apply_discount|BUG|discount", "."))),
299
        Step("read.source", "read", shell("sed -n '1,120p' app/pricing.py")),
300
        Step("read.tests", "read", shell("sed -n '1,160p' tests/test_pricing.py")),
301
        Step("test.red", "test", shell("python3 -m unittest discover -s tests"), (1,)),
302
        Step(
303
            "edit.fix_bug",
304
            "edit",
305
            shell(
306
                "python3 - <<'PY'\n"
307
                "from pathlib import Path\n"
308
                "p = Path('app/pricing.py')\n"
309
                "text = p.read_text()\n"
310
                "text = text.replace('return cents - percent', 'return cents - ((cents * percent) // 100)')\n"
311
                "p.write_text(text)\n"
312
                "PY"
313
            ),
314
        ),
315
        Step("test.green", "test", shell("python3 -m unittest discover -s tests")),
316
        *vcs_workflow_steps(subject, track),
317
    ]
318
319
320
def make_wide_config_fixture(path: Path) -> None:
321
    root = path / "services"
322
    for index in range(600):
323
        service = root / f"service-{index:04d}"
324
        service.mkdir(parents=True, exist_ok=True)
325
        timeout = 2500 if index % 3 == 0 else 1800
326
        service.joinpath("config.toml").write_text(
327
            "\n".join(
328
                [
329
                    f'name = "service-{index:04d}"',
330
                    f"timeout_ms = {timeout}",
331
                    "retries = 2",
332
                    "",
333
                ]
334
            )
335
        )
336
    (path / "validate_configs.py").write_text(
337
        "\n".join(
338
            [
339
                "from pathlib import Path",
340
                "bad = []",
341
                "for p in Path('services').glob('*/config.toml'):",
342
                "    text = p.read_text()",
343
                "    if 'timeout_ms = 2500' in text:",
344
                "        bad.append(str(p))",
345
                "print(f'bad={len(bad)}')",
346
                "raise SystemExit(1 if bad else 0)",
347
                "",
348
            ]
349
        )
350
    )
351
352
353
def wide_config_steps(subject: Subject, track: str) -> list[Step]:
354
    return [
355
        Step(
356
            "search.deprecated_timeout",
357
            "search",
358
            shell(search_command("timeout_ms = 2500", "services") + " | head -40"),
359
        ),
360
        Step("read.sample_config", "read", shell("sed -n '1,80p' services/service-0000/config.toml")),
361
        Step(
362
            "edit.rewrite_configs",
363
            "edit",
364
            shell(
365
                "python3 - <<'PY'\n"
366
                "from pathlib import Path\n"
367
                "for p in Path('services').glob('*/config.toml'):\n"
368
                "    text = p.read_text()\n"
369
                "    if 'timeout_ms = 2500' in text:\n"
370
                "        p.write_text(text.replace('timeout_ms = 2500', 'timeout_ms = 3000'))\n"
371
                "PY"
372
            ),
373
        ),
374
        Step("search.verify_none_left", "search", shell("! " + search_command("timeout_ms = 2500", "services"))),
375
        Step("test.validate_configs", "test", shell("python3 validate_configs.py")),
376
        *vcs_workflow_steps(subject, track),
377
    ]
378
379
380
def write_pattern_file(path: Path, size: int, seed: str) -> None:
381
    oakbench_fixtures.write_pattern_file(path, size, seed, binary=True, prefix="oak-workflow")
382
383
384
def make_large_asset_fixture(path: Path) -> None:
385
    assets = path / "assets"
386
    assets.mkdir(parents=True)
387
    manifest: list[dict[str, Any]] = []
388
    for index in range(4):
389
        asset_path = assets / f"asset-{index:02d}.bin"
390
        write_pattern_file(asset_path, 16 * 1024 * 1024, f"asset-{index}")
391
        manifest.append({"path": str(asset_path.relative_to(path)), "bytes": asset_path.stat().st_size, "reviewed": False})
392
    (path / "manifest.json").write_text(json.dumps({"assets": manifest}, indent=2) + "\n")
393
    (path / "validate_manifest.py").write_text(
394
        "\n".join(
395
            [
396
                "import json",
397
                "from pathlib import Path",
398
                "data = json.loads(Path('manifest.json').read_text())",
399
                "for item in data['assets']:",
400
                "    p = Path(item['path'])",
401
                "    assert p.exists(), p",
402
                "    assert p.stat().st_size == item['bytes'], p",
403
                "    assert item['reviewed'] is True, p",
404
                "print('manifest ok')",
405
                "",
406
            ]
407
        )
408
    )
409
410
411
def large_asset_steps(subject: Subject, track: str) -> list[Step]:
412
    return [
413
        Step("search.assets", "search", shell("find assets -type f -maxdepth 1 | sort")),
414
        Step("read.manifest", "read", shell("sed -n '1,120p' manifest.json")),
415
        Step(
416
            "read.binary_prefix",
417
            "read",
418
            shell("python3 - <<'PY'\nfrom pathlib import Path\nprint(Path('assets/asset-00.bin').read_bytes()[:64].hex())\nPY"),
419
        ),
420
        Step(
421
            "edit.mark_reviewed",
422
            "edit",
423
            shell(
424
                "python3 - <<'PY'\n"
425
                "import json\n"
426
                "from pathlib import Path\n"
427
                "p = Path('manifest.json')\n"
428
                "data = json.loads(p.read_text())\n"
429
                "for item in data['assets']:\n"
430
                "    item['reviewed'] = True\n"
431
                "p.write_text(json.dumps(data, indent=2) + '\\n')\n"
432
                "PY"
433
            ),
434
        ),
435
        Step("test.validate_manifest", "test", shell("python3 validate_manifest.py")),
436
        *vcs_workflow_steps(subject, track),
437
    ]
438
439
440
def make_history_fixture(path: Path) -> None:
441
    (path / "app").mkdir(parents=True)
442
    (path / "app" / "pricing.py").write_text(
443
        "\n".join(
444
            [
445
                "def apply_discount(cents: int, percent: int) -> int:",
446
                "    return cents - ((cents * percent) // 100)",
447
                "",
448
            ]
449
        )
450
    )
451
    (path / "app" / "totals.py").write_text("def total(items):\n    return sum(items)\n")
452
    (path / "README.md").write_text("History archaeology fixture for agent workflow benchmarks.\n")
453
454
455
def history_prepare_steps(subject: Subject, track: str) -> list[Step]:
456
    vcs = shlex.quote(str(subject.bin))
457
    steps: list[Step] = []
458
    edits = [
459
        ("app/pricing.py", "support negative-percent surcharges", "# rev: surcharge support"),
460
        ("app/totals.py", "guard empty item lists", "# rev: empty-list guard"),
461
        ("app/pricing.py", "clamp discount to 100 percent", "# rev: discount clamp"),
462
    ]
463
    for index, (target, message, marker) in enumerate(edits):
464
        if subject.kind == "git":
465
            script = (
466
                f"echo {shlex.quote(marker)} >> {shlex.quote(target)} && "
467
                f"{vcs} add . && {vcs} commit -m {shlex.quote(message)}"
468
            )
469
        else:
470
            script = f"echo {shlex.quote(marker)} >> {shlex.quote(target)} && {vcs} commit --no-verify"
471
        steps.append(Step(f"setup.history.commit_{index}", "vcs", shell(script)))
472
    return steps
473
474
475
def history_archaeology_steps(subject: Subject, track: str) -> list[Step]:
476
    # Agents constantly ask "what changed recently, in this file, and why".
477
    # Oak lacks show/blame/pickaxe equivalents today, so its rows use the
478
    # closest available command (oak log); the token/capability gap is the
479
    # measurement, and the command field records what actually ran.
480
    vcs = str(subject.bin)
481
    if subject.kind == "git":
482
        return [
483
            Step("history.recent", "vcs", [vcs, "log", "--oneline", "-15"]),
484
            Step("history.show_last", "vcs", [vcs, "show", "--stat", "HEAD"]),
485
            Step("history.file_history", "vcs", [vcs, "log", "--oneline", "-5", "--", "app/pricing.py"]),
486
            Step("history.pickaxe", "vcs", [vcs, "log", "-S", "surcharge", "--oneline"], (0, 1, 2)),
487
        ]
488
    return [
489
        Step("history.recent", "vcs", [vcs, "log", "-n", "15"]),
490
        Step("history.show_last", "vcs", [vcs, "log", "-n", "1", "-v"]),
491
        Step("history.file_history", "vcs", [vcs, "log", "-v"], (0, 1, 2)),
492
        Step("history.pickaxe", "vcs", [vcs, "log", "-v"], (0, 1, 2)),
493
    ]
494
495
496
def _nonempty_lines(text: str) -> list[str]:
497
    return [line for line in text.splitlines() if line.strip()]
498
499
500
def _line_count_is(n: int) -> Callable[[str], bool]:
501
    return lambda out: len(_nonempty_lines(out)) == n
502
503
504
def _names_only(present: str, absent: str) -> Callable[[str], bool]:
505
    return lambda out: present in out and absent not in out
506
507
508
def history_archaeology_v2_steps(subject: Subject, track: str) -> list[Step]:
509
    """v2 (2026-11-09): native Oak history commands plus answer oracles.
510
511
    v1 ran unfiltered ``oak log -v`` for file history and pickaxe (Oak lacked
512
    them when it was written) and accepted any of exit 0/1/2, so those steps
513
    always passed. Oak now has ``--oneline``, path filters and ``-S``; v2 uses
514
    them and checks each answer against the fixture's known history:
515
    initial snapshot + 3 history commits = 4 commits; 3 touch app/pricing.py;
516
    exactly 1 adds "surcharge"; the last commit changes only app/pricing.py.
517
    Oak has no ``show``; ``log -n 1 -v`` (changed files of the last commit)
518
    is the closest equivalent of ``git show --stat HEAD``.
519
    """
520
    vcs = str(subject.bin)
521
    recent = (_line_count_is(4), "4 commits in recent history")
522
    last = (_names_only("app/pricing.py", "app/totals.py"), "last commit names app/pricing.py only")
523
    file_hist = (_line_count_is(3), "3 commits touch app/pricing.py")
524
    pickaxe = (_line_count_is(1), "1 commit adds 'surcharge'")
525
    if subject.kind == "git":
526
        commands = {
527
            "history.recent": [vcs, "log", "--oneline", "-15"],
528
            "history.show_last": [vcs, "show", "--stat", "--format=%h", "HEAD"],
529
            "history.file_history": [vcs, "log", "--oneline", "-5", "--", "app/pricing.py"],
530
            "history.pickaxe": [vcs, "log", "-S", "surcharge", "--oneline"],
531
        }
532
    else:
533
        commands = {
534
            "history.recent": [vcs, "log", "--oneline", "-n", "15"],
535
            "history.show_last": [vcs, "log", "-n", "1", "-v"],
536
            "history.file_history": [vcs, "log", "--oneline", "-n", "5", "app/pricing.py"],
537
            "history.pickaxe": [vcs, "log", "-S", "surcharge", "--oneline"],
538
        }
539
    checks = {
540
        "history.recent": recent,
541
        "history.show_last": last,
542
        "history.file_history": file_hist,
543
        "history.pickaxe": pickaxe,
544
    }
545
    return [
546
        Step(op, "vcs", command, answer_check=checks[op][0], answer_description=checks[op][1])
547
        for op, command in commands.items()
548
    ]
549
550
551
def error_recovery_steps(subject: Subject, track: str) -> list[Step]:
552
    # Error output is a prompt: its size and clarity set how many tokens an
553
    # agent burns recovering. Failure-path rows are tolerated (wide expected
554
    # returncodes) so each subject's error text cost is recorded, not skipped.
555
    sem = semantics()
556
    vcs = str(subject.bin)
557
    if subject.kind == "git":
558
        commit_nothing = [vcs, "commit", "-m", "empty"]
559
    else:
560
        commit_nothing = [vcs, *sem.commit_args(subject.kind, "empty")]
561
    return [
562
        Step("error.commit_nothing", "vcs", commit_nothing, (0, 1, 2)),
563
        Step("error.unknown_subcommand", "vcs", [vcs, "stage-all-now"], (0, 1, 2, 101)),
564
        Step("error.status_after", "vcs", [vcs, "status"]),
565
        Step(
566
            "edit.recovery_change",
567
            "edit",
568
            shell("echo '# recovered' >> README.md"),
569
        ),
570
        *snapshot_steps(subject, "vcs.snapshot", "recovered"),
571
    ]
572
573
574
def make_sync_fixture(path: Path) -> None:
575
    (path / "work.txt").write_text("base line\n")
576
    (path / "notes.txt").write_text("shared notes\n")
577
    (path / "README.md").write_text("Sync/divergence recovery fixture for agent workflow benchmarks.\n")
578
579
580
def sync_prepare_steps(subject: Subject, track: str, ctx: dict[str, str]) -> list[Step]:
581
    """Untimed topology: link the repo to a remote, stand up a second checkout
582
    B, and move upstream from B so the measured checkout is behind.
583
584
    Git uses a local bare remote (local_file transport); oak uses the real
585
    server (network transport). Latency rows across subjects in sync workflows
586
    are therefore never comparable — the cross-subject evidence is error-output
587
    tokens, tool calls, and recovery step counts, which transport cannot change.
588
    """
589
    vcs = shlex.quote(str(subject.bin))
590
    bdir = shlex.quote(ctx["clone_b"])
591
    if subject.kind == "git":
592
        rdir = shlex.quote(ctx["remote_dir"])
593
        return [
594
            Step("setup.remote.create", "vcs", shell(f"{vcs} init -q --bare {rdir}")),
595
            Step(
596
                "setup.remote.link",
597
                "vcs",
598
                shell(f"{vcs} remote add origin {rdir} && {vcs} push -q -u origin HEAD"),
599
            ),
600
            Step("setup.remote.clone_b", "vcs", shell(f"{vcs} clone -q {rdir} {bdir}")),
601
            Step(
602
                "setup.upstream.move",
603
                "vcs",
604
                shell(
605
                    f"cd {bdir} && echo 'upstream change' >> notes.txt && "
606
                    f"{vcs} add . && {vcs} commit -q -m upstream && {vcs} push -q origin HEAD"
607
                ),
608
            ),
609
        ]
610
    return [
611
        *oak_clone_a_steps(subject, ctx),
612
        Step("setup.remote.clone_b", "vcs", shell(f"{vcs} clone {shlex.quote(ctx['oak_repo'])} {bdir}")),
613
        # B joins the shared branch (it descends from seeded main, so switch
614
        # pulls it) and moves it. Commit is local-only in current Oak, so setup
615
        # explicitly uses --push to publish the upstream actor's change.
616
        Step(
617
            "setup.upstream.move",
618
            "vcs",
619
            shell(
620
                f"cd {bdir} && {vcs} switch {shlex.quote(ctx['branch'])} && "
621
                f"echo 'upstream change' >> notes.txt && "
622
                f"{vcs} commit --no-verify --push"
623
            ),
624
        ),
625
    ]
626
627
628
# Reads the auto-generated current branch name so it can be renamed to the
629
# run's collision-safe bench branch (rename syncs to the server).
630
OAK_CURRENT_BRANCH_SNIPPET = (
631
    "branch list --json | /usr/bin/env python3 -c "
632
    '\'import json,sys; print(next(b["name"] for b in json.load(sys.stdin) if b.get("current")))\''
633
)
634
635
636
def oak_clone_a_steps(subject: Subject, ctx: dict[str, str]) -> list[Step]:
637
    """Untimed oak topology: clone A, seed the disposable repo's main with the
638
    static fixture once (idempotent — identical bytes merge as a no-op), and
639
    publish the run's shared bench branch via rename + explicit commit --push."""
640
    vcs = shlex.quote(str(subject.bin))
641
    adir = shlex.quote(ctx["clone_a"])
642
    repo = shlex.quote(ctx["oak_repo"])
643
    branch = shlex.quote(ctx["branch"])
644
    fixture_dir = shlex.quote(f"../{ctx['repo_dir']}")
645
    return [
646
        Step("setup.remote.clone_a", "vcs", shell(f"{vcs} clone {repo} {adir}")),
647
        Step(
648
            "setup.remote.seed_main",
649
            "vcs",
650
            shell(
651
                f"cd {adir} && if [ ! -f work.txt ]; then "
652
                f"cp {fixture_dir}/work.txt {fixture_dir}/notes.txt {fixture_dir}/README.md . && "
653
                f"{vcs} commit --no-verify --push && {vcs} merge; fi"
654
            ),
655
        ),
656
        # Commit and publish the auto-named branch, then rename: rename only
657
        # resolves a branch that exists server-side.
658
        Step(
659
            "setup.remote.link",
660
            "vcs",
661
            shell(
662
                f"cd {adir} && echo 'link line' >> README.md && {vcs} commit --no-verify --push && "
663
                f"cur=$({vcs} {OAK_CURRENT_BRANCH_SNIPPET}) && "
664
                f"{vcs} branch rename \"$cur\" {branch}"
665
            ),
666
        ),
667
    ]
668
669
670
def sync_push_divergence_steps(subject: Subject, track: str, ctx: dict[str, str]) -> list[Step]:
671
    # The trap an agent hits when any other actor pushed first. Expected
672
    # returncodes encode each subject's observed remote-failure contract; a
673
    # step that "fails to fail" still converges at verify.payload. Error
674
    # output is a prompt: the rejected push's text is what the agent reasons
675
    # from, and its cost is the measurement.
676
    vcs = str(subject.bin)
677
    verify = Step(
678
        "verify.payload",
679
        "read",
680
        shell("grep -q 'local change' work.txt && grep -q 'upstream change' notes.txt"),
681
    )
682
    if subject.kind == "git":
683
        return [
684
            Step("edit.local_change", "edit", shell("echo 'local change' >> work.txt")),
685
            *snapshot_steps(subject, "vcs.snapshot", "local change"),
686
            # Rejected non-fast-forward push; stderr says to pull.
687
            Step("error.push_diverged", "vcs", [vcs, "push"], (1,), recovery_hint="git pull"),
688
            # Following the hint verbatim fails again until a strategy is
689
            # chosen: fatal "Need to specify how to reconcile divergent
690
            # branches" (exit 128).
691
            Step("error.pull_unconfigured", "vcs", [vcs, "pull"], (128,), recovery_hint="--rebase"),
692
            Step("recovery.pull_rebase", "vcs", [vcs, "pull", "--rebase"]),
693
            Step("recovery.push_after", "vcs", [vcs, "push"]),
694
            verify,
695
        ]
696
    return [
697
        Step("edit.local_change", "edit", shell("echo 'local change' >> work.txt")),
698
        # oak commit is a local checkpoint. The publish failure is measured in
699
        # the explicit push row below.
700
        Step("vcs.snapshot", "vcs", [vcs, "commit", "--no-verify"], (0,)),
701
        Step("error.push_diverged", "vcs", [vcs, "push"], (0, 1, 5), recovery_hint="pull"),
702
        # The push error says "Pull changes first" — but pull also exits 5 on
703
        # a diverged branch and suggests only the destructive pull --force.
704
        Step("error.pull_diverged", "vcs", [vcs, "pull"], (5,), recovery_hint="pull --force"),
705
        # pull --force discards the local commit (observed: committed content
706
        # reverts). Recovery therefore includes redoing the lost work.
707
        Step("recovery.pull_force", "vcs", [vcs, "pull", "--force"]),
708
        Step("edit.redo_change", "edit", shell("echo 'local change' >> work.txt")),
709
        *snapshot_steps(subject, "vcs.snapshot.redo", "local change redo"),
710
        Step("recovery.push_after", "vcs", [vcs, "push"]),
711
        verify,
712
    ]
713
714
715
def sync_pull_upstream_steps(subject: Subject, track: str, ctx: dict[str, str]) -> list[Step]:
716
    # The everyday task-start motion: upstream moved, local tree clean.
717
    vcs = str(subject.bin)
718
    sem = semantics()
719
    return [
720
        Step("vcs.status", "vcs", [vcs, *sem.status_args(subject.kind, track)]),
721
        Step("sync.pull_upstream", "vcs", [vcs, "pull"]),
722
        Step("verify.payload", "read", shell("grep -q 'upstream change' notes.txt")),
723
    ]
724
725
726
def sync_amend_prepare_steps(subject: Subject, track: str, ctx: dict[str, str]) -> list[Step]:
727
    """Untimed: link the repo to a remote and push — no second actor. The
728
    divergence in this workflow is self-inflicted (history rewrite after
729
    push), so upstream never moves."""
730
    vcs = shlex.quote(str(subject.bin))
731
    if subject.kind == "git":
732
        rdir = shlex.quote(ctx["remote_dir"])
733
        return [
734
            Step("setup.remote.create", "vcs", shell(f"{vcs} init -q --bare {rdir}")),
735
            Step(
736
                "setup.remote.link",
737
                "vcs",
738
                shell(f"{vcs} remote add origin {rdir} && {vcs} push -q -u origin HEAD"),
739
            ),
740
        ]
741
    return oak_clone_a_steps(subject, ctx)
742
743
744
def sync_non_ff_after_amend_steps(subject: Subject, track: str, ctx: dict[str, str]) -> list[Step]:
745
    # The self-inflicted trap: fix the last commit after it was pushed. Git
746
    # reproduces it exactly (amend rewrites the pushed tip; push is rejected;
747
    # the error text suggests pull — which would merge the old tip back — not
748
    # the --force-with-lease an agent actually needs, so the actionability
749
    # check is expected to FAIL and that failure is the finding). Oak cannot
750
    # rewrite history (commits carry no messages; `oak desc` edits the branch
751
    # description), so the same intent is a follow-up commit with no trap:
752
    # zero error rows and zero recovery steps IS oak's measurement here.
753
    vcs = str(subject.bin)
754
    if subject.kind == "git":
755
        return [
756
            Step("edit.fix_last_commit", "edit", shell("echo 'amended line' >> work.txt")),
757
            Step(
758
                "vcs.amend",
759
                "vcs",
760
                shell(f"{shlex.quote(vcs)} add . && {shlex.quote(vcs)} commit -q --amend --no-edit"),
761
            ),
762
            Step("error.push_non_ff", "vcs", [vcs, "push"], (1,), recovery_hint="--force-with-lease"),
763
            Step("recovery.push_force_lease", "vcs", [vcs, "push", "--force-with-lease"]),
764
            Step("verify.payload", "read", shell("grep -q 'amended line' work.txt")),
765
        ]
766
    return [
767
        Step("edit.fix_last_commit", "edit", shell("echo 'amended line' >> work.txt")),
768
        *snapshot_steps(subject, "vcs.snapshot", "amended line"),
769
        Step("recovery_free.desc_update", "vcs", [vcs, "desc", "amended: follow-up fix"]),
770
        Step("recovery_free.push_after", "vcs", [vcs, "push"], (0,)),
771
        Step("verify.payload", "read", shell("grep -q 'amended line' work.txt")),
772
    ]
773
774
775
def sync_pull_dirty_steps(subject: Subject, track: str, ctx: dict[str, str]) -> list[Step]:
776
    # Same motion with uncommitted local edits to a different file — the
777
    # working state agents are usually in when they remember to sync.
778
    # The oracle is split so a failure names what was lost. The pull row
779
    # accepts both refusal and success contracts; the follow-up payload checks
780
    # report whether upstream and local dirty content survived.
781
    vcs = str(subject.bin)
782
    sem = semantics()
783
    return [
784
        Step("edit.dirty_change", "edit", shell("echo 'dirty local edit' >> work.txt")),
785
        Step("vcs.status", "vcs", [vcs, *sem.status_args(subject.kind, track)]),
786
        Step("sync.pull_dirty", "vcs", [vcs, "pull"], (0, 1, 2, 4, 5)),
787
        Step("verify.upstream_payload", "read", shell("grep -q 'upstream change' notes.txt")),
788
        Step("verify.local_payload", "read", shell("grep -q 'dirty local edit' work.txt")),
789
    ]
790
791
792
WORKFLOWS: dict[str, Workflow] = {
793
    "bugfix_test_loop": Workflow(
794
        "bugfix_test_loop",
795
        "Search, reproduce failing test, patch one source file, rerun tests, inspect and snapshot.",
796
        make_bugfix_fixture,
797
        bugfix_steps,
798
    ),
799
    "wide_config_refactor": Workflow(
800
        "wide_config_refactor",
801
        "Search and rewrite hundreds of small config files, validate, inspect and snapshot.",
802
        make_wide_config_fixture,
803
        wide_config_steps,
804
    ),
805
    "large_asset_manifest": Workflow(
806
        "large_asset_manifest",
807
        "Inspect large binary asset repo, edit small manifest only, validate, inspect and snapshot.",
808
        make_large_asset_fixture,
809
        large_asset_steps,
810
    ),
811
    "history_archaeology": Workflow(
812
        "history_archaeology",
813
        "Answer common history questions: recent commits, last change detail, file history, term search.",
814
        make_history_fixture,
815
        history_archaeology_steps,
816
        prepare=history_prepare_steps,
817
    ),
818
    "history_archaeology_v2": Workflow(
819
        "history_archaeology_v2",
820
        "Answer common history questions with each VCS's native commands; every answer is checked "
821
        "against the fixture's known history.",
822
        make_history_fixture,
823
        history_archaeology_v2_steps,
824
        prepare=history_prepare_steps,
825
    ),
826
    "vcs_error_recovery": Workflow(
827
        "vcs_error_recovery",
828
        "Hit common VCS errors (empty commit, unknown subcommand), then recover; measures error-output token cost.",
829
        make_history_fixture,
830
        error_recovery_steps,
831
    ),
832
    "sync_push_divergence": Workflow(
833
        "sync_push_divergence",
834
        "Push rejected because upstream moved, then the full recovery arc. "
835
        "Cross-subject evidence is tokens/calls/steps, never latency: git syncs a "
836
        "local bare remote, oak a real server.",
837
        make_sync_fixture,
838
        sync_push_divergence_steps,
839
        prepare=sync_prepare_steps,
840
        remote_purpose="sync",
841
    ),
842
    "sync_pull_upstream": Workflow(
843
        "sync_pull_upstream",
844
        "Clean-tree pull with upstream changes — the task-start sync motion. "
845
        "Latency is transport-dependent; compare tokens and calls only.",
846
        make_sync_fixture,
847
        sync_pull_upstream_steps,
848
        prepare=sync_prepare_steps,
849
        remote_purpose="sync",
850
    ),
851
    "sync_pull_dirty": Workflow(
852
        "sync_pull_dirty",
853
        "Pull with upstream changes while holding uncommitted local edits. "
854
        "Latency is transport-dependent; compare tokens and calls only.",
855
        make_sync_fixture,
856
        sync_pull_dirty_steps,
857
        prepare=sync_prepare_steps,
858
        remote_purpose="sync",
859
    ),
860
    "sync_non_ff_after_amend": Workflow(
861
        "sync_non_ff_after_amend",
862
        "Fix the last commit after pushing. Git: amend rewrites the pushed tip, "
863
        "push is rejected, recovery needs --force-with-lease (which the error "
864
        "text does not suggest). Oak: history rewrite does not exist, so the "
865
        "same intent is a trap-free follow-up commit — zero recovery steps is "
866
        "the measurement, not a missing row.",
867
        make_sync_fixture,
868
        sync_non_ff_after_amend_steps,
869
        prepare=sync_amend_prepare_steps,
870
        remote_purpose="sync",
871
    ),
872
}
873
874
875
def sync_context(
876
    subject: Subject,
877
    workflow: Workflow,
878
    run_index: int,
879
    metadata: dict[str, Any],
880
) -> tuple[dict[str, str] | None, str | None, dict[str, Any]]:
881
    """Per-run remote context for remote_purpose workflows.
882
883
    Returns (ctx, skip_reason, remote_row_fields). ctx is None when the
884
    subject's remote is not configured; the lane emits a skip row instead.
885
    """
886
    branch = oakbench_remotes.disposable_branch(
887
        str(metadata.get("bench_id", "bench")), workflow.name, subject.name, run_index
888
    )
889
    ctx: dict[str, str] = {
890
        "branch": branch,
891
        "remote_dir": f"../remote-run-{run_index}.git",
892
        "clone_b": f"../clone-b-run-{run_index}",
893
    }
894
    if subject.kind != "git":
895
        resolution = oakbench_remotes.resolve_oak_remote(workflow.remote_purpose or "default")
896
        if not resolution.resolved:
897
            return None, resolution.skip_reason, {}
898
        capability_skip = oak_commit_push_skip_reason(subject)
899
        if capability_skip is not None:
900
            return None, capability_skip, resolution.row_fields()
901
        ctx["oak_repo"] = resolution.repo or ""
902
        # Oak topology is clone-based: every branch must descend from the
903
        # disposable repo's seeded main (locally-init'ed history is invisible
904
        # to other clones). Measured steps run inside clone A, the checkout
905
        # that hits the trap; the local fixture copy only seeds main.
906
        ctx["clone_a"] = f"../clone-a-run-{run_index}"
907
        ctx["repo_dir"] = f"run-{run_index}"
908
        ctx["measure_dir"] = ctx["clone_a"]
909
        return ctx, None, resolution.row_fields()
910
    return ctx, None, {
911
        "remote_repo": ctx["remote_dir"],
912
        "remote_transport": oakbench_remotes.TRANSPORT_LOCAL_FILE,
913
        "remote_server": "local",
914
    }
915
916
917
def workflow_skip_row(
918
    subject: Subject,
919
    workflow: Workflow,
920
    run_index: int,
921
    metadata: dict[str, Any],
922
    reason: str,
923
) -> dict[str, Any]:
924
    return {
925
        **metadata,
926
        "subject": subject.name,
927
        "subject_kind": subject.kind,
928
        "subject_label": subject.label,
929
        "scenario": workflow.name,
930
        "workflow": workflow.name,
931
        "workflow_description": workflow.description,
932
        "run": run_index,
933
        "phase": "workflow",
934
        "operation": "workflow.skipped",
935
        "step_kind": "summary",
936
        "elapsed_ms": 0.0,
937
        "returncode": 77,
938
        "process_returncode": 77,
939
        "command": [],
940
        "skipped": True,
941
        "skip_reason": reason,
942
        "tool_call_count": 0,
943
        "terminal_tool_call_count": 0,
944
        "vcs_tool_call_count": 0,
945
        "test_tool_call_count": 0,
946
    }
947
948
949
def load_tier_skip_rows(
950
    subjects: list[Subject],
951
    workflows: list[Workflow],
952
    runs: int,
953
    metadata: dict[str, Any],
954
    reason: str,
955
    load_tier: str,
956
) -> list[dict[str, Any]]:
957
    """Explicit skip rows for a load tier the host cannot apply.
958
959
    One row per workflow x run x subject; environment_suspect is None because
960
    the suspicion machinery never ran (ADR-0002), and load_tier records the
961
    REQUESTED tier — load that was not applied is never claimed.
962
    """
963
    rows: list[dict[str, Any]] = []
964
    for workflow in workflows:
965
        for run_index in range(runs):
966
            for subject in subjects:
967
                row = workflow_skip_row(subject, workflow, run_index, metadata, reason)
968
                row["load_tier"] = load_tier
969
                row["environment_suspect"] = None
970
                rows.append(row)
971
    return rows
972
973
974
def interaction_metrics(
975
    command: list[str],
976
    stdout_text: str,
977
    stderr_text: str,
978
    stdout_bytes: int,
979
    stderr_bytes: int,
980
    stdout_truncated: bool,
981
    stderr_truncated: bool,
982
    step: Step,
983
) -> dict[str, Any]:
984
    is_vcs = 1 if step.kind == "vcs" else 0
985
    is_test = 1 if step.kind == "test" else 0
986
    return {
987
        "tool_call_count": 1,
988
        "terminal_tool_call_count": 1,
989
        "vcs_tool_call_count": is_vcs,
990
        "test_tool_call_count": is_test,
991
        **oakbench_tokens.interaction_token_fields(
992
            command_display(command),
993
            stdout_text,
994
            stderr_text,
995
            stdout_bytes,
996
            stderr_bytes,
997
            stdout_truncated,
998
            stderr_truncated,
999
        ),
1000
        "tool_calls": {
1001
            "total": 1,
1002
            "terminal": 1,
1003
            "vcs": is_vcs,
1004
            "test": is_test,
1005
            step.kind: 1,
1006
        },
1007
    }
1008
1009
1010
def run_step(
1011
    subject: Subject,
1012
    workflow: Workflow,
1013
    step: Step,
1014
    cwd: Path,
1015
    run_index: int,
1016
    phase: str,
1017
    metadata: dict[str, Any],
1018
    admitted_output_chars: int,
1019
) -> dict[str, Any]:
1020
    capture = run_timed(step.command, cwd, step_env(step), admitted_output_chars)
1021
    expected = capture.returncode in step.expected_returncodes
1022
    row = {
1023
        **metadata,
1024
        "subject": subject.name,
1025
        "subject_kind": subject.kind,
1026
        "subject_label": subject.label,
1027
        "scenario": workflow.name,
1028
        "workflow": workflow.name,
1029
        "workflow_description": workflow.description,
1030
        "run": run_index,
1031
        "phase": phase,
1032
        "operation": step.operation,
1033
        "step_kind": step.kind,
1034
        "elapsed_ms": round(capture.elapsed_ms, 3),
1035
        "returncode": 0 if expected else (capture.returncode or 1),
1036
        "process_returncode": capture.returncode,
1037
        "expected_returncodes": list(step.expected_returncodes),
1038
        "command": step.command,
1039
        **interaction_metrics(
1040
            step.command,
1041
            capture.stdout_text,
1042
            capture.stderr_text,
1043
            capture.stdout_bytes,
1044
            capture.stderr_bytes,
1045
            capture.stdout_truncated,
1046
            capture.stderr_truncated,
1047
            step,
1048
        ),
1049
    }
1050
    if not expected:
1051
        row["stderr"] = capture.stderr_text[-4000:]
1052
    if step.recovery_hint is not None:
1053
        combined = (capture.stdout_text + capture.stderr_text).lower()
1054
        row["recovery_hint"] = step.recovery_hint
1055
        row["error_mentions_recovery_command"] = step.recovery_hint.lower() in combined
1056
        row["error_actionability_source"] = "output_contains_recovery_command"
1057
    if step.answer_check is not None:
1058
        row["answer_check"] = step.answer_description
1059
        if capture.stdout_truncated:
1060
            row["answer_correct"] = None
1061
            row["answer_unmeasured_reason"] = "stdout_truncated_by_admitted_output_cap"
1062
        else:
1063
            correct = bool(step.answer_check(capture.stdout_text))
1064
            row["answer_correct"] = correct
1065
            if expected and not correct:
1066
                row["returncode"] = 1
1067
                row["failure_reason"] = f"wrong_answer: {step.answer_description}"
1068
                row["stdout"] = capture.stdout_text[-4000:]
1069
    return row
1070
1071
1072
def snapshot_step_requires_state_change(operation: str) -> bool:
1073
    return operation in {"setup.snapshot", "vcs.snapshot", "vcs.snapshot.redo"} or (
1074
        ".snapshot" in operation and operation.endswith(".commit")
1075
    )
1076
1077
1078
def branch_step_requires_state_change(operation: str) -> bool:
1079
    return operation == "vcs.branch"
1080
1081
1082
def apply_state_change_attestation(
1083
    row: dict[str, Any],
1084
    repo: Path,
1085
    before_fingerprint: str | None,
1086
    operation: str,
1087
    *,
1088
    expected_hashes: dict[str, str] | None = None,
1089
    expected_payloads: dict[str, str | bytes] | None = None,
1090
) -> dict[str, Any]:
1091
    raw_process_returncode = row.get("process_returncode")
1092
    if raw_process_returncode is None:
1093
        process_returncode = row_returncode(row)
1094
    else:
1095
        try:
1096
            process_returncode = int(raw_process_returncode)
1097
        except (TypeError, ValueError):
1098
            process_returncode = 1
1099
    fields = oakbench_integrity.state_change_fields(
1100
        repo,
1101
        before_fingerprint,
1102
        operation=operation,
1103
        process_returncode=process_returncode,
1104
    )
1105
    row.update(fields)
1106
    failure_reason = fields["integrity_failure_reason"] if not fields["integrity_check_passed"] else None
1107
    if expected_hashes or expected_payloads:
1108
        content_fields = oakbench_integrity.content_integrity_fields(
1109
            repo,
1110
            operation=operation,
1111
            process_returncode=process_returncode,
1112
            expected_hashes=expected_hashes,
1113
            expected_payloads=expected_payloads,
1114
        )
1115
        row.update(content_fields)
1116
        # None is unmeasured (reader unavailable), never a failure or a pass.
1117
        if content_fields["content_integrity_check_passed"] is False and failure_reason is None:
1118
            failure_reason = content_fields["content_integrity_failure_reason"]
1119
    if process_returncode == 0 and failure_reason is not None:
1120
        row["returncode"] = 1
1121
        row["stderr"] = str(failure_reason or "integrity_check_failed")
1122
    return row
1123
1124
1125
def workflow_step_payload_requirements(workflow: Workflow, operation: str) -> list[tuple[str, str]]:
1126
    """Content payloads required at an intermediate step.
1127
1128
    Final workflow integrity can require the fully converged payload. Snapshot
1129
    steps must only require payloads that are expected to exist in that phase.
1130
    """
1131
    if workflow.name == "sync_push_divergence" and operation in {
1132
        "vcs.snapshot",
1133
        "vcs.snapshot.commit",
1134
        "vcs.snapshot.redo",
1135
        "vcs.snapshot.redo.commit",
1136
    }:
1137
        return [("work.txt", "local change")]
1138
    return []
1139
1140
1141
def apply_content_payload_attestation(
1142
    row: dict[str, Any],
1143
    repo: Path,
1144
    expected_payloads: list[tuple[str, str]],
1145
) -> dict[str, Any]:
1146
    if not expected_payloads:
1147
        return row
1148
    fields = oakbench_integrity.content_payload_fields(repo, expected_payloads)
1149
    row.update(fields)
1150
    if row_returncode(row) == 0 and not fields["content_payload_check_passed"]:
1151
        reason = str(fields["content_payload_failure_reason"] or "content_payload_check_failed")
1152
        row["returncode"] = 1
1153
        row["process_returncode"] = 1
1154
        row["stderr"] = reason
1155
        row["integrity_check_passed"] = False
1156
        row["integrity_failure_reason"] = reason
1157
        row["integrity_check_source"] = "content_payload_attestation"
1158
    return row
1159
1160
1161
def run_attested_step(
1162
    subject: Subject,
1163
    workflow: Workflow,
1164
    step: Step,
1165
    cwd: Path,
1166
    run_index: int,
1167
    phase: str,
1168
    metadata: dict[str, Any],
1169
    admitted_output_chars: int,
1170
) -> dict[str, Any]:
1171
    requires_state_change = snapshot_step_requires_state_change(step.operation) or branch_step_requires_state_change(
1172
        step.operation
1173
    )
1174
    before = oakbench_integrity.repository_state_fingerprint(cwd) if requires_state_change else None
1175
    expected_hashes = None
1176
    expected_payloads = None
1177
    if snapshot_step_requires_state_change(step.operation):
1178
        expected_hashes = oakbench_integrity.sample_worktree_payload_hashes(cwd)
1179
        if phase == "workflow":
1180
            expected_payloads = workflow_snapshot_payload_expectations(workflow)
1181
    row = run_step(subject, workflow, step, cwd, run_index, phase, metadata, admitted_output_chars)
1182
    if requires_state_change:
1183
        apply_state_change_attestation(
1184
            row,
1185
            cwd,
1186
            before,
1187
            step.operation,
1188
            expected_hashes=expected_hashes,
1189
            expected_payloads=expected_payloads,
1190
        )
1191
    apply_content_payload_attestation(
1192
        row,
1193
        cwd,
1194
        workflow_step_payload_requirements(workflow, step.operation),
1195
    )
1196
    return row
1197
1198
1199
def _read_text(path: Path) -> str | None:
1200
    try:
1201
        return path.read_text(errors="replace")
1202
    except OSError:
1203
        return None
1204
1205
1206
def workflow_snapshot_payload_expectations(workflow: Workflow) -> dict[str, str]:
1207
    return workflow_oracles.COMMITTED_PAYLOADS.get(workflow.name, {
1208
        "wide_config_refactor": {"services/service-0000/config.toml": "timeout_ms = 3000"},
1209
        "large_asset_manifest": {"manifest.json": '\"reviewed\": true'},
1210
    }.get(workflow.name, {}))
1211
1212
1213
def workflow_worktree_payload_failure(workflow: Workflow, repo: Path) -> str | None:
1214
    name = workflow.name
1215
    if name == "bugfix_test_loop":
1216
        text = _read_text(repo / "app" / "pricing.py")
1217
        expected = "return cents - ((cents * percent) // 100)"
1218
        return None if text is not None and expected in text else "missing bugfix payload in app/pricing.py"
1219
    if name in workflow_oracles.SCENARIOS:
1220
        return workflow_oracles.validate(name, repo)
1221
    if name == "vcs_error_recovery":
1222
        text = _read_text(repo / "README.md")
1223
        return None if text is not None and "# recovered" in text else "recovery payload missing in README.md"
1224
    if name == "sync_push_divergence":
1225
        work = _read_text(repo / "work.txt") or ""
1226
        notes = _read_text(repo / "notes.txt") or ""
1227
        if "local change" not in work:
1228
            return "local pushed payload missing from work.txt"
1229
        if "upstream change" not in notes:
1230
            return "upstream pulled payload missing from notes.txt"
1231
        return None
1232
    if name == "sync_pull_upstream":
1233
        notes = _read_text(repo / "notes.txt") or ""
1234
        return None if "upstream change" in notes else "upstream pulled payload missing from notes.txt"
1235
    if name == "sync_pull_dirty":
1236
        work = _read_text(repo / "work.txt") or ""
1237
        notes = _read_text(repo / "notes.txt") or ""
1238
        if "dirty local edit" not in work:
1239
            return "dirty local payload missing from work.txt"
1240
        if "upstream change" not in notes:
1241
            return "upstream pulled payload missing from notes.txt"
1242
        return None
1243
    if name == "sync_non_ff_after_amend":
1244
        work = _read_text(repo / "work.txt") or ""
1245
        return None if "amended line" in work else "amended payload missing from work.txt"
1246
    return None
1247
1248
1249
def _git_head_text(repo: Path, path: str, git_binary: str | None = None, resolved_instrument=None) -> tuple[str | None, str | None]:
1250
    return workflow_oracles.git_head_text(repo, path, git_binary, resolved_instrument=resolved_instrument)
1251
1252
1253
def workflow_git_head_payload_failure(workflow: Workflow, repo: Path, git_binary: str | None = None, resolved_instrument=None) -> str | None:
1254
    if workflow.name in workflow_oracles.SCENARIOS:
1255
        return workflow_oracles.validate_git_head(workflow.name, repo, git_binary, resolved_instrument=resolved_instrument)
1256
    checks = workflow_snapshot_payload_expectations(workflow)
1257
    if not checks:
1258
        return None
1259
    for path, expected in checks.items():
1260
        text, error = _git_head_text(repo, path, git_binary, resolved_instrument)
1261
        if error is not None:
1262
            return error
1263
        if text is None or expected not in text:
1264
            return f"committed_payload_missing:{path}"
1265
    return None
1266
1267
1268
def workflow_integrity_fields(
1269
    subject: Subject,
1270
    workflow: Workflow,
1271
    repo: Path,
1272
    workflow_rows: list[dict[str, Any]],
1273
) -> dict[str, Any]:
1274
    failures = [row for row in workflow_rows if row_returncode(row) != 0]
1275
    snapshot_failures = [
1276
        row
1277
        for row in workflow_rows
1278
        if row.get("integrity_check_passed") is False or row.get("content_integrity_check_passed") is False
1279
    ]
1280
    if workflow.name in workflow_oracles.SCENARIOS and not failures and not snapshot_failures:
1281
        evidence = workflow_oracles.task_evidence(workflow.name, repo, subject.kind, str(subject.bin))
1282
        return {**evidence, "correctness_passed": evidence["workflow_integrity_passed"],
1283
                "correctness_failure_reason": evidence["workflow_integrity_failure_reason"]}
1284
    reason: str | None = None
1285
    source = "trusted_exact_task_worktree" if workflow.name in workflow_oracles.SCENARIOS else "worktree_payload_oracle"
1286
    if failures:
1287
        first = failures[0]
1288
        reason = str(
1289
            first.get("integrity_failure_reason")
1290
            or first.get("content_integrity_failure_reason")
1291
            or f"workflow_step_failed:{first.get('operation')}"
1292
        )
1293
    elif snapshot_failures:
1294
        first = snapshot_failures[0]
1295
        reason = str(
1296
            first.get("integrity_failure_reason")
1297
            or first.get("content_integrity_failure_reason")
1298
            or f"snapshot_integrity_failed:{first.get('operation')}"
1299
        )
1300
1301
    if reason is None:
1302
        reason = workflow_worktree_payload_failure(workflow, repo)
1303
1304
    reader_fields = {}
1305
    evidence_class = "worktree_payload"
1306
    if reason is None and subject.kind == "git" and workflow_snapshot_payload_expectations(workflow):
1307
        instrument, reader_fields = workflow_oracles.resolve_git_instrument()
1308
        reason = "git_head_oracle_unavailable" if instrument is None else workflow_git_head_payload_failure(workflow, repo, resolved_instrument=(instrument, reader_fields))
1309
        if instrument is not None and reason is not None:
1310
            evidence_class = "committed_payload_attempt"
1311
            source += ";git_head_payload_read_attempt"
1312
        if reason is None:
1313
            reader_fields.update(workflow_oracles.reader_evidence("git", str(subject.bin), reader_fields))
1314
            evidence_class = reader_fields.pop("workflow_integrity_evidence_class").replace("_tree", "_payload")
1315
            source += ";" + evidence_class
1316
    elif reason is None and subject.kind == "oak" and workflow_snapshot_payload_expectations(workflow):
1317
        # Same committed-payload check as the Git arm, read by the independent
1318
        # stdlib Oak reader (no Oak code or binary).
1319
        from oakbench import oak_sqlite_reader as oak_reader
1320
        checks = workflow_snapshot_payload_expectations(workflow)
1321
        try:
1322
            payloads, meta = oak_reader.committed_payloads(repo, list(checks))
1323
        except oak_reader.Invalid as exc:
1324
            reason = f"oak_stored_content_invalid:{exc}"
1325
            evidence_class, meta = "committed_payload_attempt", {}
1326
        except (oak_reader.Unavailable, OSError, ValueError) as exc:
1327
            reason, meta = f"oak_reader_unavailable:{exc}", {}
1328
        else:
1329
            for path, expected in checks.items():
1330
                data = payloads.get(path)
1331
                if data is None or expected not in data.decode("utf-8", "replace"):
1332
                    reason = f"committed_payload_missing:{path}"
1333
                    break
1334
            evidence_class = "independent_committed_payload" if reason is None else "committed_payload_attempt"
1335
        source += ";independent_oak_reader_payload_read"
1336
        reader_fields = {"oak_reader_version": oak_reader.READER_VERSION, "oak_reader_head": meta.get("head"),
1337
                         "oak_reader_backend": meta.get("reader_backend")}
1338
    elif reason is None and any(row.get("integrity_check_passed") is True for row in workflow_rows):
1339
        source += ";direct_repo_metadata_fingerprint"
1340
        evidence_class = "repository_metadata"
1341
1342
    unavailable = (reason in {"git_head_oracle_unavailable", "known_good_git_unavailable_for_head_payload_check"}
1343
                   or str(reason).startswith("oak_reader_unavailable:"))
1344
    passed = None if unavailable else reason is None
1345
    return {
1346
        "oracle_version": workflow_oracles.VERSION,
1347
        "workflow_integrity_passed": passed,
1348
        "workflow_integrity_failure_reason": reason,
1349
        "workflow_integrity_source": source,
1350
        **reader_fields,
1351
        "workflow_integrity_evidence_class": evidence_class,
1352
        "workflow_integrity_unmeasured_reason": reason if unavailable else None,
1353
        "correctness_passed": passed,
1354
        "correctness_failure_reason": reason,
1355
    }
1356
1357
1358
def recovery_metrics_row(
1359
    workflow_rows: list[dict[str, Any]],
1360
    metadata: dict[str, Any],
1361
    subject: Subject,
1362
    workflow: Workflow,
1363
    run_index: int,
1364
) -> dict[str, Any] | None:
1365
    """Derived recovery-cost row for workflows that hit expected failures.
1366
1367
    Error output is a prompt: the rejected command's text is what the agent
1368
    reasons from. This row prices that text (model-input tokens) and the
1369
    recovery arc that follows it. tool_call_count is 0 — the row performs no
1370
    calls and must not perturb tool-call or token deltas (bench.py probe-row
1371
    precedent).
1372
    """
1373
    error_rows = [r for r in workflow_rows if str(r.get("operation", "")).startswith("error.")]
1374
    recovery_prefixes = ("recovery.", "edit.redo", "vcs.snapshot.redo")
1375
    recovery_free_prefixes = ("recovery_free.",)
1376
    recovery_rows = [
1377
        r for r in workflow_rows if str(r.get("operation", "")).startswith(recovery_prefixes)
1378
    ]
1379
    recovery_free_rows = [
1380
        r for r in workflow_rows if str(r.get("operation", "")).startswith(recovery_free_prefixes)
1381
    ]
1382
    if not error_rows and not recovery_rows and not recovery_free_rows:
1383
        return None
1384
    hinted = [r for r in error_rows if "error_mentions_recovery_command" in r]
1385
    actionable = [r for r in hinted if r.get("error_mentions_recovery_command")]
1386
    return {
1387
        **metadata,
1388
        "subject": subject.name,
1389
        "subject_kind": subject.kind,
1390
        "subject_label": subject.label,
1391
        "scenario": workflow.name,
1392
        "workflow": workflow.name,
1393
        "workflow_description": workflow.description,
1394
        "run": run_index,
1395
        "phase": "workflow",
1396
        "operation": "sync.recovery_metrics",
1397
        "step_kind": "summary",
1398
        "elapsed_ms": 0.0,
1399
        "returncode": 0,
1400
        "process_returncode": 0,
1401
        "command": [],
1402
        "tool_call_count": 0,
1403
        "terminal_tool_call_count": 0,
1404
        "vcs_tool_call_count": 0,
1405
        "test_tool_call_count": 0,
1406
        "error_steps_count": len(error_rows),
1407
        # The failure text an agent must ingest before it can act, priced as
1408
        # model input (output of the tool, input to the model).
1409
        "error_output_tokens": sum(int(r.get("estimated_tokens_output", 0)) for r in error_rows),
1410
        "recovery_steps_count": len(recovery_rows),
1411
        "recovery_wall_ms": round(sum(float(r.get("elapsed_ms", 0)) for r in recovery_rows), 3),
1412
        "recovery_tokens_total": round(
1413
            sum(float(r.get("estimated_cost_weighted_tokens_with_envelope", 0)) for r in recovery_rows), 1
1414
        ),
1415
        "error_steps_with_hint": len(hinted),
1416
        "error_steps_hint_actionable": len(actionable),
1417
        # Null when no step declared a hint: unmeasured, never a fabricated pass.
1418
        "error_actionability": (len(actionable) == len(hinted)) if hinted else None,
1419
        "measurement_source": "derived_from_workflow_rows; hint check is output_contains_recovery_command",
1420
        "summarized_operations": [r["operation"] for r in error_rows + recovery_rows + recovery_free_rows],
1421
    }
1422
1423
1424
def sum_rows(
1425
    rows: list[dict[str, Any]],
1426
    metadata: dict[str, Any],
1427
    subject: Subject,
1428
    workflow: Workflow,
1429
    run_index: int,
1430
    phase: str,
1431
    operation: str,
1432
    extra_fields: dict[str, Any] | None = None,
1433
) -> dict[str, Any]:
1434
    elapsed_ms = sum(float(row.get("elapsed_ms", 0)) for row in rows)
1435
    tool_calls = sum(oakbench_tokens.int_or_zero(row.get("tool_call_count")) for row in rows)
1436
    terminal_calls = sum(oakbench_tokens.int_or_zero(row.get("terminal_tool_call_count")) for row in rows)
1437
    vcs_calls = sum(oakbench_tokens.int_or_zero(row.get("vcs_tool_call_count")) for row in rows)
1438
    test_calls = sum(oakbench_tokens.int_or_zero(row.get("test_tool_call_count")) for row in rows)
1439
    failures = [row for row in rows if row_returncode(row) != 0]
1440
    steps_total = len(rows)
1441
    steps_failed = len(failures)
1442
    result = {
1443
        **metadata,
1444
        "subject": subject.name,
1445
        "subject_kind": subject.kind,
1446
        "subject_label": subject.label,
1447
        "scenario": workflow.name,
1448
        "workflow": workflow.name,
1449
        "workflow_description": workflow.description,
1450
        "run": run_index,
1451
        "phase": phase,
1452
        "operation": operation,
1453
        "step_kind": "summary",
1454
        "elapsed_ms": round(elapsed_ms, 3),
1455
        "returncode": 1 if failures else 0,
1456
        "process_returncode": 1 if failures else 0,
1457
        "command": [row["command"] for row in rows],
1458
        "tool_call_count": tool_calls,
1459
        "terminal_tool_call_count": terminal_calls,
1460
        "vcs_tool_call_count": vcs_calls,
1461
        "test_tool_call_count": test_calls,
1462
        **oakbench_tokens.summed_token_fields(
1463
            rows, "sum_of_workflow_steps_command_plus_admitted_output_chars_div_4"
1464
        ),
1465
        "tool_calls": {
1466
            "total": tool_calls,
1467
            "terminal": terminal_calls,
1468
            "vcs": vcs_calls,
1469
            "test": test_calls,
1470
        },
1471
        "steps_total": steps_total,
1472
        "steps_succeeded": steps_total - steps_failed,
1473
        "steps_failed": steps_failed,
1474
        "step_failure_rate": (steps_failed / steps_total) if steps_total else None,
1475
        "summarized_operations": [row["operation"] for row in rows],
1476
    }
1477
    if extra_fields:
1478
        result.update(extra_fields)
1479
        if extra_fields.get("workflow_integrity_passed") is False:
1480
            result["returncode"] = 1
1481
            result["process_returncode"] = 1
1482
        elif extra_fields.get("workflow_integrity_unmeasured_reason"):
1483
            result["returncode"] = 77
1484
            result["skipped"] = True
1485
            result["skip_reason"] = extra_fields["workflow_integrity_unmeasured_reason"]
1486
    return result
1487
1488
1489
def copy_fixture(src: Path, dest: Path) -> None:
1490
    oakbench_fixtures.copy_fixture(src, dest)
1491
1492
1493
def prepare_fixture(root: Path, workflow: Workflow) -> Path:
1494
    fixture = root / "fixtures" / workflow.name
1495
    marker = fixture / ".fixture-ready"
1496
    if marker.exists() and marker.read_text().strip() == FIXTURE_VERSION:
1497
        return fixture
1498
    if fixture.exists():
1499
        shutil.rmtree(fixture)
1500
    fixture.mkdir(parents=True)
1501
    workflow.make_fixture(fixture)
1502
    marker.write_text(FIXTURE_VERSION + "\n")
1503
    return fixture
1504
1505
1506
def run_subject_workflow(
1507
    subject: Subject,
1508
    workflow: Workflow,
1509
    fixture: Path,
1510
    run_index: int,
1511
    run_root: Path,
1512
    metadata: dict[str, Any],
1513
    admitted_output_chars: int,
1514
    track: str,
1515
) -> list[dict[str, Any]]:
1516
    repo = run_root / workflow.name / subject.name / f"run-{run_index}"
1517
    copy_fixture(fixture, repo)
1518
1519
    ctx: dict[str, str] | None = None
1520
    if workflow.remote_purpose is not None:
1521
        ctx, skip_reason, remote_fields = sync_context(subject, workflow, run_index, metadata)
1522
        if ctx is None:
1523
            return [workflow_skip_row(subject, workflow, run_index, metadata, skip_reason or "")]
1524
        metadata = {**metadata, **remote_fields}
1525
1526
    setup_steps = list(vcs_init_steps(subject))
1527
    if workflow.prepare is not None:
1528
        setup_steps.extend(
1529
            workflow.prepare(subject, track) if ctx is None else workflow.prepare(subject, track, ctx)
1530
        )
1531
    setup_rows = [
1532
        run_attested_step(subject, workflow, step, repo, run_index, "setup", metadata, admitted_output_chars)
1533
        for step in setup_steps
1534
    ]
1535
1536
    workflow_rows: list[dict[str, Any]] = []
1537
    if any(int(row["returncode"]) != 0 for row in setup_rows):
1538
        return setup_rows + [
1539
            sum_rows(setup_rows, metadata, subject, workflow, run_index, "setup", "setup.total"),
1540
        ]
1541
1542
    # Oak remote workflows measure inside clone A (the trap-hitting checkout);
1543
    # everything else measures in the fixture repo itself.
1544
    measure_dir = repo
1545
    if ctx is not None and "measure_dir" in ctx:
1546
        measure_dir = (repo / ctx["measure_dir"]).resolve()
1547
    for step in workflow.steps(subject, track) if ctx is None else workflow.steps(subject, track, ctx):
1548
        row = run_attested_step(
1549
            subject, workflow, step, measure_dir, run_index, "workflow", metadata, admitted_output_chars
1550
        )
1551
        workflow_rows.append(row)
1552
        if int(row["returncode"]) != 0:
1553
            break
1554
1555
    derived = recovery_metrics_row(workflow_rows, metadata, subject, workflow, run_index)
1556
    integrity = workflow_integrity_fields(subject, workflow, measure_dir, workflow_rows)
1557
    return [
1558
        *setup_rows,
1559
        sum_rows(setup_rows, metadata, subject, workflow, run_index, "setup", "setup.total"),
1560
        *workflow_rows,
1561
        sum_rows(
1562
            workflow_rows,
1563
            metadata,
1564
            subject,
1565
            workflow,
1566
            run_index,
1567
            "workflow",
1568
            "workflow.total",
1569
            integrity,
1570
        ),
1571
        *([derived] if derived else []),
1572
    ]
1573
1574
1575
def select_workflows(raw: str) -> list[Workflow]:
1576
    if raw == "all":
1577
        return list(WORKFLOWS.values())
1578
    names = [item.strip() for item in raw.split(",") if item.strip()]
1579
    missing = [name for name in names if name not in WORKFLOWS]
1580
    if missing:
1581
        raise SystemExit("Unknown workflows: " + ", ".join(missing))
1582
    return [WORKFLOWS[name] for name in names]
1583
1584
1585
def remote_preflight_requirements(
1586
    subjects: list[Subject],
1587
    workflows: list[Workflow],
1588
) -> list[oakbench_remotes.RemoteRequirement]:
1589
    if not any(subject.kind == "oak" for subject in subjects):
1590
        return []
1591
    grouped: dict[str, list[str]] = {}
1592
    for workflow in workflows:
1593
        if workflow.remote_purpose is None:
1594
            continue
1595
        grouped.setdefault(workflow.remote_purpose, []).append(f"{workflow.name}/workflow.skipped")
1596
    return [
1597
        oakbench_remotes.RemoteRequirement(
1598
            purpose=purpose,
1599
            lane="workflow",
1600
            operations=tuple(operations),
1601
        )
1602
        for purpose, operations in sorted(grouped.items())
1603
    ]
1604
1605
1606
def metric_median(rows: list[dict[str, Any]], metric: str) -> dict[tuple[str, str], float]:
1607
    """Median over successful ``workflow.total`` rows (methodology: medians, not means)."""
1608
    grouped: dict[tuple[str, str], list[float]] = {}
1609
    for row in rows:
1610
        if row.get("operation") != "workflow.total" or row_returncode(row) != 0:
1611
            continue
1612
        try:
1613
            value = float(row[metric])
1614
        except (KeyError, TypeError, ValueError):
1615
            continue
1616
        grouped.setdefault((str(row["subject"]), str(row["workflow"])), []).append(value)
1617
    return {key: statistics.median(values) for key, values in grouped.items()}
1618
1619
1620
def metric_transport(rows: list[dict[str, Any]]) -> dict[tuple[str, str], tuple[str | None, str | None]]:
1621
    transports: dict[tuple[str, str], set[tuple[str | None, str | None]]] = {}
1622
    for row in rows:
1623
        if row.get("operation") != "workflow.total" or row_returncode(row) != 0:
1624
            continue
1625
        key = (str(row["subject"]), str(row["workflow"]))
1626
        transport = row.get("remote_transport") or row.get("workspace_transport")
1627
        server = row.get("remote_server") or row.get("workspace_server")
1628
        transports.setdefault(key, set()).add(
1629
            (
1630
                str(transport) if transport is not None else None,
1631
                str(server) if server is not None else None,
1632
            )
1633
        )
1634
1635
    result: dict[tuple[str, str], tuple[str | None, str | None]] = {}
1636
    for key, values in transports.items():
1637
        if len(values) == 1:
1638
            result[key] = next(iter(values))
1639
        else:
1640
            result[key] = ("mixed", "mixed")
1641
    return result
1642
1643
1644
def workflow_total_stats(rows: list[dict[str, Any]]) -> dict[tuple[str, str], dict[str, int | float]]:
1645
    """Per (subject, workflow) run outcomes, counting every attempted run.
1646
1647
    A run is classified from its rows, keyed by run index:
1648
    - ``workflow.total`` with returncode 0: success.
1649
    - ``workflow.total`` with returncode 77 (e.g. integrity unmeasured): unmeasured.
1650
    - ``workflow.total`` with any other returncode: failure.
1651
    - ``setup.total`` without ``workflow.total``: failure (setup never let the
1652
      workflow start). Before 2026-11-09 these runs vanished from the summary.
1653
    - ``workflow.skipped``: skipped (no attempt).
1654
    Failure rate is failures / attempted runs (success + failure + unmeasured).
1655
    """
1656
    runs: dict[tuple[str, str], dict[Any, dict[str, int]]] = {}
1657
    for row in rows:
1658
        op = row.get("operation")
1659
        if op not in ("workflow.total", "setup.total", "workflow.skipped"):
1660
            continue
1661
        key = (str(row["subject"]), str(row["workflow"]))
1662
        runs.setdefault(key, {}).setdefault(row.get("run"), {})[str(op)] = row_returncode(row)
1663
    stats: dict[tuple[str, str], dict[str, int | float]] = {}
1664
    for key, by_run in runs.items():
1665
        counts = {"successes": 0, "failures": 0, "unmeasured": 0, "skipped": 0}
1666
        for ops in by_run.values():
1667
            if "workflow.total" in ops:
1668
                code = ops["workflow.total"]
1669
                bucket = "successes" if code == 0 else "unmeasured" if code == SKIP_RETURNCODE else "failures"
1670
            elif "setup.total" in ops:
1671
                bucket = "failures" if ops["setup.total"] != SKIP_RETURNCODE else "unmeasured"
1672
            else:
1673
                bucket = "skipped"
1674
            counts[bucket] += 1
1675
        attempted = counts["successes"] + counts["failures"] + counts["unmeasured"]
1676
        stats[key] = {
1677
            "runs": attempted,
1678
            **counts,
1679
            "failure_rate": counts["failures"] / attempted if attempted else 0.0,
1680
        }
1681
    return stats
1682
1683
1684
def lower_is_better_pct(base: float | None, value: float | None) -> str:
1685
    return fmt_delta_lower_better(base, value)
1686
1687
1688
def comparable_time_delta(
1689
    base: float | None,
1690
    value: float | None,
1691
    base_transport: tuple[str | None, str | None] | None,
1692
    value_transport: tuple[str | None, str | None] | None,
1693
) -> str:
1694
    if base is None or value is None:
1695
        return ""
1696
    if base_transport != value_transport:
1697
        return "n/c transport"
1698
    return lower_is_better_pct(base, value)
1699
1700
1701
def fmt(value: float | None, precision: int = 1) -> str:
1702
    return fmt_num(value, precision)
1703
1704
1705
def summary_text(rows: list[dict[str, Any]], subjects: list[Subject], workflows: list[Workflow]) -> str:
1706
    avg_ms = metric_median(rows, "elapsed_ms")
1707
    avg_tokens = metric_median(rows, "estimated_tokens_total")
1708
    avg_tools = metric_median(rows, "tool_call_count")
1709
    avg_output = metric_median(rows, "raw_output_bytes")
1710
    transports = metric_transport(rows)
1711
    total_stats = workflow_total_stats(rows)
1712
    git_name = next((subject.name for subject in subjects if subject.kind == "git"), None)
1713
    # Oak baseline per CONTEXT.md: oak_main when present, else oak_installed.
1714
    subject_names = {subject.name for subject in subjects}
1715
    oak_baseline = next((name for name in ("oak_main", "oak_installed") if name in subject_names), None)
1716
1717
    lines = [
1718
        "# Oak Workflow A/B Summary",
1719
        "",
1720
        f"Track: `{rows[0].get('benchmark_track', 'unknown') if rows else 'unknown'}`.",
1721
        "Rows compare whole deterministic agent-shaped workflows. Positive deltas mean the row subject is lower/better.",
1722
        "Time deltas are not comparable across different remote/workspace transports; token and tool-call deltas remain comparable.",
1723
        "Output bytes are full stdout/stderr bytes, even when admitted token text was capped.",
1724
        "Runs counts every attempted run, including runs whose setup failed; medians use successful runs only.",
1725
        "Unmeasured runs completed but a required check could not be evaluated (returncode 77).",
1726
        "",
1727
        "| Workflow | Subject | Runs | Successes | Failures | Unmeasured | Failure rate | Median ms | Median est tokens | Median output bytes | Median tool calls | vs Git time | vs Git tokens | vs Git tools | vs Oak time | vs Oak tokens | vs Oak tools |",
1728
        "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
1729
    ]
1730
    for workflow in workflows:
1731
        git_ms = avg_ms.get((git_name, workflow.name)) if git_name else None
1732
        git_tokens = avg_tokens.get((git_name, workflow.name)) if git_name else None
1733
        git_tools = avg_tools.get((git_name, workflow.name)) if git_name else None
1734
        git_transport = transports.get((git_name, workflow.name)) if git_name else None
1735
        oak_ms = avg_ms.get((oak_baseline, workflow.name)) if oak_baseline else None
1736
        oak_tokens = avg_tokens.get((oak_baseline, workflow.name)) if oak_baseline else None
1737
        oak_tools = avg_tools.get((oak_baseline, workflow.name)) if oak_baseline else None
1738
        oak_transport = transports.get((oak_baseline, workflow.name)) if oak_baseline else None
1739
        for subject in subjects:
1740
            key = (subject.name, workflow.name)
1741
            value_ms = avg_ms.get(key)
1742
            stats = total_stats.get(key)
1743
            if value_ms is None and stats is None:
1744
                continue
1745
            value_tokens = avg_tokens.get(key)
1746
            value_tools = avg_tools.get(key)
1747
            value_output = avg_output.get(key)
1748
            value_transport = transports.get(key)
1749
            runs = int(stats["runs"]) if stats else 0
1750
            successes = int(stats["successes"]) if stats else 0
1751
            failures = int(stats["failures"]) if stats else 0
1752
            unmeasured = int(stats["unmeasured"]) if stats else 0
1753
            failure_rate = float(stats["failure_rate"]) if stats else 0.0
1754
            skip_git = subject.name == git_name
1755
            skip_oak = subject.name == oak_baseline or subject.kind == "git"
1756
            lines.append(
1757
                f"| `{workflow.name}` | `{subject.name}` | {runs} | {successes} | {failures} | {unmeasured} | "
1758
                f"{failure_rate:.0%} | {fmt(value_ms)} | {fmt(value_tokens)} | "
1759
                f"{fmt(value_output, 0)} | {fmt(value_tools, 2)} | "
1760
                f"{'' if skip_git else comparable_time_delta(git_ms, value_ms, git_transport, value_transport)} | "
1761
                f"{'' if skip_git else lower_is_better_pct(git_tokens, value_tokens)} | "
1762
                f"{'' if skip_git else lower_is_better_pct(git_tools, value_tools)} | "
1763
                f"{'' if skip_oak else comparable_time_delta(oak_ms, value_ms, oak_transport, value_transport)} | "
1764
                f"{'' if skip_oak else lower_is_better_pct(oak_tokens, value_tokens)} | "
1765
                f"{'' if skip_oak else lower_is_better_pct(oak_tools, value_tools)} |"
1766
            )
1767
    return "\n".join(lines) + "\n"
1768
1769
1770
def has_lane_failures(rows: list[dict[str, Any]]) -> bool:
1771
    return any(row_returncode(row) not in (0, SKIP_RETURNCODE) for row in rows)
1772
1773
1774
def main() -> int:
1775
    args = parse_args()
1776
    subjects = load_subjects(args)
1777
    workflows = select_workflows(args.workflows)
1778
    oakbench_remotes.print_remote_preflight_warnings(
1779
        oakbench_remotes.oak_remote_preflight_warnings(
1780
            remote_preflight_requirements(subjects, workflows)
1781
        )
1782
    )
1783
1784
    timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
1785
    args.results.mkdir(parents=True, exist_ok=True)
1786
    args.workdir.mkdir(parents=True, exist_ok=True)
1787
    run_root = args.workdir / "runs" / timestamp
1788
    fixture_root = args.workdir
1789
1790
    metadata = {
1791
        "bench_id": timestamp,
1792
        "profile": "workflow-ab",
1793
        "benchmark_track": args.track,
1794
        "command_semantics_version": COMMAND_SEMANTICS_VERSION,
1795
        "timestamp_utc": timestamp,
1796
        "host": platform.node(),
1797
        "platform": platform.platform(),
1798
        "machine": platform.machine(),
1799
        "python": platform.python_version(),
1800
        "env_isolation_version": oakbench_environment.ENV_ISOLATION_VERSION,
1801
        "subject_versions": {subject.name: subject_version(subject) for subject in subjects},
1802
        "subject_details": subject_details(subjects),
1803
        "source": source_metadata(args.oak_repo),
1804
    }
1805
1806
    metadata["load_tier"] = args.load_tier
1807
1808
    rows: list[dict[str, Any]] = []
1809
    # Background load (untimed start/stop). Failing to start under a non-none
1810
    # tier converts the whole invocation to skip rows: load that was not
1811
    # applied is never claimed.
1812
    load_generator: oakbench_loadgen.LoadGenerator | None = None
1813
    if args.load_tier != "none":
1814
        load_generator = oakbench_loadgen.LoadGenerator(
1815
            args.load_tier, args.workdir / "loadgen-temp"
1816
        )
1817
        load_start = load_generator.start()
1818
        if not load_start["started"]:
1819
            reason = oakbench_loadgen.load_tier_unavailable_reason(str(load_start["reason"]))
1820
            rows = load_tier_skip_rows(subjects, workflows, args.runs, metadata, reason, args.load_tier)
1821
            load_generator = None
1822
    try:
1823
        if not rows:
1824
            for workflow in workflows:
1825
                fixture = prepare_fixture(fixture_root, workflow)
1826
                print(f"[fixture] {workflow.name}: {workflow.description}", flush=True)
1827
                with measurement_lock("workflow_ab") as lock_info:
1828
                    metadata["measurement_lock_wait_ms"] = lock_info.wait_ms
1829
                    metadata["measurement_lock"] = "held" if lock_info.enabled else "disabled"
1830
                    for run_index in range(args.runs):
1831
                        run_subjects = list(subjects)
1832
                        if args.randomize_subject_order:
1833
                            random.Random(f"{timestamp}:{workflow.name}:{run_index}").shuffle(run_subjects)
1834
                        metadata["randomized_subject_order"] = args.randomize_subject_order
1835
                        metadata["subject_order"] = [subject.name for subject in run_subjects]
1836
                        for subject in run_subjects:
1837
                            print(f"[run] {workflow.name} run={run_index} subject={subject.name}", flush=True)
1838
                            env_before = oakbench_envwatch.sample_environment()
1839
                            subject_rows = run_subject_workflow(
1840
                                subject,
1841
                                workflow,
1842
                                fixture,
1843
                                run_index,
1844
                                run_root,
1845
                                metadata,
1846
                                args.admitted_output_chars,
1847
                                args.track,
1848
                            )
1849
                            env_after = oakbench_envwatch.sample_environment()
1850
                            boundary = oakbench_loadgen.environment_boundary_fields(
1851
                                args.load_tier, env_before, env_after
1852
                            )
1853
                            for row in subject_rows:
1854
                                row.update(boundary)
1855
                            rows.extend(subject_rows)
1856
    finally:
1857
        if load_generator is not None:
1858
            load_stop = load_generator.stop()
1859
            # bogo-ops parsed ONLY as did-the-load-run verification, never
1860
            # reported as a benchmark number.
1861
            for row in rows:
1862
                row["load_verified"] = load_stop.get("verified")
1863
1864
    store = ResultsStore(args.results, lane="workflow")
1865
    raw_path, summary_path = store.write(timestamp, rows, summary_text(rows, subjects, workflows))
1866
1867
    if not args.keep_workdirs and run_root.exists():
1868
        shutil.rmtree(run_root)
1869
1870
    print(f"[result] {raw_path}")
1871
    print(f"[summary] {summary_path}")
1872
    return 1 if has_lane_failures(rows) else 0
1873
1874
1875
if __name__ == "__main__":
1876
    raise SystemExit(main())