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
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import os
import re
import shutil
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import yaml  # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict

from packages.core.files import atomic_write_text
from packages.scene_generation.design_contract import (
    validate_repair_plan_against_contract,
)
from packages.supervisor.case import VERSION_PATTERN, CaseManager
from packages.supervisor.models import (
    GateResult,
    IterationPolicy,
    QualityReport,
    RepairAction,
    RepairPlan,
    RepairStep,
)
from packages.supervisor.planner import RepairPlanner
from packages.supervisor.quality import QualityEvaluator
from packages.supervisor.snapshot import ensure_version_media

BuildAttempt = Callable[[Path, RepairPlan | None], dict[str, Any]]


def is_packaging_only_recheck(plan: RepairPlan | None) -> bool:
    """Return whether a repair only revalidates an already accepted scene payload."""

    return bool(plan is not None and plan.strategy == "portable_packaging_recheck")


def materialize_packaging_recheck(
    case_root: Path,
    output: Path,
    plan: RepairPlan,
) -> dict[str, Any]:
    """Clone an immutable parent payload without re-entering SceneSmith.

    Portable-package defects are downstream of generation. Re-running SceneSmith can
    change geometry and, more importantly, turns a packaging repair into another model
    generation. The clone deliberately excludes prior Supervisor decisions, checksums,
    and portable validation so the new version receives fresh evidence.
    """

    if not is_packaging_only_recheck(plan):
        raise ValueError("repair plan is not a portable packaging recheck")
    root = case_root.resolve()
    source = (root / plan.parent_version).resolve()
    destination = output.resolve()
    if not source.is_relative_to(root) or not destination.is_relative_to(root):
        raise ValueError("packaging recheck paths must remain inside the case directory")
    if source == destination or not source.is_dir():
        raise ValueError(f"invalid packaging recheck parent: {source}")
    required = ("root.usda", "manifests/task.json", "manifests/scene.json")
    missing = [name for name in required if not (source / name).is_file()]
    if missing:
        raise ValueError(f"packaging recheck parent is incomplete: missing={missing}")

    def ignore(directory: str, names: list[str]) -> set[str]:
        current = Path(directory).resolve()
        ignored: set[str] = set()
        if current == source:
            ignored.update({"supervisor", "checksums.sha256"} & set(names))
        if current == source / "manifests":
            ignored.update({"portable_validation.json"} & set(names))
        return ignored

    shutil.copytree(source, destination, dirs_exist_ok=True, symlinks=True, ignore=ignore)
    provenance = {
        "schema_version": "1.0",
        "mode": "packaging_only_recheck",
        "source_version": source.name,
        "scene_generation_invoked": False,
        "excluded_evidence": [
            "supervisor/",
            "checksums.sha256",
            "manifests/portable_validation.json",
        ],
    }
    atomic_write_text(
        destination / "supervisor" / "packaging_recheck_provenance.json",
        json.dumps(provenance, ensure_ascii=False, indent=2) + "\n",
    )
    return provenance


def generation_failure_entities(exc: BaseException) -> list[str]:
    """Extract stable entity IDs from evidence-bound subtree failures."""

    message = str(exc)
    deterministic_match = re.search(
        r"deterministic_placement_failed:affected_entities=([^:;\s]+)", message
    )
    if deterministic_match:
        return sorted(
            {entity_id for entity_id in deterministic_match.group(1).split(",") if entity_id}
        )
    scored_failures = {
        match.group(1)
        for match in re.finditer(
            r"['\"]local-critic:branch-([A-Za-z0-9_.-]+)['\"]\s*:\s*"
            r"['\"][^'\"]*critic_below_threshold[^'\"]*['\"]",
            message,
        )
    }
    if scored_failures:
        return sorted(scored_failures)
    incomplete_branches = re.search(
        r"critical manipulation branches did not produce their planned entities:\s*\[([^]]+)\]",
        message,
        flags=re.IGNORECASE,
    )
    if incomplete_branches:
        branch_ids = re.findall(r"['\"]([A-Za-z0-9_.-]+)['\"]", incomplete_branches.group(1))
        # A furniture repair may expand one stable support into implementation
        # modules. Report the stable owner so checkpoint repair can replace the
        # invalid expansion without leaking generated instance IDs into the task.
        return sorted({re.sub(r"_module_[0-9]+$", "", item) for item in branch_ids})
    return sorted(
        {match.group(1) for match in re.finditer(r"local-critic:branch-([A-Za-z0-9_.-]+)", message)}
    )


def generation_failure_signature(exc: BaseException) -> str:
    """Classify infrastructure failures so unrelated defects do not stagnate."""

    message = str(exc).casefold()
    if (
        "deterministic_placement_failed:" in message
        or "infeasible_asset:semantic_constraint:" in message
    ):
        # Asset generation has completed. The failed hard gate belongs to the
        # deterministic placement/composition stage and must never trigger a
        # furniture or manipulation regeneration by default.
        return "deterministic_placement_failure"
    if "final_usd_geometry_failed:" in message:
        # The expensive generative stages succeeded.  This is a deterministic
        # composition/export defect and must only re-run post-processing.
        return "final_usd_geometry_failure"
    if (
        "agent execution dag failed" in message
        and ("merge:world" in message or "global-critic:scene" in message)
        and "local-critic:branch-" not in message
    ):
        # Generation, local placement, and local critics have already completed.
        # Merge/global audit failures are downstream post-processing defects; a
        # manipulation resume would throw away accepted subtree work.
        return "agent_postprocess_failure"
    if (
        "agent execution dag failed" in message
        and "local-critic:branch-" in message
    ):
        # Preserve the semantic failure across the SceneSmith subprocess boundary.
        # This is an owned furniture-subtree rejection, not the final composed
        # visual gate. Route it to furniture checkpoint repair so the rejected
        # subtree is regenerated while accepted siblings remain frozen.
        return "agent_local_critic_failure"
    if (
        "critical manipulation branches did not produce their planned entities" in message
        and re.search(r"_module_[0-9]+", message)
    ):
        # Manipulation is only the first consumer to notice the defect. A stable
        # furniture entity was replaced by ad-hoc modules, so replaying the same
        # manipulation checkpoint cannot repair it.
        return "upstream_entity_identity_failure"
    if "no object binding for" in message:
        # Non-fatal tracing timeouts can precede the terminal traceback.  The
        # deterministic binding error is the actionable cause and takes priority.
        return "entity_binding_failure"
    if isinstance(exc, TimeoutError) or "timed out" in message or "timeout" in message:
        return "generation_timeout"
    if "manipuland shard" in message:
        return "manipuland_worker_failure"
    if "scenesmith failed" in message:
        return "scenesmith_generation_failure"
    return "generation_failure"


def generation_failure_fingerprint(exc: BaseException) -> str:
    """Scope semantic failures to the owned subtree for stagnation accounting."""

    signature = generation_failure_signature(exc)
    entities = generation_failure_entities(exc)
    if (
        signature
        in {
            "supervisor_visual_critic",
            "agent_local_critic_failure",
            "deterministic_placement_failure",
            "upstream_entity_identity_failure",
        }
        and entities
    ):
        return f"{signature}:{','.join(entities)}"
    return signature


def refine_historical_failure(report: QualityReport, output: Path | None = None) -> QualityReport:
    """Recover a semantic gate from an older generic subprocess failure report."""

    original_signature = (report.failure_signature or "").split(":", 1)[0]
    if original_signature not in {
        "scenesmith_generation_failure",
        "supervisor_visual_critic",
    }:
        return report
    message = "\n".join(gate.message for gate in report.gates if gate.message)
    classified = generation_failure_signature(RuntimeError(message))
    if (
        original_signature == "supervisor_visual_critic"
        and classified != "agent_local_critic_failure"
    ):
        return report
    refined = (
        report.failure_signature
        if classified in {"generation_failure", "scenesmith_generation_failure"}
        else classified
    )
    if refined == report.failure_signature and output is not None:
        minimum_visual_score: float | None = None
        for score_path in output.glob("scenesmith/upstream/**/scores.yaml"):
            try:
                payload = yaml.safe_load(score_path.read_text(encoding="utf-8")) or {}
            except (OSError, yaml.YAMLError):
                continue
            grades = [
                float(value["grade"])
                for value in payload.values()
                if isinstance(value, dict) and isinstance(value.get("grade"), (int, float))
            ]
            if grades:
                score = min(grades)
                minimum_visual_score = (
                    score if minimum_visual_score is None else min(minimum_visual_score, score)
                )
        if minimum_visual_score is not None and minimum_visual_score < 7.0:
            refined = "supervisor_visual_critic"
    if refined == report.failure_signature:
        return report
    gates = [
        gate.model_copy(
            update={
                "gate_id": refined,
                "affected_entities": gate.affected_entities
                or generation_failure_entities(RuntimeError(gate.message)),
            }
        )
        if gate.gate_id
        in {"scenesmith_generation_failure", "supervisor_visual_critic"}
        else gate
        for gate in report.gates
    ]
    return report.model_copy(update={"failure_signature": refined, "gates": gates})


class IterationResult(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)

    case_dir: Path
    output_dir: Path | None
    released_version: str | None
    release: Path | None
    blocked: Path | None
    attempts: list[str]
    payload: dict[str, Any] | None = None


class SupervisorRunner:
    def __init__(
        self,
        manager: CaseManager,
        policy: IterationPolicy,
        build_attempt: BuildAttempt,
        *,
        evaluator: QualityEvaluator | None = None,
        resume_blocked: bool = False,
    ) -> None:
        self.manager = manager
        self.policy = policy
        self.build_attempt = build_attempt
        self.evaluator = evaluator or QualityEvaluator(policy)
        self.planner = RepairPlanner(policy.repair_policy, policy.stagnation_repeat_limit)
        self.resume_blocked = resume_blocked

    def run(self) -> IterationResult:
        with self.manager.campaign_locked():
            return self._run_locked()

    def _run_locked(self) -> IterationResult:
        started = time.monotonic()
        atomic_write_text(
            self.manager.root / "supervisor_policy.json",
            self.policy.model_dump_json(indent=2) + "\n",
        )
        self._reconcile_interrupted_attempts()
        existing_release = self.manager.root / "release.json"
        if existing_release.is_file():
            release_data = json.loads(existing_release.read_text(encoding="utf-8"))
            output = self.manager.root / str(release_data["run_dir"])
            return IterationResult(
                case_dir=self.manager.root,
                output_dir=output,
                released_version=output.name,
                release=existing_release,
                blocked=None,
                attempts=[],
            )
        history = self._attempt_history()
        attempts: list[str] = []
        parent: str | None = history[-1][1].version if history else None
        repair_plan: RepairPlan | None = None
        last_signature, consecutive_failures = self._consecutive_failure_state(history)
        blocked_path = self.manager.root / "blocked.json"
        resumed_campaign = False
        if self.resume_blocked:
            if not blocked_path.is_file():
                raise RuntimeError("--resume-blocked requires an existing blocked.json")
            blocked_payload = json.loads(blocked_path.read_text(encoding="utf-8"))
            if not blocked_payload.get("resumable"):
                raise RuntimeError("the blocked campaign is not resumable")
            audit_path = self.manager.root / "resume_audit.jsonl"
            with audit_path.open("a", encoding="utf-8") as handle:
                handle.write(
                    json.dumps(
                        {
                            "schema_version": "1.0",
                            "resumed_at": datetime.now(UTC).isoformat(),
                            "prior_block": blocked_payload,
                            "history_attempt_count": len(history),
                        },
                        ensure_ascii=False,
                    )
                    + "\n"
                )
            blocked_path.unlink()
            resumed_campaign = True
            # A requested resume starts a fresh repeated-failure audit while
            # preserving all attempts and their original quality reports.
            consecutive_failures = 0
        last_payload: dict[str, Any] | None = None
        if consecutive_failures >= self.policy.same_failure_signature_limit:
            repeat_phrase = (
                "twice"
                if self.policy.same_failure_signature_limit == 2
                else f"{self.policy.same_failure_signature_limit} times"
            )
            return self._blocked_result(
                f"failure signature {last_signature!r} repeated consecutively {repeat_phrase}",
                started,
                parent,
                attempts,
            )
        if history:
            last_report = self._quality_report(history[-1][0])
            if last_report is None:
                return self._blocked_result(
                    "latest attempt has no valid quality report",
                    started,
                    parent,
                    attempts,
                )
            if last_report.accepted:
                release = self.manager.release(history[-1][0], last_report)
                return IterationResult(
                    case_dir=self.manager.root,
                    output_dir=history[-1][0],
                    released_version=history[-1][1].version,
                    release=release,
                    blocked=None,
                    attempts=attempts,
                )
            last_report = refine_historical_failure(last_report, history[-1][0])
            if (
                self.policy.max_total_attempts is not None
                and len(history) >= self.policy.max_total_attempts
            ):
                return self._blocked_result(
                    f"maximum of {self.policy.max_total_attempts} outer attempts already reached",
                    started,
                    parent,
                    attempts,
                )
            repair_plan = self.planner.plan(
                last_report,
                parent_version=parent or history[-1][1].version,
                signature_occurrences=max(consecutive_failures, 1),
            )
            repair_plan = self._checkpoint_repair_plan(repair_plan)
            if repair_plan is None and not self._can_retry_failed_stage_without_checkpoint(
                last_report,
                parent or history[-1][1].version,
            ) and not resumed_campaign:
                return self._blocked_result(
                    "no validated checkpoint-local repair is available",
                    started,
                    parent,
                    attempts,
                )
        while time.monotonic() - started < self.policy.wall_clock_budget_s:
            if (
                self.policy.max_total_attempts is not None
                and len(history) + len(attempts) >= self.policy.max_total_attempts
            ):
                break
            output, manifest = self.manager.allocate_attempt(parent_version=parent)
            attempts.append(output.name)
            attempt_started = time.monotonic()
            attempt_number = len(history) + len(attempts)
            budget_multiplier = (
                self.policy.first_attempt_budget_multiplier if attempt_number == 1 else 1.0
            )
            effective = {
                "schema_version": "1.0",
                "attempt_number": attempt_number,
                "attempt_budget_multiplier": budget_multiplier,
                "max_total_attempts": self.policy.max_total_attempts,
                "critic_min_score": self.policy.critic_min_score,
                "checkpoint_repairs_only_after_first": (
                    self.policy.checkpoint_repairs_only_after_first
                ),
            }
            if repair_plan is not None:
                repair_path = output / "supervisor" / "repair_plan.json"
                atomic_write_text(repair_path, repair_plan.model_dump_json(indent=2) + "\n")
                effective.update(
                    {
                        "parent_version": repair_plan.parent_version,
                        "strategy": repair_plan.strategy,
                        "steps": [step.model_dump(mode="json") for step in repair_plan.steps],
                    }
                )
                manifest.repair_plan = "supervisor/repair_plan.json"
                self.manager.write_attempt(output, manifest)
            atomic_write_text(
                output / "supervisor" / "effective_overrides.json",
                json.dumps(effective, ensure_ascii=False, indent=2) + "\n",
            )
            report: QualityReport
            error: str | None = None
            try:
                if is_packaging_only_recheck(repair_plan):
                    assert repair_plan is not None
                    last_payload = materialize_packaging_recheck(
                        self.manager.root, output, repair_plan
                    )
                else:
                    with repair_environment(
                        repair_plan,
                        self.manager.root,
                        attempt_budget_multiplier=budget_multiplier,
                    ):
                        last_payload = self.build_attempt(output, repair_plan)
                ensure_version_media(
                    output,
                    force_snapshot=True,
                    allow_final_preview_fallback=False,
                )
                report = self.evaluator.evaluate(output)
                if report.accepted:
                    ensure_version_media(output, force_snapshot=True)
                else:
                    ensure_version_media(
                        output,
                        force_snapshot=True,
                        allow_final_preview_fallback=False,
                    )
            except Exception as exc:
                error = f"{type(exc).__name__}: {exc}"
                gate_id = generation_failure_signature(exc)
                failure_signature = generation_failure_fingerprint(exc)
                try:
                    # Persist the failure first so a pre-render diagnostic frame
                    # contains the actual failed stage instead of a generic card.
                    manifest.error = error
                    self.manager.write_attempt(output, manifest)
                    ensure_version_media(
                        output,
                        force_snapshot=True,
                        allow_final_preview_fallback=False,
                    )
                except Exception as media_exc:
                    error += f"; media_contract={type(media_exc).__name__}: {media_exc}"
                report = QualityReport(
                    accepted=False,
                    hard_gates_passed=False,
                    critic_passed=not self.policy.critic_required,
                    gates=[
                        GateResult(
                            gate_id=gate_id,
                            passed=False,
                            message=error,
                            affected_entities=generation_failure_entities(exc),
                        )
                    ],
                    failure_signature=failure_signature,
                )
            quality_path = output / "supervisor" / "quality_report.json"
            atomic_write_text(quality_path, report.model_dump_json(indent=2) + "\n")
            manifest.status = "passed" if report.accepted else "failed"
            manifest.completed_at = datetime.now(UTC).isoformat()
            manifest.duration_s = round(time.monotonic() - attempt_started, 3)
            manifest.quality_report = "supervisor/quality_report.json"
            manifest.failure_signature = report.failure_signature
            manifest.error = error
            self.manager.write_attempt(output, manifest)
            self.manager.append_attempt(manifest)
            self.manager.update_campaign()
            if report.accepted and (output / "snapshot.jpg").is_file():
                self.manager.consider_for_major(output, report)
            if report.accepted:
                release = self.manager.release(output, report)
                return IterationResult(
                    case_dir=self.manager.root,
                    output_dir=output,
                    released_version=output.name,
                    release=release,
                    blocked=None,
                    attempts=attempts,
                    payload=last_payload,
                )
            signature = report.failure_signature or "unknown"
            if signature == last_signature:
                consecutive_failures += 1
            else:
                last_signature = signature
                consecutive_failures = 1
            if consecutive_failures >= self.policy.same_failure_signature_limit:
                repeat_phrase = (
                    "twice"
                    if self.policy.same_failure_signature_limit == 2
                    else f"{self.policy.same_failure_signature_limit} times"
                )
                return self._blocked_result(
                    f"failure signature {signature!r} repeated consecutively {repeat_phrase}",
                    started,
                    output.name,
                    attempts,
                    output=output,
                    payload=last_payload,
                )
            repair_plan = self.planner.plan(
                report,
                parent_version=output.name,
                signature_occurrences=consecutive_failures,
            )
            repair_plan = self._checkpoint_repair_plan(repair_plan)
            parent = output.name
            if repair_plan is None and not self._can_retry_failed_stage_without_checkpoint(
                report,
                parent,
            ):
                return self._blocked_result(
                    "allowlisted checkpoint-local repair strategies exhausted",
                    started,
                    parent,
                    attempts,
                    output=output,
                    payload=last_payload,
                )
        attempt_limit_reached = (
            self.policy.max_total_attempts is not None
            and len(history) + len(attempts) >= self.policy.max_total_attempts
        )
        blocked = self.manager.block(
            reason=(
                f"maximum of {self.policy.max_total_attempts} outer attempts reached"
                if attempt_limit_reached
                else "wall-clock budget exhausted"
            ),
            elapsed_s=time.monotonic() - started,
            last_version=parent,
        )
        return IterationResult(
            case_dir=self.manager.root,
            output_dir=self.manager.root / parent if parent else None,
            released_version=None,
            release=None,
            blocked=blocked,
            attempts=attempts,
            payload=last_payload,
        )

    def _attempt_history(self) -> list[tuple[Path, Any]]:
        history = []
        for output in self.manager.root.iterdir():
            if not output.is_dir() or VERSION_PATTERN.fullmatch(output.name) is None:
                continue
            manifest_path = output / "supervisor" / "attempt_manifest.json"
            if manifest_path.is_file():
                history.append((output, self.manager.read_attempt(output)))
        return sorted(
            history,
            key=lambda item: int(VERSION_PATTERN.fullmatch(item[0].name).group("number")),
        )

    @staticmethod
    def _consecutive_failure_state(history: list[tuple[Path, Any]]) -> tuple[str | None, int]:
        signature: str | None = None
        count = 0
        for _, manifest in reversed(history):
            if manifest.status != "failed":
                break
            current = manifest.failure_signature or "unknown"
            if signature is None:
                signature = current
            if current != signature:
                break
            count += 1
        return signature, count

    @staticmethod
    def _quality_report(output: Path) -> QualityReport | None:
        path = output / "supervisor" / "quality_report.json"
        if not path.is_file():
            return None
        try:
            return QualityReport.model_validate_json(path.read_text(encoding="utf-8"))
        except ValueError:
            return None

    def _checkpoint_repair_plan(self, plan: RepairPlan | None) -> RepairPlan | None:
        if plan is None or not self.policy.checkpoint_repairs_only_after_first:
            return plan
        checkpoint = self._nearest_ancestor_checkpoint(plan.parent_version)
        if checkpoint is None:
            return None
        steps = list(plan.steps)
        resume_index = next(
            (
                index
                for index, step in enumerate(steps)
                if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT
            ),
            None,
        )
        failure_kind = (plan.failure_signature or "").split(":", 1)[0]
        requested_resume_stage = steps[resume_index].stage if resume_index is not None else None
        # A process can be interrupted while carrying out a postprocess-only
        # repair after its reusable upstream checkpoint has already been copied.
        # The generic interrupted-attempt strategy asks for ``manipuland``, but
        # that would unnecessarily reopen accepted Agent geometry. Preserve the
        # interrupted parent's explicitly persisted postprocess scope instead.
        if failure_kind == "interrupted_attempt":
            parent_plan_path = (
                self.manager.root
                / plan.parent_version
                / "supervisor"
                / "repair_plan.json"
            )
            if parent_plan_path.is_file():
                try:
                    parent_plan = RepairPlan.model_validate_json(
                        parent_plan_path.read_text(encoding="utf-8")
                    )
                except (OSError, ValueError):
                    parent_plan = None
                parent_resume = (
                    next(
                        (
                            step
                            for step in parent_plan.steps
                            if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT
                        ),
                        None,
                    )
                    if parent_plan is not None
                    else None
                )
                if parent_resume is not None and parent_resume.stage == "postprocess":
                    requested_resume_stage = "postprocess"
        resume_stage = (
            "postprocess"
            if requested_resume_stage == "postprocess"
            or failure_kind
            in {
                "final_usd_geometry_failure",
                "agent_postprocess_failure",
                "deterministic_placement_failure",
            }
            else self._checkpoint_resume_stage(checkpoint)
        )
        if resume_stage is None:
            return None
        # The checkpoint detector identifies how far a prior attempt completed;
        # it must not silently narrow an explicit repair plan past the stage that
        # actually failed. For example, a completed manipulation checkpoint can
        # still contain furniture rejected by the final visual critic, in which
        # case the planner's requested furniture repair must be honored.
        if resume_index is not None and plan.strategy in {
            "global_dag_furniture_repair",
            "visual_support_and_layout_repair",
            "upstream_entity_identity_repair",
        }:
            requested_stage = steps[resume_index].stage
            stage_order = ("floor_plan", "furniture", "wall", "ceiling", "manipuland")
            if (
                requested_stage in stage_order
                and resume_stage in stage_order
                and stage_order.index(requested_stage) < stage_order.index(resume_stage)
            ):
                resume_stage = requested_stage
        resume = RepairStep(
            action=RepairAction.RERUN_STAGE_FROM_CHECKPOINT,
            stage=resume_stage,
            checkpoint=checkpoint.as_posix(),
            reason="Resume the failed branch from the parent SceneSmith checkpoint.",
        )
        if resume_index is None:
            steps.insert(0, resume)
        else:
            original = steps[resume_index]
            steps[resume_index] = original.model_copy(
                update={"stage": resume_stage, "checkpoint": checkpoint.as_posix()}
            )
        return plan.model_copy(update={"steps": steps})

    def _can_retry_failed_stage_without_checkpoint(
        self,
        report: QualityReport,
        parent_version: str,
    ) -> bool:
        """Permit one deterministic stage retry when no checkpoint can exist yet.

        A worker/runtime failure before the first materialized checkpoint cannot
        be expressed honestly as a checkpoint-local scene repair.  The outer
        repeated-signature guard still stops the campaign if the retry produces
        the same failure again.  Once any usable checkpoint exists, the normal
        checkpoint-only repair policy remains authoritative.
        """

        if report.failure_signature not in {
            "generation_failure",
            "generation_timeout",
            "interrupted_attempt",
            "scenesmith_generation_failure",
        }:
            return False
        return self._nearest_ancestor_checkpoint(parent_version) is None

    def _checkpoint_resume_stage(self, checkpoint: Path) -> str | None:
        """Select the earliest unfinished SceneSmith stage in a checkpoint."""

        root = self.manager.root / checkpoint
        for timing_path in root.glob("scene_*/room_*/parallel_manipulands/timing.json"):
            try:
                timing = json.loads(timing_path.read_text(encoding="utf-8"))
            except (OSError, ValueError):
                continue
            completions = timing.get("branch_completion") or {}
            failed = timing.get("failed_critical_branches") or []
            if (
                isinstance(completions, dict)
                and completions
                and not failed
                and all(
                    isinstance(value, dict) and value.get("passed") is True
                    for value in completions.values()
                )
            ):
                # Re-enter manipulation to reproduce the final merged blend;
                # the accepted furniture/architecture checkpoint remains frozen.
                return "manipuland"
        for ledger_path in root.glob("scene_*/room_*/parallel_base_branches/execution_ledger.json"):
            try:
                ledger = json.loads(ledger_path.read_text(encoding="utf-8"))
            except (OSError, ValueError):
                continue
            if ledger.get("status") == "complete":
                return "manipuland"
        floor_render_patterns = (
            "scene_*/floor_plans/floor_plan_renders/renders_*",
            "scene_*/floor_plans/*/floor_plan_renders/renders_*",
        )
        if any(any(root.glob(pattern)) for pattern in floor_render_patterns):
            return "furniture"
        return None

    def _nearest_ancestor_checkpoint(self, version: str) -> Path | None:
        """Return the newest usable checkpoint in an attempt's ancestry.

        Infrastructure failures may create a version directory before SceneSmith
        writes any checkpoint. Follow parent_version links so a later invocation
        can resume from the last materialized attempt instead of treating the
        resource-only failure as a request for full regeneration.
        """

        candidate = version
        visited: set[str] = set()
        while candidate and candidate not in visited:
            visited.add(candidate)
            checkpoint = Path(candidate) / "scenesmith" / "upstream"
            resolved = self.manager.root / checkpoint
            # Logs, Hydra configs and half-written scene directories are not a
            # resumable checkpoint.  SceneSmith writes this marker only after
            # the reusable base state has been materialized.
            if (
                (resolved / "checkpoint.json").is_file()
                or self._legacy_upstream_complete(resolved)
                or self._checkpoint_resume_stage(checkpoint) is not None
            ):
                return checkpoint
            manifest_path = resolved.parents[1] / "supervisor" / "attempt_manifest.json"
            if not manifest_path.is_file():
                return None
            try:
                manifest = self.manager.read_attempt(resolved.parents[1])
            except ValueError:
                return None
            candidate = manifest.parent_version or ""
        return None

    @staticmethod
    def _legacy_upstream_complete(upstream: Path) -> bool:
        """Recognize runs completed before the checkpoint marker was introduced."""

        log_path = upstream.parent / "upstream.log"
        if not log_path.is_file():
            return False
        try:
            if "Experiment execution completed in" not in log_path.read_text(
                encoding="utf-8", errors="replace"
            ):
                return False
        except OSError:
            return False
        return any(upstream.glob("scene_*/room_*/scene_states/final_scene/scene.blend")) or any(
            upstream.glob("**/house.blend")
        )

    def _blocked_result(
        self,
        reason: str,
        started: float,
        parent: str | None,
        attempts: list[str],
        *,
        output: Path | None = None,
        payload: dict[str, Any] | None = None,
    ) -> IterationResult:
        blocked = self.manager.block(
            reason=reason,
            elapsed_s=time.monotonic() - started,
            last_version=parent,
        )
        return IterationResult(
            case_dir=self.manager.root,
            output_dir=output or (self.manager.root / parent if parent else None),
            released_version=None,
            release=None,
            blocked=blocked,
            attempts=attempts,
            payload=payload,
        )

    def _reconcile_interrupted_attempts(self) -> None:
        """Finalize attempts left running by a prior process interruption.

        A process cannot execute cleanup after SIGKILL or host loss. The next
        Supervisor invocation therefore repairs the visual contract before it
        allocates another version, without requiring an external backfill job.
        """

        reconciled = False
        for output in sorted(self.manager.root.iterdir()):
            if not output.is_dir() or VERSION_PATTERN.fullmatch(output.name) is None:
                continue
            manifest_path = output / "supervisor" / "attempt_manifest.json"
            if not manifest_path.is_file():
                continue
            manifest = self.manager.read_attempt(output)
            if manifest.status != "running":
                continue
            error = "Supervisor process ended before attempt finalization; auto-reconciled"
            failure_signature = "interrupted_attempt"
            # If a bad retry was interrupted before it produced a checkpoint,
            # retain a deterministic parent failure that can be repaired from
            # the parent's completed upstream scene.  Otherwise the generic
            # interruption would unnecessarily rerun an expensive Agent stage.
            current_upstream = output / "scenesmith" / "upstream"
            if manifest.parent_version and not (current_upstream / "checkpoint.json").is_file():
                parent_output = self.manager.root / manifest.parent_version
                parent_report = self._quality_report(parent_output)
                if parent_report is not None:
                    parent_report = refine_historical_failure(parent_report, parent_output)
                    parent_failure_kind = (parent_report.failure_signature or "").split(":", 1)[0]
                    if parent_failure_kind in {
                        "final_usd_geometry_failure",
                        "agent_postprocess_failure",
                        "deterministic_placement_failure",
                    }:
                        failure_signature = parent_report.failure_signature
                        error += "; retained deterministic failure from parent checkpoint"
            manifest.error = error
            try:
                ensure_version_media(
                    output,
                    force_snapshot=True,
                    allow_final_preview_fallback=False,
                )
            except Exception as media_exc:
                manifest.error += f"; media_contract={type(media_exc).__name__}: {media_exc}"
            report = QualityReport(
                accepted=False,
                hard_gates_passed=False,
                critic_passed=not self.policy.critic_required,
                gates=[
                    GateResult(
                        gate_id=failure_signature,
                        passed=False,
                        message=manifest.error,
                    )
                ],
                failure_signature=failure_signature,
            )
            quality_path = output / "supervisor" / "quality_report.json"
            atomic_write_text(quality_path, report.model_dump_json(indent=2) + "\n")
            manifest.status = "failed"
            manifest.completed_at = datetime.now(UTC).isoformat()
            manifest.quality_report = "supervisor/quality_report.json"
            manifest.failure_signature = failure_signature
            self.manager.write_attempt(output, manifest)
            self.manager.append_attempt(manifest)
            reconciled = True
        if reconciled:
            self.manager.update_campaign()


@contextmanager
def repair_environment(
    plan: RepairPlan | None,
    case_root: Path,
    *,
    attempt_budget_multiplier: float = 1.0,
) -> Iterator[None]:
    updates = {
        "RHG_CASE_ROOT": str(case_root),
        "RHG_ATTEMPT_BUDGET_MULTIPLIER": str(attempt_budget_multiplier),
    }
    design_contract = case_root / "case_design" / "contract.json"
    if design_contract.is_file():
        if plan is not None:
            validate_repair_plan_against_contract(design_contract, plan)
        updates["RHG_CASE_DESIGN_CONTRACT"] = str(design_contract.resolve())
    fresh_scene = os.environ.get("RHG_FRESH_SCENE", "0").casefold() in {
        "1",
        "true",
        "yes",
    }
    external_reuse = (
        "" if fresh_scene else os.environ.get("RHG_SCENESMITH_REUSE_FROM", "").strip()
    )
    if external_reuse:
        resolved_external_reuse = Path(external_reuse).resolve()
        if not resolved_external_reuse.is_dir():
            raise NotADirectoryError(resolved_external_reuse)
        # A product suite may reuse a separately accepted immutable room. The
        # adapter still makes a private copy before deterministic postprocessing.
        updates["RHG_SCENESMITH_REUSE_FROM"] = str(resolved_external_reuse)
    if plan is not None:
        updates["RHG_REPAIR_PLAN"] = json.dumps(plan.model_dump(mode="json"))
    resume = (
        next(
            (
                step
                for step in plan.steps
                if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT
            ),
            None,
        )
        if plan is not None
        else None
    )
    if resume is not None and not fresh_scene:
        if resume.stage == "postprocess":
            if not resume.checkpoint:
                raise ValueError("postprocess repair requires a SceneSmith checkpoint")
            checkpoint = Path(resume.checkpoint)
            if not checkpoint.is_absolute():
                checkpoint = case_root / checkpoint
            resolved = checkpoint.resolve()
            if not resolved.is_relative_to(case_root.resolve()):
                raise ValueError("repair checkpoint must remain within the case directory")
            # The checkpoint points at ``scenesmith/upstream``.  The adapter
            # stages that completed SceneSmith directory into the new version
            # and asks the worker to re-run deterministic export/validation only.
            updates["RHG_SCENESMITH_REUSE_FROM"] = str(resolved.parent)
        else:
            if resume.stage:
                updates["RHG_SCENESMITH_START_STAGE"] = resume.stage
            if resume.checkpoint:
                checkpoint = Path(resume.checkpoint)
                if not checkpoint.is_absolute():
                    checkpoint = case_root / checkpoint
                resolved = checkpoint.resolve()
                if not resolved.is_relative_to(case_root.resolve()):
                    raise ValueError("repair checkpoint must remain within the case directory")
                updates["RHG_SCENESMITH_RESUME_FROM"] = str(resolved)
    managed_keys = {
        *updates,
        "RHG_REPAIR_PLAN",
        "RHG_SCENESMITH_START_STAGE",
        "RHG_SCENESMITH_RESUME_FROM",
        "RHG_SCENESMITH_REUSE_FROM",
    }
    previous = {key: os.environ.get(key) for key in managed_keys}
    for key in managed_keys - updates.keys():
        os.environ.pop(key, None)
    os.environ.update(updates)
    try:
        yield
    finally:
        for key, value in previous.items():
            if value is None:
                os.environ.pop(key, None)
            else:
                os.environ[key] = value