File size: 51,915 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
from __future__ import annotations

import hashlib
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import uuid
from pathlib import Path
from typing import Any

import yaml  # type: ignore[import-untyped]
from PIL import Image, ImageDraw

from packages.benchmark.portable import (
    create_portable_bundle,
    create_zstd_archive,
    portable_source_fingerprint,
    refresh_checksums,
    verify_portable_bundle,
)
from packages.core.files import atomic_write_text
from packages.generative import GenerativeClient, RelaySettings
from packages.supervisor.models import GateResult, IterationPolicy, QualityReport
from packages.supervisor.visual_preflight import evaluate_visual_preflight


def _json(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(f"expected JSON object: {path}")
    return value


def _asset_ids(value: object) -> set[str]:
    found: set[str] = set()
    if isinstance(value, dict):
        asset_id = value.get("asset_id")
        if isinstance(asset_id, str):
            found.add(asset_id)
        for child in value.values():
            found.update(_asset_ids(child))
    elif isinstance(value, list):
        for child in value:
            found.update(_asset_ids(child))
    return found


def _global_critic_affected_entities(output: Path, valid_entity_ids: set[str]) -> list[str]:
    path = output / "scenesmith" / "agent_outputs" / "global-critic__scene.json"
    if not path.is_file():
        return []
    try:
        payload = _json(path)
    except (OSError, ValueError, json.JSONDecodeError):
        return []
    directive = payload.get("repair_directive") or {}
    candidates = directive.get("entities") if isinstance(directive, dict) else []
    return sorted(
        {str(entity_id) for entity_id in candidates or [] if str(entity_id) in valid_entity_ids}
    )


def _robot_release_gates(output: Path) -> list[GateResult]:
    """Require geometric and visual proof whenever a benchmark contains a robot."""
    robot_path = output / "manifests" / "robot.json"
    if not robot_path.is_file():
        return []

    placement_path = output / "manifests" / "robot_placement_validation.json"
    placement = _json(placement_path) if placement_path.is_file() else {}
    placement_facts = {
        key: placement.get(key)
        for key in (
            "passed",
            "footprint_inside_room",
            "wall_clearance_passed",
            "obstacle_clearance_passed",
            "source_approach_passed",
            "source_facing_passed",
        )
    }
    placement_passed = placement_path.is_file() and all(
        value is True for value in placement_facts.values()
    )

    preview_path = output / "scenesmith" / "preview_camera_manifest.json"
    preview = _json(preview_path) if preview_path.is_file() else {}
    shots = preview.get("shots") if isinstance(preview, dict) else []
    required_shots = [
        shot
        for shot in (shots if isinstance(shots, list) else [])
        if isinstance(shot, dict) and shot.get("required_robot_full_body") is True
    ]
    preview_passed = (
        preview_path.is_file()
        and preview.get("passed") is True
        and preview.get("robot_detected") is True
        and bool(required_shots)
        and all(
            shot.get("passed") is True and shot.get("robot_full_body_visible") is True
            for shot in required_shots
        )
    )

    critic_path = output / "scenesmith" / "final_composed_critic_views" / "manifest.json"
    critic = _json(critic_path) if critic_path.is_file() else {}
    audit = critic.get("robot_visual_audit") if isinstance(critic, dict) else {}
    audit = audit if isinstance(audit, dict) else {}
    views = critic.get("views") if isinstance(critic, dict) else {}
    views = views if isinstance(views, dict) else {}
    robot_view = views.get("robot_access")
    resolved_robot_view = None
    if isinstance(robot_view, str) and robot_view:
        candidate = Path(robot_view)
        resolved_robot_view = candidate if candidate.is_absolute() else output / "scenesmith" / candidate
    critic_passed = (
        critic_path.is_file()
        and audit.get("passed") is True
        and int(audit.get("detected_mesh_count") or 0) > 0
        and audit.get("view_created") is True
        and resolved_robot_view is not None
        and resolved_robot_view.is_file()
    )

    return [
        GateResult(
            gate_id="robot_room_placement",
            passed=placement_passed,
            message=f"report_present={placement_path.is_file()} facts={placement_facts}",
            affected_entities=[] if placement_passed else ["robot"],
            evidence={"report": str(placement_path.relative_to(output))},
        ),
        GateResult(
            gate_id="robot_preview_visibility",
            passed=preview_passed,
            message=(
                f"report_present={preview_path.is_file()} detected={preview.get('robot_detected')} "
                f"required_full_body_shots={len(required_shots)}"
            ),
            affected_entities=[] if preview_passed else ["robot"],
            evidence={"report": str(preview_path.relative_to(output))},
        ),
        GateResult(
            gate_id="robot_global_critic_visibility",
            passed=critic_passed,
            message=(
                f"report_present={critic_path.is_file()} audit={audit} "
                f"robot_access_present={bool(resolved_robot_view and resolved_robot_view.is_file())}"
            ),
            affected_entities=[] if critic_passed else ["robot"],
            evidence={"report": str(critic_path.relative_to(output))},
        ),
    ]


def _usd_python_from_environment() -> str:
    configured = os.environ.get("RHG_USD_PYTHON", "").strip()
    if configured:
        return configured
    scenesmith_command = os.environ.get("SCENESMITH_COMMAND", "").strip()
    if scenesmith_command:
        return shlex.split(scenesmith_command)[0]
    data_root = os.environ.get("RHG_DATA_ROOT", "").strip()
    if data_root:
        candidate = Path(data_root) / "conda-envs/scenesmith-sam3d/bin/python"
        if candidate.is_file():
            return str(candidate)
    return ""


class QualityEvaluator:
    def __init__(self, policy: IterationPolicy) -> None:
        self.policy = policy
        self.config: dict[str, Any] = {}
        if policy.quality_policy and policy.quality_policy.is_file():
            self.config = yaml.safe_load(policy.quality_policy.read_text(encoding="utf-8")) or {}

    def evaluate(self, output: Path) -> QualityReport:
        # Author the inexpensive manipulation schema first.  Visual rejection is
        # evaluated before launching Isaac or portable extraction so an obviously
        # low-fidelity version cannot spend minutes in external validators.
        self._materialize_manipulation_physics(output)
        gates: list[GateResult] = []
        agent_global_score: float | None = None
        required = [
            "root.usda",
            "manifests/task.json",
            "manifests/scene.json",
            "manifests/episode.json",
        ]
        missing = [name for name in required if not (output / name).is_file()]
        gates.append(
            GateResult(
                gate_id="benchmark_contract", passed=not missing, message=f"missing={missing}"
            )
        )
        if missing:
            return self._report(gates, critic_passed=not self.policy.critic_required)

        task = _json(output / "manifests/task.json")
        scene = _json(output / "manifests/scene.json")
        expected = {
            str(item["entity_id"])
            for item in task.get("entities", [])
            if isinstance(item, dict) and item.get("role") != "ROBOT"
        }
        bindings = scene.get("entity_prim_paths", {})
        missing_entities = sorted(expected - set(bindings if isinstance(bindings, dict) else {}))
        duplicate_paths = []
        if isinstance(bindings, dict):
            paths = [str(bindings[item]) for item in expected if item in bindings]
            duplicate_paths = sorted({path for path in paths if paths.count(path) > 1})
        gates.append(
            GateResult(
                gate_id="entity_identity",
                passed=not missing_entities and not duplicate_paths,
                message=f"missing={missing_entities} duplicate_paths={duplicate_paths}",
                affected_entities=missing_entities,
            )
        )
        gates.extend(_robot_release_gates(output))

        stage_path = output / "scenesmith" / "stage_manifest.json"
        if stage_path.is_file():
            stage = _json(stage_path)
            gates.append(
                GateResult(
                    gate_id="scenesmith_complete",
                    passed=stage.get("status") == "complete",
                    message=f"status={stage.get('status')}",
                )
            )
            graph_files = [
                stage.get("scene_dependency_graph"),
                stage.get("dependency_execution_plan"),
            ]
            missing_graph = [
                str(name)
                for name in graph_files
                if not isinstance(name, str) or not (stage_path.parent / name).is_file()
            ]
            gates.append(
                GateResult(
                    gate_id="dependency_plan_saved",
                    passed=not missing_graph,
                    message=f"missing={missing_graph}",
                )
            )
            if stage.get("orchestration_mode") == "dag_agents":
                ledger_name = stage.get("agent_execution_ledger")
                ledger_path = stage_path.parent / str(ledger_name or "")
                ledger = _json(ledger_path) if ledger_name and ledger_path.is_file() else {}
                records = ledger.get("records") if isinstance(ledger, dict) else {}
                records = records if isinstance(records, dict) else {}
                incomplete = sorted(
                    task_id
                    for task_id, record in records.items()
                    if not isinstance(record, dict)
                    or record.get("status") not in {"complete", "reused"}
                )
                global_record = records.get("global-critic:scene", {})
                global_result = (
                    global_record.get("result", {}) if isinstance(global_record, dict) else {}
                )
                global_score = (
                    global_result.get("critic_score") if isinstance(global_result, dict) else None
                )
                if isinstance(global_score, (int, float)):
                    agent_global_score = float(global_score)
                publish_gate_path = stage_path.parent / str(
                    stage.get("global_critic_publish_gate") or ""
                )
                publish_gate = (
                    _json(publish_gate_path)
                    if stage.get("global_critic_publish_gate")
                    and publish_gate_path.is_file()
                    else {}
                )
                # The in-worker global critic is preliminary because the robot
                # and outer benchmark layers do not exist yet. Release scoring
                # happens below from the shared final composed contact sheet.
                dag_passed = (
                    ledger.get("status") == "complete"
                    and bool(records)
                    and not incomplete
                    and global_result.get("accepted") is True
                    and global_result.get("hard_gates_passed") is True
                    and publish_gate.get("passed") is True
                )
                gates.append(
                    GateResult(
                        gate_id="agent_dag_execution",
                        passed=dag_passed,
                        message=(
                            f"ledger_status={ledger.get('status')} incomplete={incomplete} "
                            f"global_score={global_score} publish_gate={publish_gate.get('passed')}"
                        ),
                        metric=(
                            float(global_score) if isinstance(global_score, (int, float)) else None
                        ),
                        threshold=self.policy.critic_min_score,
                        affected_entities=(
                            [] if dag_passed else _global_critic_affected_entities(output, expected)
                        ),
                        evidence={
                            "global_failure_signature": (
                                global_result.get("failure_signature")
                                if isinstance(global_result, dict)
                                else None
                            )
                        },
                    )
                )
            native = stage.get("native_asset_bindings", {})
            effective_path = output / "scenesmith" / "effective_selected_assets.json"
            selected_path = output / "scenesmith" / "selected_assets.json"
            selected_payload = (
                _json(effective_path if effective_path.is_file() else selected_path)
                if (effective_path.is_file() or selected_path.is_file())
                else {}
            )
            selected_ids = _asset_ids(selected_payload) if selected_payload else set()
            native_ids = (
                {
                    str(binding["asset_id"])
                    for binding in native.values()
                    if isinstance(binding, dict)
                    and binding.get("binding_mode") != "embedded_generated"
                    and isinstance(binding.get("asset_id"), str)
                }
                if isinstance(native, dict)
                else set()
            )
            mismatched = sorted(native_ids - selected_ids) if selected_ids else sorted(native_ids)
            locked_assets = stage.get("task_asset_overrides", {})
            wrong_locked_assets = (
                sorted(
                    entity
                    for entity, expected_asset in locked_assets.items()
                    if isinstance(native, dict)
                    and (
                        not isinstance(native.get(entity), dict)
                        or native[entity].get("binding_mode") == "embedded_generated"
                        or native[entity].get("asset_id") != expected_asset
                    )
                )
                if isinstance(locked_assets, dict)
                else []
            )
            missing_usd = (
                sorted(
                    entity
                    for entity, binding in native.items()
                    if isinstance(binding, dict)
                    and (
                        not isinstance(binding.get("canonical_usd"), str)
                        or not Path(str(binding["canonical_usd"])).is_file()
                    )
                )
                if isinstance(native, dict)
                else []
            )
            gates.append(
                GateResult(
                    gate_id="canonical_asset_identity",
                    passed=not mismatched and not missing_usd and not wrong_locked_assets,
                    message=(
                        f"unselected_ids={mismatched} missing_usd={missing_usd} "
                        f"wrong_locked_assets={wrong_locked_assets}"
                    ),
                    affected_entities=sorted(set(missing_usd + wrong_locked_assets)),
                )
            )
            indexed_task_entities = {
                str(entity_id)
                for entity_id, candidates in selected_payload.items()
                if str(entity_id) in expected
                and isinstance(candidates, list)
                and any(
                    isinstance(candidate, dict) and candidate.get("asset_id")
                    for candidate in candidates
                )
            }
            embedded_indexed_entities = sorted(
                entity_id
                for entity_id in indexed_task_entities
                if not isinstance(native, dict)
                or not isinstance(native.get(entity_id), dict)
                or native[entity_id].get("binding_mode") == "embedded_generated"
            )
            gates.append(
                GateResult(
                    gate_id="indexed_task_asset_binding",
                    passed=not embedded_indexed_entities,
                    message=(
                        "indexed_entities_without_explicit_native_binding="
                        f"{embedded_indexed_entities}"
                    ),
                    affected_entities=embedded_indexed_entities,
                )
            )

        preflight_gate = self._visual_preflight(output)
        gates.append(preflight_gate)
        if not preflight_gate.passed:
            return self._report(gates, critic_passed=False, critic_score=None)

        critic_passed, supervisor_critic_score = self._critic(output, task)
        critic_score = supervisor_critic_score
        supervisor_report_path = output / "supervisor/critic_report.json"
        supervisor_severe = []
        if supervisor_report_path.is_file():
            supervisor_result = _json(supervisor_report_path).get("result") or {}
            if isinstance(supervisor_result, dict):
                raw_severe = supervisor_result.get("severe_failures") or []
                if isinstance(raw_severe, list):
                    supervisor_severe = raw_severe
        if critic_score is None and agent_global_score is not None:
            # Preserve preliminary evidence only when final visual review is
            # disabled; it can never override a final composed-frame rejection.
            critic_score = agent_global_score
        if self.policy.critic_required or supervisor_critic_score is not None:
            shared_evidence = {
                "report": "scenesmith/final_global_critic_report.json",
                "shared_final_frames": True,
            }
            gates.append(
                GateResult(
                    gate_id="final_global_visual_critic",
                    passed=critic_passed,
                    message=(
                        f"score={supervisor_critic_score} threshold={self.policy.critic_min_score} "
                        f"severe_failures={len(supervisor_severe)}"
                    ),
                    metric=supervisor_critic_score,
                    threshold=self.policy.critic_min_score,
                    evidence=shared_evidence,
                )
            )
            gates.append(
                GateResult(
                    gate_id="supervisor_visual_critic",
                    passed=critic_passed,
                    message=(
                        f"score={supervisor_critic_score} "
                        f"required={self.policy.critic_required} "
                        "reference_calibrated="
                        f"{(output / 'supervisor/critic_reference_manifest.json').is_file()} "
                        "shared_final_frames=True "
                        f"severe_failures={len(supervisor_severe)}"
                    ),
                    metric=supervisor_critic_score,
                    threshold=self.policy.critic_min_score,
                    evidence=shared_evidence,
                )
            )
        if not critic_passed:
            return self._report(gates, critic_passed=False, critic_score=critic_score)

        external_reports = self.config.get("external_reports", [])
        portable_reports = [
            report_config
            for report_config in external_reports
            if str(report_config.get("gate_id")) == "portable_bundle_verification"
            or Path(str(report_config.get("path", ""))).name == "portable_validation.json"
        ]
        nonportable_reports = [
            report_config
            for report_config in external_reports
            if report_config not in portable_reports
        ]
        self._materialize_validation_reports(output, include_portable=False)

        def append_report_gates(report_configs: list[dict[str, Any]]) -> None:
            for report_config in report_configs:
                path = output / str(report_config["path"])
                required_report = bool(report_config.get("required", True))
                payload = _json(path) if path.is_file() else {}
                passed = (
                    bool(payload.get(str(report_config.get("pass_field", "passed"))))
                    if payload
                    else not required_report
                )
                gates.append(
                    GateResult(
                        gate_id=str(report_config["gate_id"]),
                        passed=passed,
                        message=f"report={path.relative_to(output)} present={path.is_file()}",
                    )
                )

        append_report_gates(nonportable_reports)
        prepublish = self._report(
            gates,
            critic_passed=critic_passed,
            critic_score=critic_score,
        )
        if not prepublish.accepted:
            return prepublish

        # The exact frames consumed by the final Critic are now accepted and all
        # scene/physics hard gates have passed. Only now may a release video exist.
        from packages.scene_generation.orchestrator import render_accepted_final_preview
        from packages.supervisor.snapshot import ensure_version_media

        if (
            (output / "scenesmith/stage_manifest.json").is_file()
            and (output / "scenesmith/global_critic_publish_gate.json").is_file()
        ):
            render_accepted_final_preview(
                output,
                accepted=True,
                hard_gates_passed=True,
                critic_passed=True,
            )
        ensure_version_media(output, force_snapshot=True)

        self._materialize_validation_reports(
            output,
            include_isaac=False,
            include_portable=True,
        )
        append_report_gates(portable_reports)
        return self._report(gates, critic_passed=critic_passed, critic_score=critic_score)

    def _visual_preflight(self, output: Path) -> GateResult:
        config = self.config.get("visual_preflight") or {}
        config = config if isinstance(config, dict) else {}
        manifest_path = output / "scenesmith/final_composed_critic_views/manifest.json"
        manifest = _json(manifest_path) if manifest_path.is_file() else {}
        report = evaluate_visual_preflight(manifest, config)
        report_path = output / "supervisor/visual_preflight_report.json"
        atomic_write_text(
            report_path,
            json.dumps(report, ensure_ascii=False, indent=2) + "\n",
        )
        return GateResult(
            gate_id="visual_preflight",
            passed=report["passed"],
            message=(
                f"required={report['required']} manifest_present={manifest_path.is_file()} "
                f"failures={report['failures']}"
            ),
            evidence={"report": str(report_path.relative_to(output))},
        )

    def _materialize_validation_reports(
        self,
        output: Path,
        *,
        include_isaac: bool = True,
        include_portable: bool = True,
    ) -> None:
        self._materialize_manipulation_physics(output)
        configured = {
            str(item.get("gate_id")): item for item in self.config.get("external_reports", [])
        }
        isaac = configured.get("isaac_physics_and_support")
        isaac_report = output / "manifests" / "isaac_validation.json"
        portable = configured.get("portable_bundle_verification")
        portable_report = output / "manifests" / "portable_validation.json"
        if (
            include_isaac
            and isaac
            and bool(isaac.get("required", True))
            and not isaac_report.is_file()
        ):
            self._run_isaac_validation(output, isaac_report)
        if include_portable and portable and bool(portable.get("required", True)):
            # A prior report does not prove that the bundle still matches the
            # source version. The validator performs a cheap source-fingerprint
            # comparison and atomically rebuilds only when evidence changed.
            self._run_portable_validation(output, portable_report)

    @staticmethod
    def _materialize_manipulation_physics(output: Path) -> None:
        task_path = output / "manifests/task.json"
        scene_path = output / "manifests/scene.json"
        root_path = output / "root.usda"
        report_path = output / "manifests/manipulation_physics.json"
        if report_path.is_file() or not all(
            path.is_file() for path in (task_path, scene_path, root_path)
        ):
            return
        task = _json(task_path)
        if not any(
            isinstance(entity, dict) and entity.get("role") == "MANIPULATED"
            for entity in task.get("entities", [])
        ):
            return
        executable = sys.executable
        try:
            import pxr  # type: ignore[import-not-found]  # noqa: F401
        except ImportError:
            executable = os.environ.get("RHG_USD_PYTHON", "").strip()
            if not executable:
                scenesmith_command = os.environ.get("SCENESMITH_COMMAND", "").strip()
                executable = shlex.split(scenesmith_command)[0] if scenesmith_command else ""
        try:
            if not executable:
                raise RuntimeError("no USD-capable Python configured")
            script = Path(__file__).resolve().parents[2] / "scripts/author_manipulation_physics.py"
            command = [
                *shlex.split(executable),
                str(script),
                "--root",
                str(root_path),
                "--task",
                str(task_path),
                "--scene",
                str(scene_path),
                "--report",
                str(report_path),
            ]
            result = subprocess.run(command, capture_output=True, text=True, check=False)
            if result.returncode:
                raise RuntimeError((result.stdout + result.stderr)[-4000:])
        except Exception as error:
            atomic_write_text(
                report_path,
                json.dumps(
                    {
                        "schema_version": "1.0",
                        "passed": False,
                        "error": f"{type(error).__name__}: {error}",
                    },
                    indent=2,
                )
                + "\n",
            )
        refresh_checksums(output)

    def _run_portable_validation(self, output: Path, report_path: Path) -> None:
        destination = output.parent / "packages" / output.name
        try:
            destination.parent.mkdir(parents=True, exist_ok=True)
            expected_fingerprint = portable_source_fingerprint(output)
            portable_manifest = destination / "portable_manifest.json"
            existing_fingerprint = (
                str(_json(portable_manifest).get("source_fingerprint") or "")
                if portable_manifest.is_file()
                else ""
            )
            portable_is_current = (
                destination.is_dir() and existing_fingerprint == expected_fingerprint
            )
            require_pxr = bool(self.config.get("portable_require_pxr", True))
            usd_python = _usd_python_from_environment()
            try:
                import pxr  # type: ignore[import-not-found]  # noqa: F401

                pxr_available = True
            except ImportError:
                pxr_available = False
            if require_pxr and not pxr_available and usd_python:
                archive = destination.with_suffix(".tar.zst")
                packager = (
                    Path(__file__).resolve().parents[2] / "scripts/package_portable_benchmark.py"
                )
                command = [*shlex.split(usd_python), str(packager)]
                if destination.exists():
                    command.extend(["verify", "--bundle", str(destination), "--require-pxr"])
                else:
                    command.extend(
                        [
                            "create",
                            "--source",
                            str(output),
                            "--output",
                            str(destination),
                        ]
                    )
                    if self.config.get("create_archive", True):
                        command.extend(["--archive", str(archive)])
                result = subprocess.run(command, capture_output=True, text=True, check=False)
                if result.returncode:
                    raise RuntimeError((result.stdout + result.stderr)[-4000:])
                payload = json.loads(result.stdout)
                report = payload.get("verification", payload)
                if archive.is_file():
                    report["archive"] = str(archive)
            else:
                rebuilt = False
                if not portable_is_current:
                    token = uuid.uuid4().hex
                    staging = destination.parent / f".{destination.name}.staging-{token}"
                    backup = destination.parent / f".{destination.name}.backup-{token}"
                    try:
                        create_portable_bundle(output, staging)
                        staging_report = verify_portable_bundle(
                            staging, require_pxr=require_pxr
                        )
                        if not staging_report.get("passed"):
                            raise RuntimeError(
                                "staged portable verification failed: "
                                f"{staging_report.get('failures', [])}"
                            )
                        if destination.exists():
                            destination.rename(backup)
                        staging.rename(destination)
                    except Exception:
                        if backup.exists() and not destination.exists():
                            backup.rename(destination)
                        raise
                    finally:
                        if staging.exists():
                            shutil.rmtree(staging)
                    if backup.exists():
                        shutil.rmtree(backup)
                    rebuilt = True
                report = verify_portable_bundle(destination, require_pxr=require_pxr)
                if report.get("passed") and self.config.get("create_archive", True):
                    archive = destination.with_suffix(".tar.zst")
                    if rebuilt or not archive.exists():
                        temporary_archive = archive.with_name(f".{archive.name}.tmp")
                        temporary_archive.unlink(missing_ok=True)
                        create_zstd_archive(destination, temporary_archive)
                        temporary_archive.replace(archive)
                    report["archive"] = str(archive)
        except Exception as error:
            report = {
                "schema_version": "1.0",
                "passed": False,
                "error": f"{type(error).__name__}: {error}",
            }
        atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n")

    @staticmethod
    def _run_isaac_validation(output: Path, report: Path) -> None:
        repository = Path(__file__).resolve().parents[2]
        validator = repository / "scripts" / "isaac_validate_benchmark.py"
        direct = os.environ.get("RHG_ISAAC_PYTHON", "").strip()
        if not direct:
            data_root = os.environ.get("RHG_DATA_ROOT", "").strip()
            local_candidates = []
            if data_root:
                local_candidates.append(
                    Path(data_root) / "conda-envs" / "isaacsim-6.0.1" / "bin" / "python3.12"
                )
            direct = next(
                (str(candidate) for candidate in local_candidates if candidate.is_file()), ""
            )
        settle_frames = os.environ.get("RHG_ISAAC_SETTLE_FRAMES", "180").strip()
        if not settle_frames.isdigit() or int(settle_frames) <= 0:
            raise ValueError("RHG_ISAAC_SETTLE_FRAMES must be a positive integer")
        if direct:
            command = [
                *shlex.split(direct),
                str(validator),
                str(output / "root.usda"),
                "--report",
                str(report),
                "--settle-frames",
                settle_frames,
            ]
            report_root = None
        elif shutil.which("docker"):
            report_root = output / "supervisor" / "isaac_reports"
            cache_root = Path(
                os.environ.get(
                    "RHG_ISAAC_CACHE_ROOT",
                    str(output.parent.parent / ".cache" / "isaac-sim"),
                )
            )
            command = [
                sys.executable,
                str(repository / "scripts" / "isaac_parallel_validate.py"),
                str(output / "root.usda"),
                "--scene-root",
                str(output),
                "--report-root",
                str(report_root),
                "--cache-root",
                str(cache_root),
                "--validator",
                str(validator),
                "--max-gpus",
                "1",
                "--settle-frames",
                settle_frames,
                "--image",
                os.environ.get("RHG_ISAAC_IMAGE", "wholebody-scene-mvp-v0-arena:latest"),
            ]
        else:
            atomic_write_text(
                report,
                json.dumps(
                    {
                        "schema_version": "1.0",
                        "passed": False,
                        "error": "neither RHG_ISAAC_PYTHON nor docker is available",
                    },
                    indent=2,
                )
                + "\n",
            )
            return
        run_environment = os.environ.copy()
        run_environment.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
        if direct:
            isaac_executable = Path(shlex.split(direct)[0]).expanduser().resolve()
            isaac_library = isaac_executable.parent.parent / "lib"
            inherited_libraries = run_environment.get("LD_LIBRARY_PATH", "")
            run_environment["LD_LIBRARY_PATH"] = (
                f"{isaac_library}:{inherited_libraries}"
                if inherited_libraries
                else str(isaac_library)
            )
            configured_gpu = os.environ.get("RHG_ISAAC_GPU_ID", "").strip()
            if not configured_gpu:
                configured_gpu = os.environ.get("SCENESMITH_GPU_IDS", "").split(",", 1)[0].strip()
            if configured_gpu:
                run_environment["RHG_ISAAC_GPU_ID"] = configured_gpu
            # Kit's Vulkan device enumeration is independent of CUDA remapping;
            # mixing the two can make the configured physical index invalid.
            run_environment.pop("CUDA_VISIBLE_DEVICES", None)
            vulkan_icd = os.environ.get(
                "RHG_ISAAC_VULKAN_ICD", "/etc/vulkan/icd.d/nvidia_icd.json"
            ).strip()
            if vulkan_icd:
                run_environment["VK_ICD_FILENAMES"] = vulkan_icd
        try:
            result = subprocess.run(
                command,
                capture_output=True,
                text=True,
                timeout=int(os.environ.get("RHG_ISAAC_VALIDATION_TIMEOUT_S", "1800")),
                check=False,
                env=run_environment,
            )
        except (OSError, subprocess.TimeoutExpired) as error:
            atomic_write_text(
                report,
                json.dumps(
                    {
                        "schema_version": "1.0",
                        "passed": False,
                        "error": f"{type(error).__name__}: {error}",
                    },
                    indent=2,
                )
                + "\n",
            )
            return
        if report_root is not None and not report.is_file():
            candidates = sorted(
                path
                for path in report_root.glob("*.json")
                if path.name != "parallel_validation_summary.json"
            )
            if len(candidates) == 1:
                atomic_write_text(report, candidates[0].read_text(encoding="utf-8"))
        if result.returncode and not report.is_file():
            atomic_write_text(
                report,
                json.dumps(
                    {
                        "schema_version": "1.0",
                        "passed": False,
                        "error": (result.stdout + result.stderr)[-4000:],
                    },
                    indent=2,
                )
                + "\n",
            )

    def _critic(self, output: Path, task: dict[str, Any]) -> tuple[bool, float | None]:
        if not self.policy.critic_required:
            return True, None
        frame = self._critic_frame(output)
        if frame is None or not RelaySettings.status_from_env()["configured"]:
            return False, None
        rubric = self.config.get(
            "critic_prompt",
            "Inspect the final composed benchmark. Score geometry, physical plausibility, "
            "asset identity, task clarity, and visual quality from 0 to 10. Severe issues "
            "include floating objects, penetration, duplicated proxies, or wrong asset identity.",
        )
        machine_evidence: dict[str, Any] = {}
        for name in ("manipulation_physics", "isaac_validation", "portable_validation"):
            report_path = output / "manifests" / f"{name}.json"
            if not report_path.is_file():
                continue
            report = _json(report_path)
            evidence: dict[str, Any] = {"passed": report.get("passed")}
            if name == "manipulation_physics":
                evidence["entities"] = report.get("entities", {})
            elif name == "isaac_validation":
                evidence["failed_checks"] = [
                    item.get("name")
                    for item in report.get("checks", [])
                    if isinstance(item, dict) and not item.get("passed")
                ]
            elif name == "portable_validation":
                evidence["manipulation_physics"] = (report.get("usd") or {}).get(
                    "manipulation_physics", {}
                )
            machine_evidence[name] = evidence
        stage_manifest_path = output / "scenesmith/stage_manifest.json"
        if stage_manifest_path.is_file():
            stage_manifest = _json(stage_manifest_path)
            native_bindings = stage_manifest.get("native_asset_bindings") or {}
            if isinstance(native_bindings, dict):
                machine_evidence["locked_native_asset_bindings"] = {
                    entity_id: {
                        "asset_id": binding.get("asset_id"),
                        "binding_mode": binding.get("binding_mode"),
                    }
                    for entity_id, binding in native_bindings.items()
                    if isinstance(entity_id, str) and isinstance(binding, dict)
                }
        context_assets_path = output / "scenesmith/context_assets_config.json"
        if context_assets_path.is_file():
            context_assets = _json(context_assets_path)
            support_placements = context_assets.get("task_support_placements") or {}
            if isinstance(support_placements, dict):
                machine_evidence["authored_support_placements"] = support_placements
        preflight_path = output / "supervisor/visual_preflight_report.json"
        if preflight_path.is_file():
            preflight = _json(preflight_path)
            machine_evidence["final_visual_preflight"] = {
                "passed": preflight.get("passed"),
                "checks": {
                    str(item.get("check_id")): {
                        "passed": item.get("passed"),
                        "evidence": item.get("evidence", {}),
                    }
                    for item in preflight.get("checks", [])
                    if isinstance(item, dict) and item.get("check_id")
                },
            }
        prompt = (
            f"{rubric}\nTask: {task.get('natural_language', '')}\n"
            "The following physics, schema, and portability facts were independently "
            "machine-validated. Treat passing facts as established and review every labeled "
            "GENERATED view in the contact sheet. Generated panels are different camera views "
            "of the same single scene, not separate scenes or simultaneous duplicates: "
            "an object recurring in multiple quadrants is the same object instance. Never "
            "report duplicated proxies merely because the same asset is visible in more "
            "than one quadrant; duplication must be visible within one quadrant or proven "
            "by machine identity evidence. Do not penalize one view merely for not showing "
            "hidden schemas or the full action. When an exact native asset binding is "
            "machine-validated, score shape/detail fidelity against that requested asset "
            "identity; do not demand replacement by an unrelated higher-poly model. A "
            "neutral powered-off television screen is intentional and must not be treated "
            "as a missing texture. Authored support placements identify the actual support "
            "for each loose prop; do not relabel an integral flush desk insert as a loose "
            "object when the named object is machine-authored on a different support. "
            + (
                "Panels labeled REFERENCE are user-supplied visual calibration frames, not "
                "views of the generated scene. Do not evaluate their task semantics or count "
                "their objects. Score only GENERATED panels, using the REFERENCE panels to "
                "calibrate rendering realism, material response, and lighting: 7.5 means the "
                "generated visual quality is at least comparable to that supplied baseline "
                "while all generated-scene engineering and task requirements remain satisfied. "
                if (output / "supervisor/critic_reference_manifest.json").is_file()
                else ""
            )
            + f"sequence: {json.dumps(machine_evidence, ensure_ascii=False)}\n"
            'Return JSON only: {"score": number, "severe_failures": [string], '
            '"summary": string}'
        )
        raw = GenerativeClient(RelaySettings.from_env()).analyze_image(frame, prompt)
        match = re.search(r"\{.*\}", raw, re.DOTALL)
        payload = json.loads(match.group(0) if match else raw)
        view_manifest = output / "scenesmith/final_composed_critic_views/manifest.json"
        view_payload = _json(view_manifest) if view_manifest.is_file() else {}
        view_hashes = {
            role: hashlib.sha256(
                (Path(path) if Path(path).is_absolute() else output / "scenesmith" / path).read_bytes()
            ).hexdigest()
            for role, path in (view_payload.get("views") or {}).items()
            if isinstance(role, str)
            and isinstance(path, str)
            and (Path(path) if Path(path).is_absolute() else output / "scenesmith" / path).is_file()
        }
        shared_report = {
            "schema_version": "2.0",
            "consumers": ["final_global_critic", "supervisor"],
            "source_view_manifest": str(view_manifest.relative_to(output)),
            "source_view_manifest_sha256": (
                hashlib.sha256(view_manifest.read_bytes()).hexdigest()
                if view_manifest.is_file()
                else None
            ),
            "view_sha256": view_hashes,
            "frame": str(frame.relative_to(output)),
            "frame_sha256": hashlib.sha256(frame.read_bytes()).hexdigest(),
            "threshold": self.policy.critic_min_score,
            "raw": raw,
            "result": payload,
        }
        serialized = json.dumps(shared_report, ensure_ascii=False, indent=2) + "\n"
        atomic_write_text(output / "supervisor" / "critic_report.json", serialized)
        atomic_write_text(output / "scenesmith" / "final_global_critic_report.json", serialized)
        score = float(payload.get("score", 0))
        severe = payload.get("severe_failures") or []
        return score >= self.policy.critic_min_score and not severe, score

    @staticmethod
    def _critic_frame(output: Path) -> Path | None:
        target = output / "supervisor" / "critic_frame.jpg"
        # This contact sheet is derived evidence, not an immutable source artifact.
        # Always rebuild it from the current critic-view manifest so a rerender or
        # renderer-profile change cannot be evaluated through a stale JPEG.
        if target.is_file():
            target.unlink()
        reference_manifest = target.parent / "critic_reference_manifest.json"
        if reference_manifest.is_file():
            reference_manifest.unlink()
        # Prefer the topology-aware, full-resolution evidence rendered from the
        # final canonical USD. Video extraction downsamples each view to 480p
        # before tiling and can make native meshes/materials look like proxies.
        # Prefer the release-grade composed views: unlike the SceneSmith-internal
        # DAG views, these include the robot and all outer benchmark layers.
        view_manifests = [
            output / "scenesmith/final_composed_critic_views/manifest.json",
            output / "scenesmith/final_critic_views/manifest.json",
        ]
        view_manifest = next((path for path in view_manifests if path.is_file()), None)
        if view_manifest is not None:
            try:
                raw_views = (_json(view_manifest).get("views") or {})
                view_items = [
                    (str(role), Path(str(path)))
                    for role, path in raw_views.items()
                    if isinstance(role, str) and isinstance(path, str)
                ]
                resolved_items = [
                    (role, path if path.is_absolute() else output / "scenesmith" / path)
                    for role, path in view_items
                ]
                if len(resolved_items) >= 4 and all(path.is_file() for _, path in resolved_items):
                    reference_items: list[tuple[str, Path]] = []
                    reference_root_text = os.environ.get("RHG_CRITIC_REFERENCE_DIR", "").strip()
                    if reference_root_text:
                        reference_root = Path(reference_root_text).resolve()
                        if reference_root.is_dir():
                            reference_items = [
                                (f"REFERENCE:{path.stem}", path)
                                for path in sorted(reference_root.iterdir())
                                if path.suffix.casefold() in {".jpg", ".jpeg", ".png"}
                            ][:4]
                    labeled_items = [
                        (f"GENERATED:{role}", path) for role, path in resolved_items
                    ] + reference_items
                    target.parent.mkdir(parents=True, exist_ok=True)
                    width, height, label_height = 640, 360, 24
                    columns = 3 if len(labeled_items) >= 6 else 2
                    rows = (len(labeled_items) + columns - 1) // columns
                    sheet = Image.new("RGB", (columns * width, rows * (height + label_height)), "white")
                    draw = ImageDraw.Draw(sheet)
                    for index, (role, path) in enumerate(labeled_items):
                        image = Image.open(path).convert("RGB")
                        image.thumbnail((width, height))
                        x = (index % columns) * width
                        y = (index // columns) * (height + label_height)
                        sheet.paste(image, (x + (width - image.width) // 2, y + label_height))
                        draw.text((x + 8, y + 5), role, fill="black")
                    sheet.save(target, format="JPEG", quality=94, optimize=True)
                    if reference_items:
                        atomic_write_text(
                            reference_manifest,
                            json.dumps(
                                {
                                    "schema_version": "1.0",
                                    "calibration_rule": (
                                        "7.5 means generated visual quality is at least "
                                        "comparable to the user-supplied reference"
                                    ),
                                    "generated_views": [role for role, _ in resolved_items],
                                    "reference_frames": [
                                        {
                                            "label": role,
                                            "path": str(path),
                                            "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
                                        }
                                        for role, path in reference_items
                                    ],
                                },
                                indent=2,
                            )
                            + "\n",
                        )
                    elif reference_manifest.exists():
                        reference_manifest.unlink()
                    return target
            except (OSError, ValueError, TypeError):
                pass
        preview = output / "scenesmith" / "preview.mp4"
        if preview.is_file() and shutil.which("ffmpeg"):
            target.parent.mkdir(parents=True, exist_ok=True)
            result = subprocess.run(
                [
                    "ffmpeg",
                    "-y",
                    "-i",
                    str(preview),
                    "-vf",
                    "fps=1,scale=480:270:force_original_aspect_ratio=decrease,"
                    "pad=480:270:(ow-iw)/2:(oh-ih)/2,tile=2x2",
                    "-frames:v",
                    "1",
                    str(target),
                ],
                capture_output=True,
                timeout=60,
                check=False,
            )
            if result.returncode == 0 and target.is_file():
                return target
        candidates = sorted((output / "scenesmith").glob("iteration_frames/*.png"))
        return candidates[-1] if candidates else None

    @staticmethod
    def _report(
        gates: list[GateResult], *, critic_passed: bool, critic_score: float | None = None
    ) -> QualityReport:
        failed = sorted(
            gate.gate_id for gate in gates if not gate.passed and gate.severity == "severe"
        )
        signature = hashlib.sha256("|".join(failed).encode()).hexdigest()[:16] if failed else None
        hard_passed = not failed
        return QualityReport(
            accepted=hard_passed and critic_passed,
            hard_gates_passed=hard_passed,
            critic_passed=critic_passed,
            critic_score=critic_score,
            gates=gates,
            failure_signature=signature,
        )