"""Whole-house plans and evidence gates around the native generation chain.""" from __future__ import annotations import argparse import json import math from pathlib import Path if __package__: from .run_chain import BASE, contained, digest, execute_command, load, run_chain, save from .room_program import compile_room_program, evaluate_room_program from .material_plan import compile_material_plan, audit_material_plan from .visibility_plan import build_visibility_plan, audit_visibility else: from run_chain import BASE, contained, digest, execute_command, load, run_chain, save from room_program import compile_room_program, evaluate_room_program from material_plan import compile_material_plan, audit_material_plan from visibility_plan import build_visibility_plan, audit_visibility VERSION = 'v16.21p-wholehouse-repair-v2.5-20261024' def _missing(kind, plan=None): unknowns = [dict(code=kind + '_evidence_missing', message='Actual generated evidence is required')] if isinstance(plan, dict): for rid, detail in sorted((plan.get('room_visibility_degraded') or {}).items()): if isinstance(detail, dict): level = detail.get('level', '?') reason = detail.get('reason', 'camera planning degraded') else: level, reason = '?', str(detail) unknowns.append('room_visibility_degraded:%s:%s:%s' % (rid, level, reason)) return dict(passed=False, issues=[], warnings=[], unknowns=unknowns) def _failure_records(audits, result): records, seen = [], set() def append(stage, label, detail, fallback): detail = detail if isinstance(detail, dict) else {'code': str(detail)} identity = (stage, label, json.dumps(detail, sort_keys=True)) if identity in seen: return seen.add(identity) records.append(dict(stage=stage, label=label, failure_type=detail.get('code', fallback), detail=detail, generated_manifest_sha256=result.get('generated_manifest_sha256'), accepted_training_positive=False)) for stage, audit in audits.items(): for field in ('issues', 'errors', 'unknowns', 'pending'): for item in audit.get(field, []): append(stage, 'unknown' if field in ('unknowns', 'pending') else 'failure', item, stage + '_' + field) if result.get('error_type') or result.get('inputs_unchanged') is False: append('execution', 'failure', dict(code=result['status'], error_type=result.get('error_type'), message=result.get('error')), result['status']) native_status = result.get('native_status', '') if ('failed' in native_status or native_status in ('budget_exhausted', 'manual_review_required', 'total_timeout', 'candidate_domain_exhausted')): append('native', 'failure', dict(code=native_status), native_status) return records def _bound_load(path, inputs): path = Path(path).resolve() sha = digest(path) if str(path) in inputs and inputs[str(path)] != sha: raise ValueError('Bound evidence changed: ' + str(path)) value = load(path) if digest(path) != sha: raise ValueError('Evidence changed while reading: ' + str(path)) inputs[str(path)] = sha return value def _unchanged(inputs): try: return all(Path(path).is_file() and digest(path) == sha for path, sha in inputs.items()) except OSError: return False def _render_settings(settings): render = settings.get('render') if render is None: return None if (not isinstance(render, dict) or set(render) - {'command', 'timeout_s', 'evidence_output'} or not isinstance(render.get('command'), list) or not render['command'] or any(not isinstance(arg, str) or not arg for arg in render['command'])): raise ValueError('render requires an explicit argv command') timeout = render.get('timeout_s', 1800) if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0: raise ValueError('render timeout_s must be finite and positive') contained(BASE / 'render-placeholder', render.get('evidence_output', 'wholehouse_visibility_evidence.json')) return render def _audit_material_output(material, generated, structural, scene, generated_path, blend, inputs): # Furniture requirements apply to actual output even when suites are pinned. actual_plan = dict(material, furniture=generated.get('entities', [])) report = audit_material_plan(actual_plan, structural, scene) expected = {'source_manifest_sha256': digest(generated_path)} if blend.is_file(): expected['source_sha256'] = digest(blend) inputs[str(blend)] = expected['source_sha256'] native_bound = False reference = generated.get('structural_material_manifest') verification = scene / 'saved_blend_verification.json' if isinstance(reference, dict) and verification.is_file(): structural_path = contained(scene, reference.get('path')) # Reuse an actual native reopen receipt frozen by this generation run. if (inputs.get(str(verification)) == digest(verification) and structural_path.is_file() and digest(structural_path) == reference.get('sha256') and load(structural_path) == structural): readback = _bound_load(verification, inputs) native_bound = (readback.get('passed') is True and expected.get('source_sha256') is not None and readback.get('blend_sha256') == expected.get('source_sha256') and readback.get('scene_id') == generated.get('scene_id') and readback.get('entity_count') == len(generated.get('entities', []))) if native_bound: report['source_binding_scope'] = 'current_manifest_reference_and_frozen_native_saved_scene_readback' for key in ('source_manifest_sha256', 'source_sha256'): if key not in expected or structural.get(key) is None: if not native_bound: report['unknowns'].append(dict(code='material_saved_scene_binding_missing', location=key, blocking=True)) elif structural[key] != expected[key]: report['issues'].append(dict(code='material_saved_scene_binding_mismatch', location=key)) for check in report.get('dependency_checks', []): if check.get('matched'): dependency = Path(check['source_path']) if not dependency.is_absolute(): dependency = scene / dependency inputs[str(dependency.resolve())] = check['sha256'] report['passed'] = not report['issues'] and not any( row.get('blocking', True) for row in report['unknowns']) return report def _visibility_evidence(scene, output, settings, generated_path, views, inputs, execute): """Run an explicit renderer, or read current evidence without inventing it.""" render = _render_settings(settings) evidence_root = scene if render is not None: if not execute: return None timeout = render.get('timeout_s', 1800) evidence_root = output / 'render' tokens = {'{scene}': str(scene), '{manifest}': str(generated_path), '{plan}': str(output / 'visibility_plan.final.json'), '{evidence_dir}': str(evidence_root), '{source_root}': str(BASE / 'source')} command = list(render['command']) for token, value in tokens.items(): command = [arg.replace(token, value) for arg in command] for arg in command: script = Path(arg) if script.is_absolute() and script.suffix == '.py' and script.is_file(): inputs[str(script.resolve())] = digest(script) receipt = execute_command(command, BASE, output / 'render.log', timeout) save(output / 'render_command.json', receipt) if receipt['exit_code'] or receipt['timed_out'] or not receipt['cleanup']['complete']: raise ValueError('Render command failed; inspect render.log and render_command.json') relative = (render or {}).get('evidence_output', 'wholehouse_visibility_evidence.json') path = contained(evidence_root, relative) if not path.is_file(): return None evidence = _bound_load(path, inputs) if (evidence.get('source_manifest_sha256') != digest(generated_path) or evidence.get('source_sha256') != views.get('source_sha256')): raise ValueError('Visibility receipt does not bind this saved scene and manifest') files = evidence.get('files_sha256') if not isinstance(files, dict) or not files: raise ValueError('Visibility receipt requires actual rendered file hashes') for name, sha in files.items(): file = contained(evidence_root, name) if not file.is_file() or digest(file) != sha: raise ValueError('Rendered evidence bytes differ: ' + name) inputs[str(file)] = sha return evidence def run_wholehouse(config_path, output, *, execute=False): config_path, output = Path(config_path).resolve(), Path(output).resolve() if output == BASE or output == BASE / 'source' or BASE / 'source' in output.parents: raise ValueError('Run outputs must be outside the saved source tree') output.mkdir(parents=True, exist_ok=False) result = dict(schema='rhg.wholehouse-result.v1', version=VERSION, status='wholehouse_preflight_blocked', generation_executed=False, output_contract_passed=False, visual_qualified=False, visibility_passed=False, appearance_qualified=False, diagnostic_only=False, physical_qualified=False, whole_task_acceptance=False, model_training_executed=False, geometry_requested=False, geometry_disabled=False, geometry_current=False, geometry_passed=False) audits, inputs = {}, {} try: if __package__: from .run_chain import runtime_implementation_identity else: from run_chain import runtime_implementation_identity result['runtime_implementation'] = runtime_implementation_identity() for path in BASE.glob('*.py'): inputs[str(path)] = digest(path) config = _bound_load(config_path, inputs) if __package__: from .geometry_validation import settings as geometry_settings from .repair_execution import _absolute_config else: from geometry_validation import settings as geometry_settings from repair_execution import _absolute_config config = _absolute_config(config, config_path.parent) config.setdefault('geometry_validation', {'enabled': True}) options = geometry_settings(config) if config['geometry_validation'] is None: raise ValueError('geometry_validation must be an explicit settings object') result.update(geometry_requested=options is not None, geometry_disabled=options is None) native_config = output / 'effective_config.json' save(native_config, config) inputs[str(native_config)] = digest(native_config) manifest_path = (config_path.parent / config['manifest']).resolve() request_path = (config_path.parent / config['request']).resolve() manifest, request = _bound_load(manifest_path, inputs), _bound_load(request_path, inputs) settings = config.get('wholehouse', {}) if not isinstance(settings, dict): raise ValueError('wholehouse settings must be an object') if set(settings) - {'room_policy', 'material_policy', 'functional_policy', 'width', 'height', 'render'}: raise ValueError('Unsupported wholehouse settings') _render_settings(settings) repairs = config.get('repair_execution', {}) if not isinstance(repairs, dict): raise ValueError('repair_execution must be an object') program = compile_room_program(manifest, request, settings.get('room_policy')) material = compile_material_plan(manifest, settings.get('material_policy')) views = build_visibility_plan(manifest, width=settings.get('width', 960), height=settings.get('height', 540)) for name, value in (('room_program', program), ('material_plan', material), ('visibility_plan', views)): save(output / (name + '.json'), value) # Geometry measurements are post-generation gates; the program's hard # inventory/topology checks must already pass before an expensive run. if program.get('issues') or material.get('issues'): audits['room_preflight'] = program audits['material_preflight'] = material return result if repairs.get('enabled'): if __package__: from .repair_execution import execute_repairs else: from repair_execution import execute_repairs native = execute_repairs(native_config, output / 'chain', execute=execute) else: native = run_chain(native_config, output / 'chain', execute=execute) result.update(native_status=native['status'], generation_executed=native['generation_executed'], output_contract_passed=native['output_contract_passed'], status=native['status'], chain_result='chain/result.json') result.update(geometry_current=native.get('geometry_current', False), geometry_passed=native.get('geometry_passed', False)) if native.get('candidate_admission_failure'): result['candidate_admission_failure'] = native['candidate_admission_failure'] geometry = native.get('geometry_validation') if geometry: audits['geometry'] = dict(passed=geometry.get('geometry_passed') is True, issues=geometry.get('diagnostics', []), unknowns=[ dict(code=str(field)) for field in geometry.get('pending_fields', [])], acceptance_scope=geometry.get('acceptance_scope'), skipped_checks=geometry.get('skipped_checks', []), full_geometry_complete=geometry.get('full_geometry_complete', geometry.get('complete')), full_geometry_passed=geometry.get('full_geometry_passed', geometry.get('geometry_passed'))) result['geometry_acceptance_scope'] = audits['geometry']['acceptance_scope'] result['skipped_geometry_checks'] = audits['geometry']['skipped_checks'] result['full_geometry_complete'] = audits['geometry']['full_geometry_complete'] result['full_geometry_passed'] = audits['geometry']['full_geometry_passed'] for path, sha in native.get('input_sha256', {}).items(): if path in inputs and inputs[path] != sha: raise ValueError('Native chain rebound an existing input: ' + path) inputs[path] = sha diagnostic_ready = (native.get('generation_executed') is True and native.get('native_contract_passed') is True and native.get('inputs_unchanged') is True and bool(native.get('generated_manifest'))) if native['output_contract_passed'] or diagnostic_ready: result['diagnostic_only'] = not native['output_contract_passed'] generated_path = Path(native['generated_manifest']).resolve() if output not in generated_path.parents: raise ValueError('Generated manifest escaped this run') generated = _bound_load(generated_path, inputs) result['generated_manifest'] = str(generated_path) result['generated_manifest_sha256'] = digest(generated_path) scene = generated_path.parent effective_path = scene / 'eligible_scene_request.json' if effective_path.is_file(): # The native chain has already verified sealed records and pins. expected = native.get('input_sha256', {}).get(str(effective_path)) if not expected or digest(effective_path) != expected: raise ValueError('Effective request lost its native contract binding') effective = _bound_load(effective_path, inputs) program = compile_room_program(manifest, effective, settings.get('room_policy')) save(output / 'room_program.effective.json', program) audits['room'] = evaluate_room_program(generated, program, geometry_evidence=native.get('geometry_validation')) if native.get('native_contract_passed') is True: room = audits['room'] room['unknowns'] = [row for row in room.get('unknowns', []) if row.get('code') != 'native_candidate_evidence_unknown'] room['native_contract_scope'] = 'sealed_source_bytes_dimensions_and_pins_verified_by_chain' room['passed'] = not room.get('issues') and not room['unknowns'] blend = contained(scene, str(generated.get('scene_id', '')) + '.blend') structural_path = scene / 'structural_material_manifest.json' if structural_path.is_file(): structural = _bound_load(structural_path, inputs) if not material.get('selected_suites'): material = compile_material_plan(dict(generated, structural_materials=structural), settings.get('material_policy')) material = dict(material, furniture=generated.get('entities', [])) save(output / 'material_plan.final.json', material) audits['material'] = _audit_material_output(material, generated, structural, scene, generated_path, blend, inputs) else: audits['material'] = _missing('material') measured = dict(generated) if blend.is_file(): measured['source_sha256'] = digest(blend) inputs[str(blend)] = measured['source_sha256'] else: measured.pop('source_sha256', None) measured.pop('blend_sha256', None) measured['source_manifest_sha256'] = digest(generated_path) final_views = build_visibility_plan(measured, width=settings.get('width', 960), height=settings.get('height', 540)) save(output / 'visibility_plan.final.json', final_views) evidence = _visibility_evidence(scene, output, settings, generated_path, final_views, inputs, execute) audits['visibility'] = (audit_visibility(final_views, evidence) if evidence is not None else _missing('visibility', final_views)) failures = any(audit.get('issues') or audit.get('errors') for audit in audits.values()) complete = (native['output_contract_passed'] and all(audit.get('passed') is True for audit in audits.values()) and native['status'] in ('generation_completed_pending_native_validation', 'generation_completed_geometry_verified')) result['visibility_passed'] = audits['visibility'].get('passed') is True # Coverage alone cannot certify material/lighting appearance fidelity. result['visual_qualified'] = False result['wholehouse_evidence_complete'] = complete result['status'] = ('wholehouse_audit_failed' if failures else 'wholehouse_evidence_verified_pending_native_physics' if complete else native['status'] if result['diagnostic_only'] else 'generation_completed_pending_wholehouse_evidence') except (ValueError, OSError, KeyError, TypeError) as error: result.update(error_type=type(error).__name__, error=str(error)) if result['generation_executed']: result['status'] = 'wholehouse_audit_failed' finally: result['inputs_unchanged'] = _unchanged(inputs) if not result['inputs_unchanged']: result['status'] = 'input_integrity_failed' result['output_contract_passed'] = False result['visual_qualified'] = False result['visibility_passed'] = False result['wholehouse_evidence_complete'] = False result['geometry_current'] = False result['geometry_passed'] = False save(output / 'wholehouse_audits.json', audits) save(output / 'training_trace.json', dict( schema='rhg.wholehouse-training-trace.v1', scope='evidence_export_only_no_model_training', accepted_training_positive=False, source_inputs_sha256=inputs, result_status=result['status'], audits=audits, failure_records=_failure_records(audits, result), repair_trace='chain/result.json', qualification=dict(visibility_passed=result['visibility_passed'], appearance_qualified=False, geometry_passed=result['geometry_passed']), physical_qualified=False, whole_task_acceptance=False)) save(output / 'result.json', result) return result def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--execute', action='store_true') args = parser.parse_args(argv) result = run_wholehouse(args.config, args.output, execute=args.execute) print(json.dumps(result, sort_keys=True)) return 0 if result['status'] == 'preflight_complete' or result.get('wholehouse_evidence_complete') else 1 if __name__ == '__main__': raise SystemExit(main())