"""Opt-in geometry review and bounded generation on the separately saved source.""" from __future__ import annotations import argparse import hashlib import json import math from pathlib import Path import shutil import sys BASE = Path(__file__).resolve().parent VERSION = 'v16.21p-wholehouse-repair-v2.5-20261024' def runtime_implementation_identity(): if __package__: from . import geometry_validation from .runtime_identity import implementation_identity else: import geometry_validation from runtime_identity import implementation_identity return implementation_identity(BASE, geometry_validation) def digest(path): sha = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): sha.update(block) return sha.hexdigest() def load(path): value = json.loads(Path(path).read_text(encoding='utf-8')) json.dumps(value, allow_nan=False) if not isinstance(value, dict): raise ValueError('Expected a JSON object: ' + str(path)) return value def save(path, value): path = Path(path) temporary = path.with_suffix(path.suffix + '.tmp') temporary.write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + '\n', encoding='utf-8') temporary.replace(path) def base_identity(): inventory = BASE / 'BASE_SHA256SUMS' mismatches = [] count = 0 for line in inventory.read_text().splitlines(): expected, name = line.split(' ', 1) path = BASE / name if not path.is_file() or digest(path) != expected: mismatches.append(name) count += 1 return dict(files=count, passed=not mismatches, mismatches=mismatches, inventory_sha256=digest(inventory)) def entities(manifest): rows = manifest['entities'] if not isinstance(rows, list) or not rows: raise ValueError('Require the complete nonempty scene inventory') ids = [e['entity_id'] for e in rows] if (any(not isinstance(eid, str) or not eid for eid in ids) or len(ids) != len(set(ids))): raise ValueError('Require unique nonempty entity IDs') if not isinstance(manifest.get('floor_plan'), dict): raise ValueError('Require an explicit floor plan') return {e['entity_id']: e for e in rows} def validate_request(manifest, request): known = entities(manifest) rows = request['furniture'] ids = [row['entity_id'] for row in rows] if len(ids) != len(set(ids)) or set(ids) != set(known): raise ValueError('Request must preserve the full entity inventory') if request.get('mode') not in ('pool', 'locked'): raise ValueError('Require pool or locked request mode') for row in rows: domain = ([row.get('asset_id')] if request['mode'] == 'locked' else row.get('candidate_asset_ids')) if (not isinstance(domain, list) or not domain or any(not isinstance(item, str) or not item for item in domain) or len(domain) != len(set(domain))): raise ValueError('Invalid native asset domain: ' + row['entity_id']) if 'record_id' in row and (not isinstance(row['record_id'], str) or not row['record_id']): raise ValueError('record_id must be a nonempty string') if 'candidate_record_ids' in row: records = row['candidate_record_ids'] if (not isinstance(records, list) or not records or any(not isinstance(value, str) or not value for value in records)): raise ValueError('candidate_record_ids must be a nonempty string list') def floor_range_released_support(original, actual, key): """Only a cooking appliance that the binder turned into a floor-standing range may drop its counter parent: it must name that very counter as floor_range_counter_id, stand on the floor, and nothing else about its parentage may have changed.""" return (key in ('supported_by_entity_id', 'support_entity_id') and original.get(key) is not None and actual.get(key) is None and actual.get('cooking_appliance_mode') == 'floor_range' and actual.get('floor_range_counter_id') == original.get(key) and abs(actual.get('base_z_m', 1.)) <= .005) def output_diagnostics(before, after, request, candidates=None, inputs=None, *, allow_derived_support=False): old, new = entities(before), entities(after) problems = [] def problem(code, ids, message): problems.append(dict(code=code, entity_ids=ids, message=message)) if set(old) != set(new): problem('entity_inventory_changed', [], 'Required entity inventory changed') return problems if before['floor_plan'] != after['floor_plan']: problem('floor_plan_changed', [], 'Immutable floor plan changed') for key in ('task_kind', 'task_text'): if key in before and before[key] != after.get(key): problem('task_contract_changed', [], key + ' changed') requirements = {row['entity_id']: row for row in request['furniture']} for eid, original in old.items(): actual = new[eid] derived_support_verified = False if actual.get('derived_support_relation') is not None: if __package__: from .support_contract import authored_support_parent else: from support_contract import authored_support_parent try: derived_support_verified = authored_support_parent( actual, new, inputs=inputs, verify_evidence=True) is None except (ValueError, OSError, TypeError, KeyError) as error: problem('derived_support_unverified', [eid], str(error)) elif (original.get('derived_support_relation') is not None and actual.get('support_entity_id') is not None): problem('derived_support_unverified', [eid], 'Existing rug support lost its derivation provenance') for key in ('room_id', 'role', 'supported_by_entity_id', 'support_entity_id', 'parent_entity_id'): if original.get(key) != actual.get(key): if floor_range_released_support(original, actual, key): continue if (allow_derived_support and key == 'support_entity_id' and not any(original.get(k) for k in ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id')) and derived_support_verified): continue problem('entity_contract_changed', [eid], key + ' changed') requirement = requirements[eid] domain = ([requirement['asset_id']] if request['mode'] == 'locked' else requirement['candidate_asset_ids']) if actual.get('asset_id') not in domain: problem('asset_outside_domain', [eid], 'Selected source is outside the native asset domain') if candidates and actual.get('asset_id') in candidates: if __package__: from .native_contract import check_candidate else: from native_contract import check_candidate allowed = candidates[actual['asset_id']] if requirement.get('record_id'): allowed = [row for row in allowed if row.get('pool_candidate_key') == requirement['record_id']] if requirement.get('candidate_record_ids'): allowed = [row for row in allowed if row.get('pool_candidate_key') in requirement['candidate_record_ids']] if actual.get('pool_candidate_key'): allowed = [row for row in allowed if row.get('pool_candidate_key') == actual['pool_candidate_key']] if requirement.get('source_sha256'): allowed = [row for row in allowed if row.get('asset_sha256') == requirement['source_sha256']] errors, sources = check_candidate(actual, allowed) problems.extend(errors) if inputs is not None: inputs.update(sources) elif original.get('asset_id') == actual.get('asset_id'): if (requirement.get('source_sha256') and actual.get('asset_sha256') != requirement['source_sha256']): problem('native_source_pin_mismatch', [eid], 'Selected source differs from the explicit source pin') key = actual.get('pool_candidate_key') if (requirement.get('record_id') and key != requirement['record_id'] or requirement.get('candidate_record_ids') and key not in requirement['candidate_record_ids']): problem('native_record_unverified', [eid], 'Selected candidate record is outside the requested records') for key in ('dimensions_m', 'source_dimensions_m', 'asset_sha256', 'source_sha256', 'runtime_sha256', 'canonical_transform', 'canonical_path', 'runtime_path', 'scale', 'uniform_scale'): if original.get(key) != actual.get(key): problem('native_source_changed', [eid], key + ' changed for the same source asset') else: problem('replacement_native_contract_unverified', [eid], 'Replacement requires a sealed prepared candidate pool for native size/source checks') return problems def bind_baseline_sources(manifest, inputs): for entity in manifest['entities']: for path_key, hash_key in (('canonical_path', 'asset_sha256'), ('runtime_path', 'runtime_sha256')): if entity.get(path_key): path = Path(entity[path_key]) if not path.is_absolute() or not path.is_file() or digest(path) != entity.get(hash_key): raise ValueError('Baseline source bytes differ from the declared source identity') inputs[str(path.resolve())] = entity[hash_key] def review(manifest, config): if __package__: from .task_precheck import evaluate_task from .spatial_priors import evaluate_priors else: from task_precheck import evaluate_task from spatial_priors import evaluate_priors task = evaluate_task(manifest, config.get('task')) priors = evaluate_priors(manifest, config.get('priors')) return dict(task=task, priors=priors, passed=all(row['status'] in ('not_requested', 'geometry_feasible') for row in (task, priors)), diagnostics=[item for row in (task, priors) if row['status'] not in ('not_requested', 'geometry_feasible') for item in row['diagnostics']]) def repair(manifest, request, diagnostics, config): if __package__: from .feedback import plan_repair else: from feedback import plan_repair return plan_repair(manifest, request, diagnostics, attempt_index=config.get('attempt_index', 1), max_attempts=config.get('max_attempts', 3)) def save_repair(output, manifest, request, diagnostics, config): plan = repair(manifest, request, diagnostics, config) save(output / 'repair_plan.json', plan) if plan['next_request'] is not None: save(output / 'next_request.json', plan['next_request']) def contained(root, relative): root = Path(root).resolve() if not isinstance(relative, str) or not relative: raise ValueError('Require a relative output manifest path') path = (root / relative).resolve() if path == root or root not in path.parents: raise ValueError('Generated output must stay inside its new attempt') return path def measured_diagnostics(attempt, relative, generated_path, manifest, inputs): """Accept structured failures only from a receipt bound to this output.""" path = contained(attempt, relative) sha = digest(path) receipt = load(path) if (digest(path) != sha or receipt.get('source_manifest_sha256') != digest(generated_path)): raise ValueError('Measured diagnostics do not bind this generated manifest') rows = receipt.get('diagnostics') known = entities(manifest) if not isinstance(rows, list): raise ValueError('Measured diagnostics must be a list') for row in rows: if (not isinstance(row, dict) or not isinstance(row.get('code'), str) or not row['code'].strip() or not isinstance(row.get('message'), str) or not isinstance(row.get('entity_ids'), list) or any(not isinstance(eid, str) or eid not in known for eid in row['entity_ids']) or len(row['entity_ids']) != len(set(row['entity_ids']))): raise ValueError('Invalid structured measured diagnostic') inputs[str(path)] = sha return rows def bind_runtime_geometry(runtime, inputs): """Freeze native measurement indices before the generator can consume them.""" for key in ('prepared_support_surfaces', 'prepared_floor_body_geometry'): if not runtime.get(key): continue path = Path(runtime[key]) if not path.is_absolute(): path = BASE / 'source' / path path = path.resolve() runtime[key] = str(path) sha = digest(path) data = load(path) if digest(path) != sha: raise ValueError('Runtime geometry index changed while reading') inputs[str(path)] = sha if key == 'prepared_support_surfaces': for row in data.get('sources', []): source = Path(row['path']) if not source.is_absolute(): source = path.parent / source source = source.resolve() if not source.is_file() or digest(source) != row['sha256']: raise ValueError('Prepared support surface differs from its source hash') inputs[str(source)] = row['sha256'] def execute_command(command, cwd, log_path, timeout): if __package__: from .process_control import execute_command as bounded_command else: from process_control import execute_command as bounded_command return bounded_command(command, cwd, log_path, timeout) def candidate_admission_failure(attempt, generation, frozen_request, inputs): path = contained(attempt, generation['manifest_output']).parent / 'candidate_eligibility_report.json' if not path.is_file(): return None sha = digest(path) report = load(path) if digest(path) != sha: raise ValueError('Candidate admission report changed while reading') empty = report.get('empty_roles_after_full_prepared_pool') if (report.get('schema') != 'rhg.eligible_candidate_request.v1' or report.get('passed') is not False or not isinstance(empty, list) or not empty or any(not isinstance(eid, str) or not eid for eid in empty) or Path(report.get('input_request', '')).resolve() != Path(frozen_request).resolve() or report.get('input_request_sha256') != digest(frozen_request)): return None requested = {row['entity_id'] for row in load(frozen_request)['furniture']} rows = report.get('entities', []) if not set(empty) <= requested or not set(empty) <= {row.get('entity_id') for row in rows}: return None for pool in report.get('prepared_pools', []): name = str(Path(pool['path']).resolve()) if inputs.get(name) != pool.get('sha256'): return None inputs[str(path.resolve())] = sha return dict(status='candidate_domain_exhausted', report_path=str(path.resolve()), report_sha256=sha, entity_ids=empty, domains=rows, all_entity_domains_evaluated=report.get('all_entity_domains_evaluated', True), unchecked_entity_ids=report.get('unchecked_entity_ids', []), next_action='supply_qualified_assets', placement_retry_applicable=False) def run_chain(config_path, output, *, execute=False): config_path, output = Path(config_path).resolve(), Path(output).resolve() if output == BASE or BASE / 'source' == output 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.frontier-chain-result.v1', version=VERSION, status='configuration_failed', generation_executed=False, output_contract_passed=False, physical_qualified=False, native_preflight_queried=False, whole_task_acceptance=False, automatic_retry=False, automatic_seed_replacement=False) inputs = {} pool_journals = [] config = None try: result['runtime_implementation'] = runtime_implementation_identity() implementations = [*BASE.glob('*.py'), BASE / 'source/scripts/run_frontier_generation.py'] result['implementation_sha256'] = {str(path.relative_to(BASE)): digest(path) for path in implementations} inputs.update({str(path): digest(path) for path in implementations}) config = load(config_path) if __package__: from .geometry_validation import settings as geometry_settings, validate_generated_scene, evidence_current else: from geometry_validation import settings as geometry_settings, validate_generated_scene, evidence_current geometry_options = geometry_settings(config) result.update(geometry_requested=geometry_options is not None, geometry_current=False, geometry_passed=False, geometry_provenance_current=False, geometry_complete=False) if config.get('schema') != 'rhg.frontier-chain-config.v1': raise ValueError('Unsupported frontier chain config schema') manifest_path = (config_path.parent / config['manifest']).resolve() request_path = (config_path.parent / config['request']).resolve() for path in (config_path, manifest_path, request_path): inputs[str(path)] = digest(path) manifest, request = load(manifest_path), load(request_path) if __package__: from .search_bridge import compile_search_request, compile_search_runtime else: from search_bridge import compile_search_request, compile_search_runtime request = compile_search_request(request, config, manifest) validate_request(manifest, request) candidates = {} pool_paths = config.get('prepared_pools', []) if not isinstance(pool_paths, list) or any(not isinstance(p, str) or not p for p in pool_paths): raise ValueError('prepared_pools must be a list of sealed pool paths') pool_paths = [(config_path.parent / p).resolve() for p in pool_paths] template = None if (config.get('generation') or {}).get('runtime_template'): template_path = (config_path.parent / config['generation']['runtime_template']).resolve() inputs[str(template_path)] = digest(template_path) template = load(template_path) bind_runtime_geometry(template, inputs) for key in ('prepared_asset_pool', 'supplemental_prepared_pool'): if template.get(key): path = Path(template[key]) pool_paths.append(path if path.is_absolute() else BASE / 'source' / path) if pool_paths: pool_journals = [Path(str(path.resolve()) + suffix) for path in pool_paths for suffix in ('-wal', '-journal')] if __package__: from .native_contract import load_pools else: from native_contract import load_pools requested_ids = {asset for row in request['furniture'] for asset in ([row['asset_id']] if request['mode'] == 'locked' else row['candidate_asset_ids'])} candidates, hashes = load_pools(pool_paths, requested_ids) inputs.update(hashes) preservation_plan = None if config.get('preservation_plan'): if __package__: from .feedback import verify_preservation else: from feedback import verify_preservation plan_path = (config_path.parent / config['preservation_plan']).resolve() inputs[str(plan_path)] = digest(plan_path) preservation_plan = load(plan_path) if not verify_preservation(manifest, manifest, preservation_plan)['passed']: raise ValueError('Preservation plan does not match this input manifest') if (preservation_plan.get('next_request') is not None and preservation_plan['next_request'] != request): raise ValueError('Request differs from the planned new attempt') if preservation_plan.get('next_attempt_index') is not None: next_index = preservation_plan['next_attempt_index'] if config.get('attempt_index', next_index) != next_index: raise ValueError('Attempt index differs from the bound preservation plan') config = dict(config, attempt_index=next_index, max_attempts=preservation_plan['max_attempts']) result['base_identity'] = base_identity() if not result['base_identity']['passed']: raise ValueError('Saved latest source no longer matches its baseline inventory') if ((config.get('task') or config.get('priors')) and config.get('evidence_manifest_sha256') != digest(manifest_path)): raise ValueError('Measured task/prior evidence must bind the exact input manifest SHA256') checked = review(manifest, config) save(output / 'preflight.json', checked) save(output / 'input_sha256.json', inputs) save_repair(output, manifest, request, checked['diagnostics'], config) repairable_preflight = (preservation_plan is not None and preservation_plan.get('status') == 'repair_planned' and all(row['status'] in ('not_requested', 'geometry_feasible', 'geometry_rejected') for row in (checked['task'], checked['priors']))) if not checked['passed'] and not repairable_preflight: result['status'] = 'preflight_blocked' elif not execute: result['status'] = 'preflight_complete' else: generation = config['generation'] bind_baseline_sources(manifest, inputs) timeout = generation.get('timeout_s', 7200) if (type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0): raise ValueError('Require a finite positive timeout_s') command = generation['command'] if (not isinstance(command, list) or not command or any(not isinstance(arg, str) or not arg for arg in command)): raise ValueError('Generation command must be a nonempty argv array') attempt = output / 'attempt_01' attempt.mkdir() generated_path = contained(attempt, generation['manifest_output']) frozen_request = attempt / 'request.json' save(frozen_request, request) inputs[str(frozen_request)] = digest(frozen_request) runtime_path = attempt / 'runtime.json' runtime = None if generation.get('runtime_template'): runtime = compile_search_runtime(template, config) for key, relative in dict(out_root='generated', jobs_root='jobs', cache_root='cache', usage_ledger='usage.json', mdl_bake_cache='mdl-cache', cuda_kernel_cache_root='cuda-cache').items(): runtime[key] = str(attempt / relative) runtime['baseline_root'] = None if template.get('baseline_root'): original_layout = Path(template['baseline_root']) if not original_layout.is_absolute(): original_layout = BASE / 'source' / original_layout scene_count = template.get('scene_count', 1) if type(scene_count) is not int or scene_count < 1: raise ValueError('Require a positive integer scene_count') for index in range(scene_count): scene_id = 'fullhome_asset_v16_%03d' % index source_scene = original_layout / scene_id required = ('composition_manifest.runtime.json', 'SceneManifest.v16.json', 'blender_report.json', scene_id + '.blend') if not all((source_scene / name).is_file() for name in required): raise ValueError('Declared precomputed layout is incomplete') source_files = [p for p in source_scene.rglob('*') if p.is_file()] for path in source_files: inputs[str(path.resolve())] = digest(path) destination = attempt / 'layout' / scene_id shutil.copytree(source_scene, destination) for path in source_files: copied = destination / path.relative_to(source_scene) if digest(copied) != inputs[str(path.resolve())]: raise ValueError('Precomputed layout changed while copying') inputs[str(copied.resolve())] = inputs[str(path.resolve())] runtime['baseline_root'] = str(attempt / 'layout') runtime['joint_request'] = str(frozen_request) runtime['gpu'] = '' runtime['render_profile'] = 'none' runtime['render_device'] = 'CPU' prior_usage = template.get('usage_ledger') if prior_usage: ledger_path = Path(prior_usage) if not ledger_path.is_absolute(): ledger_path = BASE / 'source' / ledger_path inputs[str(ledger_path)] = digest(ledger_path) save(attempt / 'usage.json', load(ledger_path)) save(runtime_path, runtime) inputs[str(runtime_path)] = digest(runtime_path) replacements = {'{attempt_dir}': str(attempt), '{request}': str(frozen_request), '{manifest}': str(manifest_path), '{source_root}': str(BASE / 'source'), '{runtime}': str(runtime_path)} for token, value in replacements.items(): command = [arg.replace(token, value) for arg in command] cwd = (config_path.parent / generation['cwd']).resolve() if generation.get('cwd') else BASE / 'source' if not cwd.is_dir(): raise ValueError('Generation working directory is unavailable') result['generation_executed'] = True result['status'] = 'generation_failed' save(output / 'input_sha256.json', inputs) save(output / 'result.json', result) result['command'] = execute_command(command, cwd, attempt / 'generation.log', timeout) save(attempt / 'command.json', result['command']) if (result['command']['exit_code'] or result['command']['timed_out'] or not result['command']['cleanup']['complete']): failure = (candidate_admission_failure(attempt, generation, frozen_request, inputs) if not result['command']['timed_out'] and result['command']['cleanup']['complete'] else None) if failure is not None: result.update(status=failure['status'], candidate_admission_failure=failure) diagnostics = [dict(code=failure['status'], entity_ids=failure['entity_ids'], message='No qualified candidate remains; see the bound candidate admission report')] else: diagnostics = [dict(code='generation_command_failed', entity_ids=[], message='See original generation.log and command.json')] save_repair(output, manifest, request, diagnostics, config) else: result['status'] = 'output_contract_failed' generated_path = contained(attempt, generation['manifest_output']) generated_sha = digest(generated_path) generated = load(generated_path) if digest(generated_path) != generated_sha: raise ValueError('Generated manifest changed while reading') inputs[str(generated_path)] = generated_sha result['generated_manifest'] = str(generated_path) result['output_manifest_sha256'] = generated_sha artifacts = {str(generated_path): generated_sha} if generated.get('scene_id'): blend = contained(generated_path.parent, str(generated['scene_id']) + '.blend') if blend.is_file(): artifacts[str(blend)] = digest(blend) inputs[str(blend)] = artifacts[str(blend)] for name in ('saved_blend_verification.json', 'real_asset_import_audit.json'): receipt = generated_path.parent / name if receipt.is_file(): artifacts[str(receipt)] = digest(receipt) inputs[str(receipt)] = artifacts[str(receipt)] result['output_artifacts_sha256'] = artifacts if __package__: from .effective_contract import verified_effective_request else: from effective_contract import verified_effective_request effective, effective_candidates, effective_audit = verified_effective_request( manifest, request, frozen_request, generated_path, pool_paths, inputs, runtime) if effective_audit is not None: candidates = effective_candidates save(attempt / 'effective_request_review.json', effective_audit) diagnostics = output_diagnostics(manifest, generated, effective, candidates, inputs, allow_derived_support=geometry_options is not None) search_report = generated_path.parent / 'joint_search_report.json' result['preservation_enforced'] = False if effective.get('search_constraints') and search_report.is_file(): report = load(search_report) inputs[str(search_report)] = digest(search_report) evidence = report.get('search_constraints', {}) bound_requests = {digest(frozen_request)} eligible_path = generated_path.parent / 'eligible_scene_request.json' if effective_audit is not None: bound_requests.add(digest(eligible_path)) expected_fixed = sorted(row['entity_id'] for row in effective['search_constraints'].get('fixed_entities', [])) if (report.get('passed') is not True or evidence.get('enforced') is not True or report.get('request_sha256') not in bound_requests or sorted(evidence.get('fixed_entity_ids', [])) != expected_fixed): diagnostics.append(dict(code='search_enforcement_unverified', entity_ids=[], message='Native search evidence differs from this request')) else: result['preservation_enforced'] = bool(expected_fixed) result['search_constraints_enforced'] = True elif (effective.get('search_constraints') and generation.get('native_search_required', generation.get('runtime_template') is not None)): diagnostics.append(dict(code='search_enforcement_missing', entity_ids=[], message='This native run requires solver enforcement evidence')) if preservation_plan is not None: preserved = verify_preservation(manifest, generated, preservation_plan, defer_geometry=geometry_options is not None) save(attempt / 'preservation_review.json', preserved) diagnostics.extend(preserved['errors']) result['native_contract_passed'] = not diagnostics if result['native_contract_passed'] and geometry_options is not None: geometry = validate_generated_scene(config, generated_path, attempt / 'geometry', timeout_s=timeout) result['geometry_validation'] = geometry for path, sha in geometry['input_sha256'].items(): if path in inputs and inputs[path] != sha: raise ValueError('Saved geometry rebound an existing input: ' + path) inputs[path] = sha inputs[geometry['result_path']] = digest(geometry['result_path']) result['geometry_provenance_current'] = ( evidence_current(generated, geometry) and geometry.get('manifest_sha256') == generated_sha) result['geometry_complete'] = geometry.get('complete') is True result['geometry_current'] = (result['geometry_provenance_current'] and geometry['status'] == 'measured' and result['geometry_complete']) result['geometry_passed'] = (result['geometry_current'] and geometry.get('geometry_passed') is True and not geometry['diagnostics']) if result['geometry_provenance_current']: diagnostics.extend(geometry['diagnostics']) if preservation_plan is not None: preserved = verify_preservation(manifest, generated, preservation_plan, geometry_evidence=geometry) save(attempt / 'preservation_review.json', preserved) diagnostics.extend(preserved['errors']) result['native_contract_passed'] = preserved['passed'] elif geometry['status'] == 'failed': diagnostics.append(dict(code='saved_geometry_measurement_failed', entity_ids=[], message=geometry.get('error', 'Saved geometry validation failed'))) elif geometry.get('diagnostics') or geometry['status'] == 'measured': diagnostics.append(dict(code='saved_geometry_evidence_unverified', entity_ids=[], message='Saved geometry provenance does not bind this output')) if not diagnostics and generation.get('diagnostics_output'): diagnostics.extend(measured_diagnostics(attempt, generation['diagnostics_output'], generated_path, generated, inputs)) refreshed = None if (result['native_contract_passed'] and (config.get('task') or config.get('priors')) and config.get('measurement_refresh')): if __package__: from .measurement_refresh import refresh_measurements else: from measurement_refresh import refresh_measurements refreshed = refresh_measurements(config, generated_path, attempt / 'measurement', source_root=BASE / 'source', timeout_s=timeout) save(attempt / 'measurement_refresh.json', refreshed) result['measurement_refresh'] = refreshed refreshed_files = dict(refreshed.get('input_sha256', {})) refreshed_files.update(refreshed.get('artifact_sha256', {})) if refreshed.get('result_path'): refreshed_files[refreshed['result_path']] = digest(refreshed['result_path']) for path, sha in refreshed_files.items(): if path in inputs and inputs[path] != sha: raise ValueError('Fresh measurement rebound an existing input: ' + path) inputs[path] = sha if refreshed.get('passed'): updates = {key: refreshed[key] for key in ('task', 'priors', 'evidence_manifest_sha256') if key in refreshed} if updates.get('evidence_manifest_sha256') != generated_sha: raise ValueError('Fresh evidence does not bind this actual output') config = dict(config, **updates) result['measurement_current'] = True result['refreshed_evidence_config'] = updates measured_review = review(generated, config) save(attempt / 'measured_review.json', measured_review) diagnostics.extend(measured_review['diagnostics']) elif refreshed.get('status') != 'pending': diagnostics.append(dict(code='measurement_refresh_failed', entity_ids=[], message='Fresh saved-scene measurements are unavailable; inspect receipt')) result['output_contract_passed'] = not diagnostics and ( geometry_options is None or result['geometry_passed']) save(attempt / 'output_review.json', dict(diagnostics=diagnostics, passed=result['output_contract_passed'], geometry_requested=result['geometry_requested'], geometry_provenance_current=result['geometry_provenance_current'], geometry_complete=result['geometry_complete'], scope=('inventory_floor_plan_native_source_and_saved_geometry' if geometry_options is not None else 'inventory_floor_plan_native_source_contract_only'))) save_repair(output, generated, effective, diagnostics, config) if diagnostics: result['status'] = 'output_contract_failed' elif geometry_options is not None and not result['geometry_passed']: result['status'] = 'generation_completed_pending_geometry_review' elif ((config.get('task') or config.get('priors')) and not result.get('measurement_current')): result['status'] = 'generation_completed_pending_measured_review' else: result['status'] = ('generation_completed_geometry_verified' if geometry_options is not None else 'generation_completed_pending_native_validation') except Exception as error: result.update(error_type=type(error).__name__, error=str(error)) if result['generation_executed'] and result['status'] != 'generation_failed': result['status'] = 'output_contract_failed' finally: result['pool_journal_absence'] = {str(path): not path.exists() for path in pool_journals} result['inputs_unchanged'] = (all(result['pool_journal_absence'].values()) and all(Path(path).is_file() and digest(path) == expected for path, expected in inputs.items())) result['input_sha256'] = inputs if not result['inputs_unchanged']: result.update(status='input_integrity_failed', output_contract_passed=False, geometry_current=False, geometry_passed=False, geometry_provenance_current=False) if 'base_identity' in result: result['base_identity_after'] = base_identity() if not result['base_identity_after']['passed']: result.update(status='source_integrity_failed', output_contract_passed=False, geometry_current=False, geometry_passed=False, geometry_provenance_current=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', help='Execute the explicitly configured generation command') args = parser.parse_args(argv) try: result = run_chain(args.config, args.output, execute=args.execute) except (ValueError, OSError) as error: print(str(error), file=sys.stderr) return 2 print(json.dumps(result, sort_keys=True)) return 0 if result['status'] in ('preflight_complete', 'generation_completed_geometry_verified', 'generation_completed_pending_native_validation') else 1 if __name__ == '__main__': raise SystemExit(main())