"""Read-only evidence binding and low-cost positive connectivity replay. CLI writes only --out, never the case or native audit. Evidence failures are returned, not ignored. Run after native generation and strict render validation. """ from __future__ import annotations import argparse import hashlib import json from pathlib import Path from acceptance_layers import evaluate_evidence from furnishing_fulfillment import audit_saved_coverage, fingerprint def sha(path): h=hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda:stream.read(1024*1024),b''):h.update(block) return h.hexdigest() def load_case_evidence(case, validation_dir=None): root=Path(case).resolve(); final=root recovery=root/'layout_recovery_execution.json' if recovery.is_file(): value=json.loads(recovery.read_text()) if value.get('final_case'): final=Path(value['final_case']).resolve() if final != root and root not in final.parents:raise ValueError('final_case_outside_root') b=dict(schema='rhg.acceptance-evidence.v1',bindings={},references={},evidence_errors=[]) cache={} def digest(p): p=Path(p).resolve() if p not in cache:cache[p]=sha(p) return cache[p] def read(p): p=Path(p).resolve(); d=json.loads(p.read_text()) b['references'][str(p)]=digest(p) return d def check_hash(p,expected): return isinstance(expected,str) and len(expected)==64 and digest(p)==expected def part(name,func): try:func() except (OSError,ValueError,KeyError,TypeError,IndexError,ImportError) as exc: b['bindings'][name]=False b['evidence_errors'].append(dict(stage=name,error=type(exc).__name__+': '+str(exc))) state={} def generation(): g=read(final/'execution/result.json'); b['generation']=g mpath=Path(g['generated_manifest']).resolve() if final not in mpath.parents:raise ValueError('manifest_outside_final_case') m=read(mpath); state.update(manifest_path=mpath,manifest=m,directory=mpath.parent) blends=list(mpath.parent.glob('*.blend')) if len(blends)!=1:raise ValueError('saved_blend_not_unique') state['blend']=blends[0] candidates=[] for path in (final/'execution/chain').glob('round_*/attempt_*/geometry/result.json'): data=read(path) if data.get('manifest_sha256')==digest(mpath):candidates.append(data) if len(candidates)!=1:raise ValueError('current_geometry_not_unique') geo=candidates[0];b['geometry']=geo pins=geo.get('input_sha256') or {} evidence=geo.get('evidence_input_sha256') or {} b['bindings']['geometry']=(check_hash(mpath,g.get('generated_manifest_sha256')) and check_hash(blends[0],geo.get('scene_sha256')) and bool(pins) and all(check_hash(p,h) for p,h in {**pins,**evidence}.items())) part('geometry',generation) def validation(): if validation_dir is None:raise ValueError('strict_validation_missing') vdir=Path(validation_dir).resolve() result=read(vdir/'result.json'); b['validation']=result plan=read(vdir/'plan.json'); state['plan']=plan if Path(plan['manifest']).resolve()!=state['manifest_path']:raise ValueError('validation_wrong_manifest') artifacts=result.get('artifact_hashes') or {} required=[vdir/'layout_conventions.json',vdir/'render_views/wholehouse_visibility_evidence.json',vdir/'render_views/visibility_audit.json'] if not all(str(p) in artifacts and check_hash(p,artifacts[str(p)]) for p in required): raise ValueError('strict_artifacts_changed_or_unbound') r=read(required[1]);b['render_receipt']=r b['visibility']=read(required[2]);b['conventions']=read(required[0]) if Path(r['source_blend']).resolve()!=state['blend']:raise ValueError('render_wrong_scene') if not (check_hash(state['blend'],r.get('source_sha256')) and check_hash(state['blend'],r.get('source_sha256_after')) and check_hash(state['manifest_path'],r.get('source_manifest_sha256'))): raise ValueError('render_scene_changed') render_files=r.get('files_sha256') or {} if not render_files or not any(x.get('rendered') is True for x in r.get('views',[])): raise ValueError('render_outputs_missing') for name,expected in render_files.items(): path=(vdir/'render_views'/name).resolve() if (vdir/'render_views') not in path.parents or not check_hash(path,expected): raise ValueError('render_output_changed_or_outside_output') b['bindings']['render']=True conv=b['conventions'];findings=conv.get('findings') b['bindings']['conventions']=(conv.get('schema')=='rhg.layout-conventions-audit.v1' and Path(conv['manifest']).resolve()==state['manifest_path'] and isinstance(findings,list) and conv.get('fail_count')==sum(r.get('severity')=='fail' for r in findings) and conv.get('warn_count')==sum(r.get('severity')=='warn' for r in findings) and conv.get('passed')==(conv.get('fail_count')==0)) part('render',validation) def structure(): directory=state['directory'];r=b['render_receipt'] sourcepins=r.get('source_files_sha256') or {} needed=['saved_blend_verification.json','metric_layout_verification.json','shell_geometry_input.json'] if not all(check_hash(directory/n,sourcepins.get(n)) for n in needed): raise ValueError('saved_structure_evidence_unbound_or_changed') st=read(directory/needed[0]);metric=read(directory/needed[1]);shell=read(directory/needed[2]) b['structure']=st;b['metric']=metric;state['shell']=shell from acceptance_doors import door_degradation_evidence b['door_degradation']=door_degradation_evidence(state['manifest'],shell,st) b['bindings']['structure']=check_hash(state['blend'],st.get('blend_sha256')) part('structure',structure) def connectivity(): import layout_conventions_audit as native import passability m=state['manifest'];shell=state['shell'];plan=m['floor_plan'] rooms=plan.get('rooms') or [];doors=plan.get('doors') or [] if not rooms or not doors:raise ValueError('room_or_door_inventory_missing') rids=[r['room_id'] for r in rooms];dids=[d['door_id'] for d in doors] if len(rids)!=len(set(rids)) or len(dids)!=len(set(dids)):raise ValueError('duplicate_room_or_door') if not all(d.get('room_ids') and set(d['room_ids'])<=set(rids) for d in doors): raise ValueError('door_room_references_invalid') if not shell.get('floor_mesh_bounds') or not shell.get('wall_mesh_bounds'): raise ValueError('measured_shell_missing_no_approximation_allowed') data=passability.analyse(plan,m['entities'],native.footprint,shell,passability.BODY_RADIUS_M) data.update(evaluated=True,saved_shell_used=True,inventory_complete=True, evaluated_room_ids=rids,evaluated_door_ids=dids, producer={str(Path(x.__file__).resolve()):digest(x.__file__) for x in (native,passability)}) b['connectivity']=data b['bindings']['connectivity']=b['bindings'].get('structure') is True and b['bindings'].get('geometry') is True part('connectivity',connectivity) def inventory(): original=read(root/'source_request.json') if fingerprint(read(final/'source_request.json')) != fingerprint(original): raise ValueError('recovery_original_requirement_differs_from_root') request=read(final/'request.json') ledger=read(final/'furnishing_fulfillment.json') actual=[e['entity_id'] for e in state['manifest']['entities']] if len(actual)!=len(set(actual)):raise ValueError('saved_entity_ids_duplicate') b['inventory']=audit_saved_coverage(original,request,actual,ledger) b['bindings']['inventory']=b['bindings'].get('geometry') is True part('inventory',inventory) b['case']=str(root);b['final_case']=str(final) return b def evaluate_case(case,validation_dir=None): bundle=load_case_evidence(case,validation_dir) result=evaluate_evidence(bundle) result.update(case=bundle['case'],final_case=bundle['final_case'],connectivity=bundle.get('connectivity')) return result def main(): p=argparse.ArgumentParser() p.add_argument('--case',required=True,type=Path) p.add_argument('--validation-dir',type=Path) p.add_argument('--out',required=True,type=Path) args=p.parse_args() result=evaluate_case(args.case,args.validation_dir) args.out.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n') print(json.dumps(dict(basic_success=result['basic_success'],gates=result['gates']))) return 0 if result['basic_success'] else 2 if __name__=='__main__':raise SystemExit(main())