File size: 31,414 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import json
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor

import pytest
from PIL import Image

from bench_builder.builder_progress import BuilderProgressError, BuilderProgressService, game_version, summarize
from bench_builder.build_progress import read_build_progress


@pytest.fixture
def service(tmp_path):
    run = tmp_path / "task/run"
    contract = run / "public-inputs/video_agent/analysis/game_design.json"
    contract.parent.mkdir(parents=True)
    contract.write_text(json.dumps({"observable_requirements": [
        {"id": "r1", "category": "visual", "attribute": "color", "acceptance": "A red player"},
        {"id": "r2", "category": "gameplay", "acceptance": "Click moves the player"},
    ], "reference_instances": [{"instance_id": "player.1"}]}), encoding="utf-8")
    output = run / "candidate/dist"
    output.mkdir(parents=True)
    (output / "index.html").write_text('<html><body style="background:#f00">Game</body></html>')
    verification = run / "candidate/verification"
    verification.mkdir()
    Image.new("RGB", (64, 36), "red").save(verification / "current.png")
    (verification / "results.json").write_text('{"errors":[],"inputs":["click"]}')
    return BuilderProgressService(run)


def publish(service, request_id="first", base="", **extra):
    return service.update_progress(request_id=request_id, base_snapshot_id=base, preview={"mode": "none"}, **extra)


def first_pass(service):
    version = service.get_progress()["current_version"]
    return publish(service, captures=[{"id": "frame", "path": "verification/current.png", "build_version": version}],
                   checks=[{"requirement_id": "r1", "status": "passed", "reason": "Inspected red body",
                            "evidence": [{"capture_id": "frame", "bbox": [0, 0, 64, 36]}]}])


def test_batch_updates_snapshot_counts_and_keeps_images_immutable(service):
    first = first_pass(service)
    assert first["progress"]["passed"] == 1
    assert first["progress"]["total"] == 2
    media_id = first["preview"]["media_id"]
    original = service.media(media_id).read_bytes()
    Image.new("RGB", (64, 36), "blue").save(service.candidate / "verification/current.png")
    second = publish(service, "second", first["snapshot_id"], summary="Gameplay still pending",
                     checks=[{"requirement_id": "r2", "status": "partial", "reason": "Movement works; reset untested"}])
    assert second["progress"]["partial"] == 1
    assert service.media(media_id).read_bytes() == original
    assert service.snapshot(first["snapshot_id"])["progress"]["partial"] == 0
    assert [s["snapshot_id"] for s in service.list_snapshots()["snapshots"]] == [second["snapshot_id"], first["snapshot_id"]]
    assert json.loads((service.candidate / "builder_checks.json").read_text())["snapshot_id"] == second["snapshot_id"]


def test_taxonomy_survives_tools_and_snapshots_without_changing_progress_or_contract(service):
    from bench_builder.taxonomy import TAXONOMY_VERSION
    path = service.run / "public-inputs/video_agent/analysis/game_design.json"
    design = json.loads(path.read_text())
    design["taxonomy_version"] = TAXONOMY_VERSION
    design["observable_requirements"][0]["taxonomy"] = {
        "primary_domain": "visuals.assets", "level": "structure",
        "requirement_group_id": "player", "secondary_domains": ["interface.hud"],
    }
    path.write_text(json.dumps(design))
    raw = path.read_bytes()
    digest = service.contract()[1]
    before = service.get_progress()
    assert before["requirements"][0]["taxonomy"]["primary_domain"] == "visuals.assets"
    assert before["taxonomy_diagnostics"]["unclassified"]["total"] == 1
    first = first_pass(service)
    saved = service.snapshot(first["snapshot_id"])
    history_bytes = service.history_path.read_bytes()
    assert saved["requirements"][0]["taxonomy_version"] == TAXONOMY_VERSION
    assert saved["contract_sha256"] == digest
    assert saved["taxonomy_diagnostics"]["domains"]["visuals"] == {
        "total": 1, "counts": {"passed": 1, "partial": 0, "failed": 0,
                             "pending": 0, "unavailable": 0, "needs_recheck": 0},
    }
    assert "interface" not in saved["taxonomy_diagnostics"]["domains"]  # Secondary labels add no count.
    assert first["progress"]["passed"] == 1 and first["progress"]["total"] == 2
    filtered = service.get_progress(status="pending")
    assert [r["id"] for r in filtered["requirements"]] == ["r2"]
    assert filtered["taxonomy_diagnostics"]["requirement_count"] == 2
    assert service.list_snapshots()["requirements"][0]["taxonomy"] == design["observable_requirements"][0]["taxonomy"]

    # Taxonomy diagnostics follow retained self-reports; saved counts stay frozen.
    (service.candidate / "dist/index.html").write_text("Changed game")
    current = service.get_progress()
    assert current["taxonomy_diagnostics"]["domains"]["visuals"]["counts"]["needs_recheck"] == 0
    assert current["taxonomy_diagnostics"]["domains"]["visuals"]["counts"]["passed"] == 1
    assert service.snapshot(first["snapshot_id"]) == saved
    assert service.history_path.read_bytes() == history_bytes
    assert path.read_bytes() == raw and service.contract()[1] == digest


def test_legacy_builder_requirements_remain_unclassified(service):
    result = first_pass(service)
    diagnostics = result["taxonomy_diagnostics"]
    assert diagnostics["domains"] == {}
    assert diagnostics["unclassified"]["total"] == result["progress"]["total"] == 2
    assert diagnostics["unclassified"]["counts"]["passed"] == 1
    assert all("taxonomy" not in r for r in service.list_snapshots()["requirements"])


@pytest.mark.parametrize("count", [0, 1, 3])
def test_report_screenshots_are_optional_and_scoped_to_each_batch(service, count):
    version = service.get_progress()["current_version"]
    captures = []
    for index, label in enumerate(["Beginning", "Middle", "Outcome"][:count]):
        filename = f"verification/{index}.png"
        Image.new("RGB", (64, 36), ["red", "green", "blue"][index]).save(service.candidate / filename)
        captures.append({"path": filename, "label": label, "build_version": version})
    first = publish(service, captures=captures)
    saved = service.snapshot(first["snapshot_id"])
    ids = saved["report_capture_ids"]
    assert len(ids) == count
    by_id = {c["capture_id"]: c for c in saved["captures"]}
    assert [by_id[key]["label"] for key in ids] == [c["label"] for c in captures]
    assert first["progress"]["pending"] == 2  # Images do not manufacture passes.
    second = publish(service, "status-only", first["snapshot_id"])
    assert second["report_capture_ids"] == []
    assert len(service.snapshot(second["snapshot_id"])["captures"]) == count
    assert service.snapshot(first["snapshot_id"])["report_capture_ids"] == ids


def test_new_version_preserves_self_reported_status(service):
    first = first_pass(service)
    (service.candidate / "dist/index.html").write_text("Changed version")
    observed = service.get_progress()
    assert observed["progress"]["passed"] == 1
    assert observed["progress"]["needsRecheck"] == 0
    assert observed["progress"]["unreportedVersion"]
    second = publish(service, "new-version", first["snapshot_id"])
    assert second["preview"] is None
    assert second["progress"]["passed"] == 1
    third = publish(service, "carry", second["snapshot_id"], checks=[{
        "requirement_id": "r1", "status": "passed", "assessment": "carried_forward",
        "reason": "Only the reset handler changed; player drawing and its assets are unchanged",
    }])
    assert third["progress"]["carriedPassed"] == 1
    assert third["progress"]["freshPassed"] == 0
    assert service.snapshot(first["snapshot_id"])["progress"]["passed"] == 1


def test_retry_deduplicates_and_repairs_latest_projection(service):
    first = first_pass(service)
    second = publish(service, "second", first["snapshot_id"], summary="Still testing")
    (service.candidate / "builder_checks.json").write_text("interrupted write")
    assert first_pass(service)["snapshot_id"] == first["snapshot_id"]
    assert len(service.history()) == 2
    assert json.loads((service.candidate / "builder_checks.json").read_text())["snapshot_id"] == second["snapshot_id"]
    with pytest.raises(BuilderProgressError, match="different content"):
        publish(service, summary="changed request content")


def test_crash_tail_is_ignored_and_next_commit_recovers(service):
    first = first_pass(service)
    with service.history_path.open("ab") as stream:
        stream.write(b'{"snapshot_id":"partial')
    assert len(service.history()) == 1
    publish(service, "recovered", first["snapshot_id"])
    assert len(service.history()) == 2
    assert len(service.history_path.read_text().splitlines()) == 2


def test_parallel_updates_cannot_overwrite_each_other(service):
    first = first_pass(service)
    def update(index):
        try:
            other = BuilderProgressService(service.run)
            return publish(other, f"worker-{index}", first["snapshot_id"])["snapshot_id"]
        except BuilderProgressError:
            return "conflict"
    with ThreadPoolExecutor(max_workers=2) as pool:
        results = list(pool.map(update, range(2)))
    assert results.count("conflict") == 0
    assert len(service.history()) == 3


def test_invalid_batch_cannot_change_counts_or_contract(service):
    first = first_pass(service)
    result = publish(service, "mixed", checks=[
        {"requirement_id": "invented", "status": "passed"},
        {"requirement_id": "r2", "status": "invalid"},
        {"requirement_id": "r2", "status": "pending"},
        {"requirement_id": "r2", "status": "passed", "reason": None},
        None,
    ])
    assert result["progress"]["passed"] == 2
    assert result["progress"]["total"] == 2
    assert len(result["progress"]["warnings"]) == 5
    contract = service.run / "public-inputs/video_agent/analysis/game_design.json"
    d = json.loads(contract.read_text()); d["observable_requirements"].pop(); contract.write_text(json.dumps(d))
    with pytest.raises(BuilderProgressError, match="contract changed"):
        publish(service, "weaken", first["snapshot_id"])
    assert len(service.history()) == 2


def test_pass_without_evidence_or_version_gate(service):
    result = publish(service, checks=[{"requirement_id": "r1", "status": "passed"}])
    assert result["progress"]["passed"] == 1



def test_runtime_requires_test_results_and_is_independent_of_requirement_passes(service):
    first = first_pass(service)
    check = {"requirement_id": "startup", "status": "passed", "reason": "No console errors",
             "evidence": [{"capture_id": first["preview"]["capture_id"]}]}
    publish(service, "runtime-preview", first["snapshot_id"], runtime_checks=[check])
    version = first["build_version"]
    check["evidence"] = [{"path": "verification/results.json", "build_version": version}]
    result = publish(service, "runtime", first["snapshot_id"], runtime_checks=[check])
    assert result["progress"]["runtimeChecks"][0]["status"] == "passed"
    assert not result["progress"]["runtimeSatisfied"]
    assert result["progress"]["passed"] == 1


def test_bad_attachments_do_not_block_progress_or_valid_attachments(service):
    (service.candidate / "verification/broken.png").write_text("not an image")
    result = publish(service, captures=[
        {"path": "../../outside.png"}, {"path": "verification/broken.png"},
        {"id": "frame", "path": "verification/current.png"},
    ], checks=[{"requirement_id": "r1", "status": "passed", "evidence": [
        {"capture_id": "missing"}, {"path": "verification/missing.json"},
        {"capture_id": "frame", "bbox": [0, 0, 200, 200]},
    ]}])
    assert result["progress"]["passed"] == 1
    assert len(result["progress"]["warnings"]) == 4
    saved = service.snapshot(result["snapshot_id"])
    assert len(saved["checks"][0]["evidence"]) == 1
    assert len(saved["report_capture_ids"]) == 1
    assert publish(service, "next")["progress"]["warnings"] == []
    with pytest.raises(BuilderProgressError):
        service.media("../../outside.txt")


def test_candidate_attachment_has_no_extension_or_directory_gate(service):
    (service.candidate / "notes.csv").write_text("case,outcome")
    result = publish(service, checks=[{"requirement_id": "r1", "status": "passed",
                     "evidence": [{"path": "notes.csv"}]}])
    assert not result["progress"]["warnings"]
    assert len(service.snapshot(result["snapshot_id"])["artifacts"]) == 1
    media = service.snapshot(result["snapshot_id"])["artifacts"][0]["media_id"]
    assert service.media(media).read_text() == "case,outcome"


def test_progress_projection_reads_history_and_detects_unreported_build(service):
    first_pass(service)
    root = service.run.parent.parent
    assert read_build_progress(root, "task", "run")["passed"] == 1
    (service.candidate / "dist/index.html").write_text("another game version")
    assert read_build_progress(root, "task", "run")["passed"] == 1
    assert read_build_progress(root, "task", "run")["unreportedVersion"]


def test_preview_failure_does_not_discard_valid_checks(service, monkeypatch):
    monkeypatch.setattr(service, "_capture_preview", lambda *_: (_ for _ in ()).throw(RuntimeError("browser unavailable")))
    first = first_pass(service)
    result = service.update_progress("preview", first["snapshot_id"], preview={"mode": "capture"})
    assert "Preview capture failed" in result["capture_error"]
    assert result["progress"]["passed"] == 1
    assert result["preview"]["capture_id"] == first["preview"]["capture_id"]


def user_additions(service, revisions=None):
    import hashlib
    base = service.run / "public-inputs/video_agent/analysis/game_design.json"
    payload = {"schema_version": 1, "base_contract_sha256": hashlib.sha256(base.read_bytes()).hexdigest(),
               "revisions": revisions or [{"id": "user-1", "authorization": "Please add death and retry", "reason": "User expanded scope",
                "requirements": [{"id": "wiki-death", "category": "lifecycle", "acceptance": "Zero health enters a death state",
                                  "required_evidence": ["capture", "artifact"]}]}]}
    (service.run / "requirement_additions.json").write_text(json.dumps(payload), encoding="utf-8")
    return payload


def test_user_additions_expand_counts_without_rewriting_original_history(service):
    first = first_pass(service)
    original_history = service.history_path.read_bytes()
    original_contract = (service.run / "public-inputs/video_agent/analysis/game_design.json").read_bytes()
    user_additions(service)
    current = service.get_progress()
    assert current["progress"]["total"] == 3
    assert current["progress"]["passed"] == 1
    assert current["progress"]["unreportedRequirements"]
    assert current["checks"][-1]["requirement_id"] == "wiki-death"
    assert current["checks"][-1]["status"] == "pending"
    assert len(service.list_snapshots()["requirements"]) == 3
    second = publish(service, "scope-expanded", first["snapshot_id"])
    assert second["progress"]["total"] == 3
    assert not service.get_progress()["progress"]["unreportedRequirements"]
    assert service.history_path.read_bytes().startswith(original_history)
    assert service.snapshot(first["snapshot_id"])["progress"]["total"] == 2
    assert (service.run / "public-inputs/video_agent/analysis/game_design.json").read_bytes() == original_contract


@pytest.mark.parametrize("change", ["remove", "edit", "base", "duplicate"])
def test_published_requirement_additions_cannot_be_removed_or_weakened(service, change):
    first = first_pass(service)
    data = user_additions(service)
    second = publish(service, "expanded", first["snapshot_id"])
    if change == "remove":
        (service.run / "requirement_additions.json").unlink()
    else:
        if change == "edit":
            data["revisions"][0]["requirements"][0]["acceptance"] = "A death label is enough"
        elif change == "base":
            data["base_contract_sha256"] = "changed"
        else:
            data["revisions"][0]["requirements"].append({"id": "r1", "acceptance": "Replace existing requirement"})
        (service.run / "requirement_additions.json").write_text(json.dumps(data), encoding="utf-8")
    with pytest.raises(BuilderProgressError):
        publish(service, "invalid-scope", second["snapshot_id"])
    assert len(service.history()) == 2
    assert len(service.list_snapshots()["snapshots"]) == 2
    assert service.list_snapshots().get("error")


def test_second_user_revision_appends_pending_checks_and_preserves_first_revision(service):
    first_pass(service)
    data = user_additions(service)
    expanded = publish(service, "expanded", "s000001")
    data["revisions"].append({"id": "user-2", "authorization": "Also add Burn", "reason": "Another requested mechanic",
                              "requirements": [{"id": "wiki-burn", "acceptance": "Burn damages over time"}]})
    user_additions(service, data["revisions"])
    second = publish(service, "expanded-again", expanded["snapshot_id"])
    assert second["progress"]["total"] == 4
    assert service.get_progress(status="pending")["checks"][-1]["requirement_id"] == "wiki-burn"


def test_authorized_metric_amendment_requires_new_evidence_and_preserves_history(service):
    from bench_builder.requirement_revisions import row_digest
    first = first_pass(service)
    prior_history = service.history_path.read_bytes()
    contract, _ = service.contract()
    original = contract["observable_requirements"][0]
    data = user_additions(service, [{"id": "metric-v2", "authorization": "Owner requested a reasonable metric",
        "reason": "Repair an underspecified visual check", "requirements": [],
        "amendments": [{"id": "r1", "before_sha256": row_digest(original), "reason": "Specify visible evidence",
                        "changes": {"acceptance": "A red player beside a visible door"}}]}])
    current = service.get_progress()
    assert current["progress"]["passed"] == 0
    assert current["checks"][0]["status"] == "needs_recheck"
    assert service.history_path.read_bytes() == prior_history
    assert service.snapshot(first["snapshot_id"])["progress"]["passed"] == 1
    from bench_builder.independent_review import latest_review_summary
    review_path = service.run / "agent/reviews/latest.json"
    review_path.parent.mkdir(parents=True, exist_ok=True)
    review_path.write_text(json.dumps({"confirmed": True, "weighted_confirmed_percent": 100}))
    assert latest_review_summary(service.run)["stale_metric"] is True
    assert latest_review_summary(service.run)["confirmed"] is False
    revised = publish(service, "amended", first["snapshot_id"])
    data["revisions"][0]["amendments"][0]["changes"]["acceptance"] = "Anything counts"
    (service.run / "requirement_additions.json").write_text(json.dumps(data))
    with pytest.raises(BuilderProgressError):
        publish(service, "tampered", revised["snapshot_id"])


def test_amendment_invalidates_dependent_claims(service):
    from bench_builder.requirement_revisions import row_digest
    base = service.run / "public-inputs/video_agent/analysis/game_design.json"
    contract = json.loads(base.read_text())
    contract["requirement_dependencies"] = [{"requirement_id": "r2", "depends_on": ["r1"]}]
    base.write_text(json.dumps(contract))
    first_pass(service)
    user_additions(service, [{"id": "metric-v2", "authorization": "Owner requested an evidence repair",
        "reason": "Bind the reference moment", "requirements": [], "amendments": [{
            "id": "r1", "before_sha256": row_digest(contract["observable_requirements"][0]),
            "reason": "Missing reference timestamp", "changes": {"evidence_refs": ["ev.repair.t2"]}}]}])
    contract, digest, lineage = service._contract_with_lineage()
    snapshot = service.history()[0]
    snapshot["checks"][1]["status"] = "passed"
    service._reconcile_requirements(snapshot, contract, digest, lineage)
    assert [row["status"] for row in snapshot["checks"]] == ["needs_recheck", "needs_recheck"]


def test_added_mechanic_requires_both_game_image_and_runtime_artifact(service):
    first = first_pass(service)
    user_additions(service)
    version = first["build_version"]
    check = {"requirement_id": "wiki-death", "status": "passed", "reason": "Verified death transition with inputs",
             "evidence": [{"capture_id": first["preview"]["capture_id"]}]}
    publish(service, "death-preview", first["snapshot_id"], checks=[check])
    check["evidence"].append({"path": "verification/results.json", "build_version": version})
    result = publish(service, "death", first["snapshot_id"], checks=[check])
    assert result["progress"]["passed"] == 2


@pytest.mark.parametrize("required", ["capture", ["notes"], [None], {}])
def test_user_additions_validate_required_evidence_types(service, required):
    data = user_additions(service)
    data["revisions"][0]["requirements"][0]["required_evidence"] = required
    (service.run / "requirement_additions.json").write_text(json.dumps(data), encoding="utf-8")
    with pytest.raises(BuilderProgressError, match="User requirement additions"):
        service.contract()


def _dependency_service(tmp_path, rows, dependencies, target=90, strict=True):
    run = tmp_path / "dependent/run"
    contract = run / "public-inputs/video_agent/analysis/game_design.json"
    contract.parent.mkdir(parents=True)
    contract.write_text(json.dumps({"observable_requirements": rows, "requirement_dependencies": dependencies}))
    (run / "candidate/dist").mkdir(parents=True)
    (run / "candidate/dist/index.html").write_text("<html><body>Game</body></html>")
    if strict:  # strict completion (independent_review on) gates on dependencies and weights
        (run / "result.json").write_text(json.dumps({"build": {"harness_options": {"independent_review": "on"}}}))
    return BuilderProgressService(run, target)


def test_without_strict_completion_every_reported_pass_counts_once_as_before(tmp_path):
    rows = [{"id": "flow.board", "category": "gameplay", "acceptance": "Board"},
            {"id": "flow.ride", "category": "gameplay", "acceptance": "Ride"}] + [
        {"id": f"ui.glyph{i}", "category": "ui", "acceptance": "Glyph"} for i in range(8)]
    service = _dependency_service(tmp_path, rows, [{"requirement_id": "flow.ride", "depends_on": ["flow.board"]}],
                                  strict=False)
    progress = publish(service, checks=[{"requirement_id": "flow.board", "status": "failed", "reason": "missed"}] + [
        {"requirement_id": key, "status": "passed", "reason": "seen"} for key in ["flow.ride"] + [
            f"ui.glyph{i}" for i in range(8)]])["progress"]
    assert (progress["passed"], progress["percentage"], progress["targetSatisfied"]) == (9, 90.0, True)
    assert not {"weightedPercentage", "blockedByDependencies", "reportedPassed"} & progress.keys()


def _counted(progress):
    return {key: progress[key] for key in ("passed", "reportedPassed", "blockedByDependencies", "partial", "failed", "pending")}


def test_passes_behind_a_failed_prerequisite_do_not_count_until_it_passes(tmp_path):
    service = _dependency_service(tmp_path, [
        {"id": "flow.board", "category": "gameplay", "acceptance": "Board the elevator"},
        {"id": "flow.ride", "category": "gameplay", "acceptance": "Ride to floor 15"},
        {"id": "ui.hint", "category": "ui", "acceptance": "Hint text"},
    ], [{"requirement_id": "flow.ride", "depends_on": ["flow.board"]}])
    first = publish(service, checks=[{"requirement_id": "flow.ride", "status": "passed", "reason": "rode"},
                                     {"requirement_id": "ui.hint", "status": "passed", "reason": "shown"},
                                     {"requirement_id": "flow.board", "status": "failed", "reason": "missed the door"}])
    progress = first["progress"]
    assert _counted(progress) == {"passed": 1, "reportedPassed": 2, "blockedByDependencies": 1,
                                  "partial": 0, "failed": 1, "pending": 0}
    assert progress["blockedRequirementIds"] == ["flow.ride"]
    assert progress["percentage"] == 33.3 and progress["weightedPercentage"] == 14.2
    assert progress["targetSatisfied"] is False
    assert service.get_progress()["progress"]["blockedRequirementIds"] == ["flow.ride"]
    second = publish(service, "second", first["snapshot_id"],
                     checks=[{"requirement_id": "flow.board", "status": "passed", "reason": "boarded"}])
    assert _counted(second["progress"])["passed"] == 3 and second["progress"]["blockedByDependencies"] == 0
    assert second["progress"]["targetSatisfied"] is True


def test_target_is_the_weighted_share_so_hud_checks_cannot_outvote_the_story(tmp_path):
    rows = [{"id": "flow.door", "category": "gameplay", "acceptance": "Open the door"}] + [
        {"id": f"ui.glyph{i}", "category": "ui", "acceptance": "Glyph"} for i in range(9)]
    service = _dependency_service(tmp_path, rows, [], target=65)
    progress = publish(service, checks=[{"requirement_id": f"ui.glyph{i}", "status": "passed"} for i in range(9)])["progress"]
    assert progress["percentage"] == 90.0 and progress["weightedPercentage"] == 75.0
    assert progress["targetSatisfied"] is True
    service = _dependency_service(tmp_path / "story", rows, [], target=65)
    checks = [{"requirement_id": "flow.door", "status": "passed"}] + [
        {"requirement_id": f"ui.glyph{i}", "status": "passed"} for i in range(5)]
    progress = publish(service, checks=checks)["progress"]
    # The weighted share alone decides: 8 of 12 weight passes although only 6 of 10 rows do.
    assert progress["percentage"] == 60.0 and progress["weightedPercentage"] == 66.6
    assert progress["targetSatisfied"] is True


def test_snapshots_saved_without_dependency_data_are_scored_with_the_current_contract(tmp_path):
    service = _dependency_service(tmp_path, [
        {"id": "flow.board", "category": "gameplay", "acceptance": "Board"},
        {"id": "flow.ride", "category": "gameplay", "acceptance": "Ride"},
    ], [{"requirement_id": "flow.ride", "depends_on": ["flow.board"]}])
    publish(service, checks=[{"requirement_id": "flow.ride", "status": "passed"}])
    stored = json.loads(service.history_path.read_text())
    for key in ("requirement_dependencies", "requirements"):
        stored.pop(key)
    service.history_path.write_text(json.dumps(stored) + "\n")
    assert summarize(stored, 90, strict=True)["passed"] == 1  # no dependency data: nothing to cap
    progress = service.get_progress()["progress"]
    assert progress["passed"] == 0 and progress["blockedRequirementIds"] == ["flow.ride"]


def _chain_service(tmp_path):
    chain = [("flow.obj_enter_elevator", [], ["94.5", "97.5"]), ("flow.obj_talk_tbug", ["flow.obj_enter_elevator"], ["107.5"]),
             ("gameplay.door_opens", ["flow.obj_talk_tbug"], ["343.5", "344.5"]),
             ("gameplay.xp_award", ["gameplay.door_opens"], ["344.5"])]
    return _dependency_service(tmp_path, [
        {"id": key, "category": "gameplay", "acceptance": key, "evidence_refs": [f"ev.r1.t{t}" for t in times]}
        for key, _, times in chain], [{"requirement_id": key, "depends_on": deps} for key, deps, _ in chain if deps])


def test_cosmetic_partials_do_not_block_but_a_missed_elevator_blocks_everything_after_it(tmp_path):
    service = _chain_service(tmp_path)
    first = publish(service, checks=[
        {"requirement_id": "flow.obj_enter_elevator", "status": "passed"},
        {"requirement_id": "flow.obj_talk_tbug", "status": "passed"},
        {"requirement_id": "gameplay.door_opens", "status": "partial", "reason": "opens at 344.5 s; door far away"},
        {"requirement_id": "gameplay.xp_award", "status": "passed"}])
    assert _counted(first["progress"]) == {"passed": 3, "reportedPassed": 3, "blockedByDependencies": 0,
                                           "partial": 1, "failed": 0, "pending": 0}
    assert first["progress"]["blockedBy"] == {}
    second = publish(service, "second", first["snapshot_id"], checks=[
        {"requirement_id": "flow.obj_enter_elevator", "status": "failed", "reason": "official replay never boards"}])
    progress = second["progress"]
    assert progress["passed"] == 0 and progress["blockedRequirementIds"] == ["flow.obj_talk_tbug", "gameplay.xp_award"]
    assert progress["blockedBy"] == {
        "flow.obj_talk_tbug": [{"id": "flow.obj_enter_elevator", "time": 97.5, "verdict": "fail"}],
        "gameplay.xp_award": [{"id": "gameplay.door_opens", "time": 344.5, "verdict": "blocked",
                               "because": [{"id": "flow.obj_enter_elevator", "time": 97.5, "verdict": "fail"}]}]}
    assert service.get_progress()["progress"]["blockedBy"] == progress["blockedBy"]


def test_per_time_statuses_gate_each_dependent_by_the_instance_it_relies_on(tmp_path):
    service = _dependency_service(tmp_path, [
        {"id": "ui.qh.ram_cost", "category": "ui", "acceptance": "RAM COST 2",
         "evidence_refs": ["ev.r23.t283.5", "ev.r07.t337.5"]},
        {"id": "gameplay.qh_ram_deduction", "category": "gameplay", "acceptance": "RAM 4/4 to 2/4",
         "evidence_refs": ["ev.r35.t342.1"]},
        {"id": "ui.first_scan.hint", "category": "ui", "acceptance": "Hint", "evidence_refs": ["ev.r23.t290"]},
    ], [{"requirement_id": "gameplay.qh_ram_deduction", "depends_on": ["ui.qh.ram_cost"]},
        {"requirement_id": "ui.first_scan.hint", "depends_on": ["ui.qh.ram_cost"]}])
    first = publish(service, checks=[
        {"requirement_id": "ui.qh.ram_cost", "status": "partial", "reason": "2 RAM COST at 337.5 s; absent at 283.5 s",
         "times": {"337.5": "passed", "283.5": "failed", "100": "passed"}},
        {"requirement_id": "gameplay.qh_ram_deduction", "status": "passed", "times": {"342.1": "passed"}},
        {"requirement_id": "ui.first_scan.hint", "status": "passed", "times": "290"}])
    progress = first["progress"]
    assert progress["passed"] == 1 and progress["blockedRequirementIds"] == ["ui.first_scan.hint"]
    assert progress["blockedBy"] == {"ui.first_scan.hint": [{"id": "ui.qh.ram_cost", "time": 283.5, "verdict": "fail"}]}
    stored = service.snapshot(first["snapshot_id"])
    rows = {row["requirement_id"]: row for row in stored["checks"]}
    assert rows["ui.qh.ram_cost"]["times"] == {"283.5": "failed", "337.5": "passed"}
    assert "times" not in rows["ui.first_scan.hint"]
    assert [e.split(":")[0] for e in stored["attachment_errors"]] == ["ui.qh.ram_cost", "ui.first_scan.hint"]
    ledger = json.loads((service.candidate / "builder_checks.json").read_text())
    assert next(r for r in ledger["requirement_checks"] if r["requirement_id"] == "ui.qh.ram_cost")["times"] == {
        "283.5": "failed", "337.5": "passed"}
    # A later report without times grades every instance by the row status again.
    second = publish(service, "second", first["snapshot_id"], checks=[{"requirement_id": "ui.qh.ram_cost", "status": "partial"}])
    assert second["progress"]["passed"] == 2 and second["progress"]["blockedByDependencies"] == 0
    assert "times" not in next(r for r in service.snapshot(second["snapshot_id"])["checks"]
                               if r["requirement_id"] == "ui.qh.ram_cost")