File size: 31,851 Bytes
870b85a
 
 
 
 
 
3f15e9f
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Prepare three fresh CPU shells, then explicitly execute and render them.

Preparation never consumes an existing scene. Execute/render are dry runs unless
--execute is supplied. See THREE_CASES.md for staging and evidence limitations.
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import rhg_paths

import argparse
import copy
from contextlib import contextmanager
import hashlib
import json
import math
import os
from pathlib import Path
import re
import sys

ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / 'source'
CODE = SOURCE / 'scripts/internal/scene_generation/real_assets'
sys.path.insert(0, str(ROOT))
from real_test import run_server_house as adapter
from real_test.projection_adapter import project_with_semantic_preservation
from visibility_plan import INTERIOR_RENDER_PROFILE

SEEDS = (2026102401, 2026102402, 2026102403)
SCHEMA = 'rhg.three-fresh-houses.v1'
STAGE_TIMEOUT_S = 3600
GENERATION_TIMEOUT_S = 18000
REPAIR_TIMEOUT_S = 2 * (GENERATION_TIMEOUT_S + 3 * 900) + 600
SUPERVISOR = os.environ.get('RHG_SUPERVISOR_PYTHON', sys.executable)
SCRIPT = Path(__file__).resolve()
FUNCTION_FIELDS = (
    'entity_id', 'room_id', 'role', 'layout_slot_id', 'semantic_group',
    'wall_anchor', 'layout_relation', 'placement_side', 'supported_by_entity_id',
    'support_entity_id', 'support_relation', 'face_target_slot_id',
    'front_target_entity_id', 'asset_pool_key', 'binding_semantic_key',
    'procedural_kind',
)


def fingerprint(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'),
                                     allow_nan=False).encode()).hexdigest()


def fresh_directory(path):
    path = Path(path).resolve()
    if path in (ROOT, SOURCE) or SOURCE in path.parents:
        raise ValueError('Output must be outside the source tree')
    path.mkdir(parents=True, exist_ok=False)
    return path


def case_runtime(template, case, seed):
    runtime = copy.deepcopy(template)
    case = Path(case)
    for key, relative in dict(out_root='generated', jobs_root='jobs', cache_root='cache',
            usage_ledger='usage.json', baseline_root='layout', mdl_bake_cache='mdl-cache',
            cuda_kernel_cache_root='cuda-cache').items():
        runtime[key] = str(case / relative)
    runtime.update(seed=seed, material_seed=seed, rplan_index=None,
        rplan_sampling='qualified_random', scene_count=1, asset_bundle=None,
        joint_request=None, render_profile='none', render_quality='preview',
        render_device='CPU', gpu='', threads=4, window_scenery=None,
        door_physics_worker_config=None, stage_timeout_s=STAGE_TIMEOUT_S,
        rplan_seeds=os.environ.get(
            'RHG_RPLAN_SEEDS', str(SOURCE / 'configs/floorplans/rplan_production_16.json')),
        task_prompt=None, task_prompt_file=None, task_selection_response=None,
        task_selection_response_sha256=None)
    return runtime


def case_environment(case, *, gpu='', native=False):
    environment = adapter.runtime_environment(case, native=native)
    # Preserve the actual fused imports while isolating every writable user path.
    environment['PYTHONPATH'] = os.pathsep.join(str(ROOT / name) for name in (
        ('source', 'inputs/native_site', '') if native else
        ('runtime_site', 'supervisor_site', 'source', '')))
    environment.update(CUDA_VISIBLE_DEVICES=gpu, OMP_NUM_THREADS='4', NUMEXPR_NUM_THREADS='4')
    for key in list(environment):
        if key not in rhg_paths.ENVIRONMENT_KEYS and key not in ('RHG_DIGEST_CACHE', 'RHG_ROOM_SEARCH_BUDGETS',
                       'RHG_FLOOR_COVER_COLLISION_OMISSION', 'RHG_RECOVERY_MAX_ATTEMPTS',
                       'RHG_PENETRATION_TOLERANCE_M', 'RHG_COMPACT_KITCHEN') and key.startswith(('RHG_', 'OPENAI_', 'ASTRA_')):
            environment.pop(key)
    # Re-inject generation policy declared by the immutable case config after
    # clearing inherited state. Native execution otherwise cannot see explicit
    # collision mappings even though they are recorded in chain_config.json.
    config_path = Path(case) / 'chain_config.json'
    if config_path.is_file():
        config = adapter.load(config_path)
        mapping_path = config.get('collision_frame_mappings')
        if isinstance(mapping_path, str) and mapping_path:
            environment['RHG_COLLISION_FRAME_MAPPINGS'] = mapping_path
    # Restore only the explicitly paired SDK declarations for this case. This
    # function runs again at the native entry, after inherited RHG_* is cleared.
    runtime_path = Path(case) / 'runtime.json'
    receipt_path = Path(case) / 'runtime-prep.json'
    runtime = adapter.load(runtime_path) if runtime_path.is_file() else {}
    receipt = adapter.load(receipt_path) if receipt_path.is_file() else {}
    if not isinstance(runtime, dict) or not isinstance(receipt, dict):
        raise ValueError('MDL SDK runtime and receipt must be objects')
    # Performance-only option, explicitly restored after inherited RHG_* removal.
    # A runtime null is an explicit off switch even if the caller exports a path.
    attribute_cache = (runtime['attribute_index_cache_root']
        if 'attribute_index_cache_root' in runtime else os.environ.get('RHG_ATTRIBUTE_INDEX_CACHE'))
    if attribute_cache is not None:
        if not isinstance(attribute_cache,str) or not attribute_cache.strip():
            raise ValueError('attribute_index_cache_root must be a nonempty path string or null')
        cache_path = Path(attribute_cache).expanduser()
        if not cache_path.is_absolute():
            cache_path = SOURCE/cache_path
        environment['RHG_ATTRIBUTE_INDEX_CACHE'] = str(cache_path.resolve())
    declared_environment = receipt.get('environment', {})
    if not isinstance(declared_environment, dict):
        raise ValueError('MDL SDK receipt environment must be an object')
    from source.scripts.internal.scene_generation.real_assets.stage_checkpoint import (
        SUBPROCESS_TIMEOUT_DEFAULTS, subprocess_timeout)
    for name in SUBPROCESS_TIMEOUT_DEFAULTS:
        if name in os.environ or name in declared_environment:
            environment[name] = str(subprocess_timeout(name,
                {name: os.environ[name] if name in os.environ else declared_environment[name]}))
    sdk_keys = ('RHG_MDL_SDK_ROOT', 'RHG_MDL_SDK_PYTHON')
    runtime_pair = tuple(runtime.get(key) for key in ('mdl_sdk_root', 'mdl_sdk_python'))
    receipt_pair = tuple(declared_environment.get(key) for key in sdk_keys)
    if any(value is not None for value in (*runtime_pair, *receipt_pair)):
        if not all(isinstance(value, str) and value.strip()
                   for value in (*runtime_pair, *receipt_pair)):
            raise ValueError('MDL SDK root and Python require complete runtime and receipt pairs')
        if runtime_pair != receipt_pair:
            raise ValueError('MDL SDK runtime and receipt pairs differ')
        # These are declarations, not proof of SDK/source identity. Native
        # runtime signatures and source qualification still validate the bytes.
        environment.update(zip(sdk_keys, receipt_pair))
    return environment


@contextmanager
def environment_scope(environment):
    previous = dict(os.environ)
    try:
        os.environ.clear()
        os.environ.update(environment)
        yield
    finally:
        os.environ.clear()
        os.environ.update(previous)


def stage(root, name, command, timeout, environment):
    from process_control import execute_command
    root = Path(root)
    log = root / (name + '.log')
    with environment_scope(environment):
        receipt = execute_command([str(arg) for arg in command], ROOT, log, timeout)
    receipt['scope_passed'] = adapter.scope_passed(receipt, (0,))
    adapter.save(log.with_suffix('.receipt.json'), receipt)
    return receipt


def project_request(manifest, domains, *, semantic_key):
    """Project fresh poses/functions, retaining source-owned native dimensions."""
    entities = manifest['entities']
    ids = [row['entity_id'] for row in entities]
    rooms = {row['room_id'] for row in manifest['floor_plan']['rooms']}
    if not ids or len(ids) != len(set(ids)):
        raise ValueError('Fresh shell requires unique nonempty entities')
    definitions, furniture = [], []
    for entity in entities:
        identifier = entity['entity_id']
        if entity['room_id'] not in rooms:
            raise ValueError('Unknown fresh entity room: ' + identifier)
        for key in ('supported_by_entity_id', 'support_entity_id', 'front_target_entity_id'):
            if entity.get(key) and entity[key] not in ids:
                raise ValueError('Unknown fresh relation: ' + identifier + ':' + key)
        center, yaw, height = entity['center_xy_m'], entity['yaw_deg'], entity.get('base_z_m', 0.)
        if (len(center) != 2 or any(type(v) not in (int, float) or not math.isfinite(v)
                                   for v in [*center, yaw, height])):
            raise ValueError('Fresh entity has invalid pose: ' + identifier)
        candidates = sorted(set(domains.get(semantic_key(entity), [])))
        if not candidates or any(not isinstance(v, str) or not v for v in candidates):
            raise ValueError('No verified same-semantic candidate domain for ' + identifier)
        definition = {key: copy.deepcopy(entity[key]) for key in FUNCTION_FIELDS if key in entity}
        definition.update(preferred_center_xy_m=list(center), preferred_yaw_deg=yaw,
                          installation_height_m=height)
        definitions.append(definition)
        furniture.append(dict(entity_id=identifier, candidate_asset_ids=candidates))
    task_text = manifest.get('natural_language_task', manifest.get('task_text',
        'Generate the complete furnished house with all requested entities and functional relations.'))
    if not isinstance(task_text, str) or not task_text.strip():
        raise ValueError('Source natural language task must be nonempty text')
    request = dict(schema='rhg.scene_request.v1', mode='pool', task_kind='scene_generation',
        task_text=task_text,
        floor_plan_sha256=fingerprint(manifest['floor_plan']),
        entities=definitions, furniture=furniture)
    return project_with_semantic_preservation(manifest, request, semantic_key=semantic_key)


def chain_config(case):
    case = Path(case)
    return dict(schema='rhg.frontier-chain-config.v1',
        manifest=str(case / 'layout/fullhome_asset_v16_000/composition_manifest.runtime.json'),
        request=str(case / 'request.json'), max_attempts=2,
        generation=dict(runtime_template=str(case / 'runtime.json'),
            command=[SUPERVISOR, '-B', str(SCRIPT), 'native',
                '--source', '{source_root}', '--runtime', '{runtime}',
                '--request', '{request}', '--output', '{attempt_dir}/generated',
                '--isolation', str(case)],
            manifest_output='generated/fullhome_asset_v16_000/composition_manifest.runtime.json',
            timeout_s=GENERATION_TIMEOUT_S),
        geometry_validation=dict(enabled=True, blender=str(adapter.BLENDER), timeout_s=900),
        repair_execution=dict(enabled=True, max_attempts=2, total_timeout_s=REPAIR_TIMEOUT_S),
        collision_frame_mappings=str(ROOT / 'inputs/collision_frame_mappings_v1.json'),
        wholehouse={key: INTERIOR_RENDER_PROFILE[key] for key in ('width', 'height')})


def verify_hashes(hashes):
    for name, expected in hashes.items():
        path = Path(name)
        if not path.is_file() or adapter.digest(path) != expected:
            raise ValueError('Prepared input changed: ' + name)


def generation_interpreter(path):
    # Resolving this symlink bypasses the venv and loses its site-packages.
    return str(Path(path).absolute())


def prepare_command(case):
    return [SUPERVISOR, '-B', str(SCRIPT), '_prepare-case', '--case-root', str(case)]


def prepare_case(args):
    case = args.case_root.resolve()
    runtime = adapter.load(case / 'initial_runtime.json')
    sys.path[:0] = [str(CODE), str(SOURCE)]
    from stable_pipeline import child_environment
    from bind_fixed_layout import semantic_key, semantic_match, prepared_candidate
    from task_asset_selection import prepared_catalog
    environment = case_environment(case, native=True)
    with environment_scope(environment):
        environment.update(child_environment(runtime, case))
    environment.update(CUDA_VISIBLE_DEVICES='')
    env_file = case / 'no_external_api.env'
    env_file.write_text('RHG_USE_ASTRA_TASK_PLAN=0\nRHG_USE_ASTRA_LAYOUT_BRIEF=0\n'
                        'RHG_ENABLE_VLM_REVIEW=0\nRHG_REQUIRE_VLM_REVIEW=0\n')
    command = [runtime['python'], '-B', str(SOURCE / 'scripts/internal/scene_generation/'
        'run_rhg_v16_21p_procedural_pure_scene_generation.py'),
        '--out-root', runtime['baseline_root'], '--scene-count', '1',
        '--blender', runtime['blender'], '--skip-render', '--layout-shell',
        '--diagnostic-view-set', 'none', '--no-astra-cache', '--env-file', str(env_file)]
    receipt = stage(case, 'layout', command, 1800, environment)
    if not receipt['scope_passed']:
        raise RuntimeError('Fresh layout failed; see layout.log and layout.receipt.json')
    scene = case / 'layout/fullhome_asset_v16_000'
    required = ('composition_manifest.runtime.json', 'SceneManifest.v16.json',
                'blender_report.json', 'fullhome_asset_v16_000.blend')
    if not all((scene / name).is_file() for name in required):
        raise ValueError('Fresh layout did not produce a complete native shell')
    manifest = adapter.load(scene / required[0])
    prepared, pools = prepared_catalog(runtime)
    domains = {semantic_key(entity): [] for entity in manifest['entities']}
    for key in domains:
        domains[key] = sorted({candidate['asset_id'] for candidate in prepared.values()
                              if prepared_candidate(candidate) and semantic_match(key, candidate)})
    request, audit = project_request(manifest, domains, semantic_key=semantic_key)
    adapter.save(case / 'request.json', request)
    adapter.save(case / 'request_semantic_audit.json', audit)
    adapter.save(case / 'request_derivation.json', dict(
        policy='fresh_full_inventory_verified_prepared_same_semantic_domains',
        prepared_pools=pools, seed=runtime['seed'], source_manifest_sha256=adapter.digest(scene / required[0]),
        source_entity_count=len(manifest['entities']), old_scene_consumed=False))
    runtime['joint_request'] = str(case / 'request.json')
    adapter.save(case / 'runtime.json', runtime)
    adapter.save(case / 'chain_config.json', chain_config(case))
    paths = [p for p in scene.rglob('*') if p.is_file()]
    paths += [case / name for name in ('runtime.json', 'chain_config.json', 'request.json',
                                      'request_semantic_audit.json', 'request_derivation.json', 'usage.json')]
    for pool in pools:
        paths.extend((Path(pool['path']), Path(pool['path']).with_suffix('.receipt.json')))
    adapter.save(case / 'prepared.json', dict(seed=runtime['seed'], prepared=True,
        input_sha256={str(p): adapter.digest(p) for p in paths}, gpu_used=False,
        fresh_shell_generated=True, original_scene_reused=False))
    return 0


def prepare(args):
    output = args.output.resolve()
    if ROOT not in output.parents:
        raise ValueError('Preparation output must be inside this derivative workspace')
    template = adapter.load(args.runtime_template)
    for path in (Path(args.generation_python), Path(template.get('blender', adapter.BLENDER)),
                 SOURCE / 'configs/floorplans/rplan_production_16.json'):
        if not path.is_file():
            raise FileNotFoundError('Server prerequisite missing: ' + str(path))
    fresh_directory(output)
    manifest = dict(schema=SCHEMA, root=str(output), seeds=list(SEEDS), cases=[],
                    automatic_seed_retry=False, whole_task_acceptance=False)
    for seed in SEEDS:
        case = fresh_directory(output / ('case_' + str(seed)))
        runtime = case_runtime(template, case, seed)
        runtime['python'] = generation_interpreter(args.generation_python)
        runtime['blender'] = str(template.get('blender', adapter.BLENDER))
        adapter.save(case / 'initial_runtime.json', runtime)
        # A fresh ledger avoids carrying selection history between these cases.
        adapter.save(case / 'usage.json', dict(counts={}, scenes={}))
        row = dict(seed=seed, path=str(case), prepared=False)
        manifest['cases'].append(row)
        adapter.save(output / 'three_cases.json', manifest)
        print('Preparing fresh CPU shell seed=' + str(seed) + ' case=' + str(case), flush=True)
        try:
            receipt = stage(case, 'prepare', prepare_command(case),
                            args.timeout_s, case_environment(case))
            row['receipt'] = receipt
            if receipt['scope_passed'] and (case / 'prepared.json').is_file():
                row.update(adapter.load(case / 'prepared.json'))
        except Exception as error:
            row.update(error_type=type(error).__name__, error=str(error))
        adapter.save(output / 'three_cases.json', manifest)
    manifest['prepared'] = all(row['prepared'] for row in manifest['cases'])
    adapter.save(output / 'three_cases.json', manifest)
    print(json.dumps(manifest, indent=2), flush=True)
    return 0 if manifest['prepared'] else 1


def generated_scenes(case):
    scenes = []
    chain = Path(case) / 'execution/chain'
    manifests = [p for pattern in (
        'attempt_*/generated/fullhome_asset_v16_000/composition_manifest.runtime.json',
        'round_*/attempt_*/generated/fullhome_asset_v16_000/composition_manifest.runtime.json')
        for p in chain.glob(pattern)]
    for manifest in sorted(manifests):
        scene = manifest.parent
        if Path(case).resolve() not in scene.resolve().parents:
            raise ValueError('Generated scene escaped case directory')
        identifier = adapter.load(manifest).get('scene_id')
        if (isinstance(identifier, str) and Path(identifier).name == identifier
                and (scene / (identifier + '.blend')).is_file()):
            scenes.append(scene)
    return scenes


def validate_gpu_uuid(value):
    if value is not None and not re.fullmatch(
            r'GPU-[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', value):
        raise ValueError('--gpu-uuid must be a complete GPU UUID from nvidia-smi')
    return value


def execution_command(case):
    return [SUPERVISOR, '-B', str(ROOT / 'wholehouse_pipeline.py'),
            '--config', str(Path(case) / 'execution_config.json'),
            '--output', str(Path(case) / 'execution'), '--execute']


def write_execution_config(case):
    # Preparation may finish while this driver's execution support is updated.
    # Freeze current repair policy separately; prepared bytes remain immutable.
    case = Path(case)
    config = adapter.load(case / 'chain_config.json')
    config.update(max_attempts=2, repair_execution=dict(enabled=True, max_attempts=2,
                                                     total_timeout_s=REPAIR_TIMEOUT_S))
    config['wholehouse'] = dict(config.get('wholehouse', {}), **{
        key: INTERIOR_RENDER_PROFILE[key] for key in ('width', 'height')})
    path = case / 'execution_config.json'
    if path.exists():
        raise FileExistsError('Execution config already exists: ' + str(path))
    adapter.save(path, config)
    return path


def verify_render_files(output, evidence):
    output = Path(output).resolve()
    files = evidence.get('files_sha256')
    if not isinstance(files, dict) or not files:
        raise ValueError('Render evidence has no actual image/depth files')
    for relative, expected in files.items():
        path = (output / relative).resolve()
        if output not in path.parents or not path.is_file() or adapter.digest(path) != expected:
            raise ValueError('Rendered evidence file missing, escaped or changed: ' + str(relative))


def render_commands(case, *, gpu_uuid=None):
    validate_gpu_uuid(gpu_uuid)
    rows = []
    for index, scene in enumerate(generated_scenes(case), 1):
        output = Path(case) / 'diagnostic_render' / ('scene_%02d' % index)
        rows.append(dict(scene=str(scene), output=str(output),
            physical_qualified=False, whole_task_acceptance=False,
            command=[str(adapter.BLENDER), '--background', '--threads', '12' if gpu_uuid else '24',
                '--python-exit-code', '1', '--python', str(ROOT / 'real_test/render_wholehouse.py'),
                '--', '--scene', str(scene), '--output', str(output),
                '--device', 'GPU' if gpu_uuid else 'CPU', '--gpu-backend', 'CUDA',
                '--width', str(INTERIOR_RENDER_PROFILE['width']),
                '--height', str(INTERIOR_RENDER_PROFILE['height']),
                '--samples', str(INTERIOR_RENDER_PROFILE['samples']),
                '--time-budget-s', str(INTERIOR_RENDER_PROFILE['time_budget_s'])]))
    return rows


def case_diagnostics(case):
    case = Path(case)
    reports = {}
    names = ('result.json', 'native_scope.json', 'saved_blend_verification.json',
             'independent_saved_geometry.json', 'output_review.json',
             'binding_failure.json', 'failure_report.json', 'repair_plan.json',
             'wholehouse_audits.json', 'run_report.json')
    for path in sorted((case / 'execution').rglob('*.json')):
        if path.name in names:
            reports[str(path.relative_to(case))] = dict(path=str(path), sha256=adapter.digest(path))
    scenes = []
    for scene in generated_scenes(case):
        path = scene / 'composition_manifest.runtime.json'
        manifest = adapter.load(path)
        blend = scene / (manifest['scene_id'] + '.blend')
        scenes.append(dict(path=str(scene), manifest_sha256=adapter.digest(path),
            blend_sha256=adapter.digest(blend), entity_count=len(manifest.get('entities', [])),
            room_count=len(manifest.get('floor_plan', {}).get('rooms', []))))
    result_path = case / 'execution/result.json'
    result = adapter.load(result_path) if result_path.is_file() else {}
    return dict(seed=adapter.load(case / 'runtime.json')['seed'], scenes=scenes, reports=reports,
        status=result.get('status', 'execution_result_missing'),
        output_contract_passed=result.get('output_contract_passed') is True,
        geometry_current=result.get('geometry_current') is True,
        geometry_passed=result.get('geometry_passed') is True,
        wholehouse_evidence_complete=result.get('wholehouse_evidence_complete') is True,
        physical_qualified=False, whole_task_acceptance=False,
        diagnostic_render_does_not_override_acceptance=True)


def parser():
    result = argparse.ArgumentParser(description=__doc__)
    sub = result.add_subparsers(dest='mode', required=True)
    prep = sub.add_parser('prepare', help='Generate three NEW CPU shells and projected requests')
    prep.add_argument('--output', type=Path, required=True)
    prep.add_argument('--runtime-template', type=Path, default=ROOT / 'inputs/runtime_template_v2.json')
    prep.add_argument('--generation-python', type=Path, default=adapter.PYTHON)
    prep.add_argument('--timeout-s', type=float, default=2400)
    worker = sub.add_parser('_prepare-case', help=argparse.SUPPRESS)
    worker.add_argument('--case-root', type=Path, required=True)
    for mode in ('execute', 'render'):
        run = sub.add_parser(mode, help=mode + ' prepared cases; dry run unless --execute')
        run.add_argument('--prepared', type=Path, required=True)
        run.add_argument('--case', type=int, choices=SEEDS, action='append')
        run.add_argument('--execute', action='store_true')
        run.add_argument('--timeout-s', type=float,
            default=REPAIR_TIMEOUT_S+1200 if mode == 'execute' else INTERIOR_RENDER_PROFILE['time_budget_s']+900)
        if mode == 'render':
            run.add_argument('--gpu-uuid', help='Explicit GPU UUID; default is CPU rendering')
    native_parser = sub.add_parser('native', help='Internal isolated wrapper around fusion native adapter')
    for name in ('source', 'runtime', 'request', 'output', 'isolation'):
        native_parser.add_argument('--' + name, type=Path, required=True)
    return result


def main(argv=None):
    cli = parser()
    args = cli.parse_args(argv)
    if hasattr(args, 'timeout_s') and (not math.isfinite(args.timeout_s) or args.timeout_s <= 0):
        cli.error('--timeout-s must be positive and finite')
    if args.mode == 'prepare':
        return prepare(args)
    if args.mode == '_prepare-case':
        return prepare_case(args)
    if args.mode == 'native':
        # The adapter keeps its source/output guards, cache validation and exit-75 contract.
        isolated = case_environment(args.isolation, native=True)
        previous = adapter.runtime_environment
        adapter.runtime_environment = lambda *unused, **kwargs: isolated
        try:
            return adapter.native(args)
        finally:
            adapter.runtime_environment = previous
    return run_prepared(args)


def run_prepared(args):
    root = args.prepared.resolve()
    manifest = adapter.load(root / 'three_cases.json')
    if manifest.get('schema') != SCHEMA:
        raise ValueError('Not a three-case preparation manifest')
    if Path(manifest['root']).resolve() != root or [row['seed'] for row in manifest['cases']] != list(SEEDS):
        raise ValueError('Preparation must retain all three fixed seeds in their original root')
    rows = [row for row in manifest['cases'] if not args.case or row['seed'] in args.case]
    gpu = validate_gpu_uuid(getattr(args, 'gpu_uuid', None))
    plans = []
    for row in rows:
        case = Path(row['path']).resolve()
        if case.parent != root or SOURCE in case.parents:
            raise ValueError('Case directory escaped the prepared root')
        commands = ([dict(command=execution_command(case), output=str(case / 'execution'))]
                    if args.mode == 'execute' else render_commands(case, gpu_uuid=gpu))
        plans.append(dict(seed=row['seed'], case=str(case), prepared=row['prepared'], commands=commands))
    if not args.execute:
        print(json.dumps(dict(mode=args.mode, generation_started=False,
            cases=plans), indent=2))
        return 0
    # Refuse every reused destination before starting any selected case.
    for plan in plans:
        case = Path(plan['case'])
        if (case / (args.mode + '.log')).exists() or (case / (args.mode + '_result.json')).exists():
            raise FileExistsError('This phase already ran; preserve it: ' + str(case))
        for command in plan['commands']:
            if Path(command['output']).exists():
                raise FileExistsError('Refusing existing output: ' + command['output'])
        if args.mode == 'render' and (case / 'diagnostic_render').exists():
            raise FileExistsError('Diagnostic render already exists: ' + str(case))
    if args.mode == 'execute':
        from run_chain import base_identity
        identity = base_identity()
        if not identity['passed']:
            raise ValueError('Saved source inventory failed before execution: ' + str(identity))
    results = []
    for row, plan in zip(rows, plans):
        case = Path(plan['case'])
        result = dict(seed=row['seed'], case=str(case), phase=args.mode, passed=False,
                      physical_qualified=False, whole_task_acceptance=False, commands=[])
        try:
            if not row['prepared']:
                raise ValueError('Fresh shell preparation failed; see prepare.log')
            verify_hashes(row['input_sha256'])
            environment = case_environment(case, gpu=gpu or '')
            if args.mode == 'execute':
                config_path = write_execution_config(case)
                result['execution_config_sha256'] = adapter.digest(config_path)
                result['implementation_sha256'] = {str(path): adapter.digest(path) for path in (
                    SCRIPT, ROOT / 'wholehouse_pipeline.py', ROOT / 'repair_execution.py',
                    ROOT / 'run_chain.py', ROOT / 'real_test/run_server_house.py')}
                result['command'] = stage(case, 'execute', plan['commands'][0]['command'],
                                          args.timeout_s, environment)
                result.update(case_diagnostics(case))
                result['passed'] = (result['command']['scope_passed']
                    and result['wholehouse_evidence_complete'])
                result['render_commands'] = render_commands(case)
            else:
                if not plan['commands']:
                    raise ValueError('No fresh generated saved blend to render; shell renders are excluded')
                render_root = fresh_directory(case / 'diagnostic_render')
                for index, command in enumerate(plan['commands'], 1):
                    receipt = stage(render_root, 'render_%02d' % index, command['command'],
                                    args.timeout_s, environment)
                    evidence_path = Path(command['output']) / 'wholehouse_visibility_evidence.json'
                    command.update(receipt=receipt, evidence_path=str(evidence_path))
                    if evidence_path.is_file():
                        evidence = adapter.load(evidence_path)
                        scene = Path(command['scene'])
                        actual = adapter.load(scene / 'composition_manifest.runtime.json')
                        bound = (evidence.get('source_manifest_sha256') == adapter.digest(
                            scene / 'composition_manifest.runtime.json')
                            and evidence.get('source_sha256') == adapter.digest(scene / (actual['scene_id'] + '.blend')))
                        command.update(evidence_sha256=adapter.digest(evidence_path),
                            evidence_bound=bound, visibility_passed=evidence.get('passed') is True,
                            render_completed=evidence.get('render_completed') is True,
                            source_unchanged=evidence.get('source_unchanged') is True)
                        verify_render_files(command['output'], evidence)
                    result['commands'].append(command)
                    adapter.save(render_root / 'result.json', result)
                result['passed'] = all(command['receipt']['scope_passed']
                    and command.get('evidence_bound') and command.get('render_completed')
                    and command.get('source_unchanged') for command in result['commands'])
                result['gpu_uuid'] = gpu
                result['scope'] = 'diagnostic_render_execution_only_geometry_acceptance_unchanged'
                adapter.save(render_root / 'result.json', result)
            verify_hashes(row['input_sha256'])
        except Exception as error:
            result.update(passed=False, error_type=type(error).__name__, error=str(error))
        results.append(result)
        if args.mode == 'execute':
            adapter.save(case / 'case_diagnostics.json', result)
        elif (case / 'diagnostic_render').is_dir():
            adapter.save(case / 'diagnostic_render/result.json', result)
        adapter.save(case / (args.mode + '_result.json'), result)
        # Per-case results also support independent --case invocations without
        # sharing a mutable suite receipt between concurrent parent launches.
        print(json.dumps(result, indent=2), flush=True)
    return 0 if results and all(row['passed'] for row in results) else 1


if __name__ == '__main__':
    raise SystemExit(main())