from pathlib import Path import ast,hashlib,json,struct import numpy as np from PIL import Image O=Path(__file__).resolve().parent;R=O.parents[1];P=R/'.reference/hd-iron-names-terrain2054d-2054e-and2057f-20581-20588-Original-primary-author-20261019-v1';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();js=lambda p:json.loads(Path(p).read_text());hp=R/'.reference/hd-shoreline4-independent-intrinsic-ART-review-20261019-v1/check_saved_shoreline.py';fn=next(x for x in ast.parse(hp.read_text()).body if isinstance(x,ast.FunctionDef)and x.name=='nx');ns={'np':np};exec(compile(ast.Module(body=[fn],type_ignores=[]),str(hp),'exec'),ns);nx=ns['nx'];handoff=P/'FINAL-NIGHT5-CURRENT-SOURCEG2-INTRINSIC-AUTHOR-HANDOFF.json';d=js(handoff);assert sha(handoff).startswith('5f305826');entries={i:(int(n),R/'data'/p)for i,n,p in(l.split()for l in(R/'data/INDEX').read_text().splitlines()if l.strip())};vga=np.frombuffer((R/'data/misc/PALETTE_DAT').read_bytes(),np.uint8).reshape(256,3);pal=(vga<<2)|(vga>>4);records=[];native=retained=0;banks={};qa_seen={};board_total=0 for item in d['assets']: a=item['asset'];g='hardware2'if a in ['2054d','2054e']else'dark3';qpath=R/item['actual_QA'];qa=js(qpath);bankpath=R/item['actual_indexed_bank'];bank=js(bankpath);row=next(x for x in bank if x['asset']==a);banks[a]=row;assert sha(qpath)==item['actual_QA_sha256'];assert sha(R/item['candidate'])==qa['candidate_sha256']==item['candidate_sha256'];assert qa['diagnostics']==[]and qa['actual_new_helper_invocations']==1;assert qa['artwork_sha256'][item['frame_binding']['file']]==sha(R/item['actual_selected_png'])==item['actual_selected_png_sha256'];assert sha(R/qa['library'])==qa['library_sha256'];assert all(sha(R/n)==h for n,h in qa['actual_sourceG2_source18_sha256'].items());qa_seen[str(qpath)]=sha(qpath) size,path=entries[a];b=path.read_bytes();assert len(b)==size==1044 and struct.unpack_from('<5i',b)==(1,1,0,32,32);src=np.frombuffer(b[20:],np.uint8).reshape(32,32);assert src.ravel().tolist()==row['source']['indices']and sha(path)==item['frame_binding']['source_sha256'];assert np.array_equal(np.array(Image.open(R/item['authentic_Original_png']).convert('RGB')),pal[src]);Q=qpath.parent;assert np.array_equal(np.array(Image.open(Q/f'{a}-original.ppm').convert('RGB')),pal[src]);board=Image.open(R/item['whole_native_page']).convert('RGB');assert board.size==(1328,710);cells=item['frame_binding'].get('original_detail_cells',[]);scales=[] for i,r in enumerate(row['scales']): s=r['scale'];actual=np.array(r['indices'],np.uint16).reshape(32*s,32*s);control=nx(src,s);assert(actual<256).all();assert np.array_equal(np.array(Image.open(Q/f'{a}-hd-{s}.ppm').convert('RGB')),pal[actual]);assert np.array_equal(np.array(Image.open(P/g/'whole-native-final-review-pages'/f'{a}-actual-native{s}-lossless.png').convert('RGB')),pal[actual]);functional=control>=240;assert np.array_equal(actual[functional],control[functional]);mask=np.zeros(actual.shape,bool) for x,y in cells:mask[y*s:(y+1)*s,x*s:(x+1)*s]=True assert np.array_equal(actual[mask],control[mask]);factor=[8,4,3,2][i];xx=16+i*328;size=32*s*factor for yy,img in [(36,pal[control]),(388,pal[actual])]:assert xx+size<=1328 and yy+size<=710;assert np.array_equal(np.array(board.crop((xx,yy,xx+size,yy+size))),np.array(Image.fromarray(img).resize((size,size),Image.Resampling.NEAREST)));board_total+=1 native+=actual.size;retained+=int(mask.sum());scales.append(dict(scale=s,indices=int(actual.size),retained_SourceNx_samples=int(mask.sum()),functional_SourceNx_samples_exact=int(functional.sum()),PPM_and_lossless_PNG_exact=True,complete_Source_and_actual_board_rectangles_exact=True)) # Verify black/functional derived512 backing exactly from Source4 followed by nearest4, not generated-art credit. derived=np.array(Image.open(R/item['actual_selected_png']).convert('RGB'));assert derived.shape==(512,512,3);guide=nx(src,4);exact=np.repeat(np.repeat(pal[guide],4,0),4,1);black=np.repeat(np.repeat(guide==31,4,0),4,1);functional=np.repeat(np.repeat(guide>=240,4,0),4,1);assert np.array_equal(derived[black|functional],exact[black|functional]);assert int(black.sum())==item['genuine_material_metrics']['opaque_black_HDR_pixels'];assert int(functional.sum())==item['genuine_material_metrics']['functional_HDR_pixels'];recipe=js(P/'source-material-code-proposal'/g/'recipe.json');raw=P/g/'returned-untouched-atlas.png';assert all(sha(P/'source-material-code-proposal'/g/q['path'])==q['sha256']==sha(raw)for q in recipe['donors'].values());records.append(dict(asset=a,Source_sha256=sha(path),candidate_sha256=item['candidate_sha256'],QA_sha256=sha(qpath),raw_master_sha256=sha(raw),derived_PNG_sha256=sha(R/item['actual_selected_png']),whole_native_board_sha256=sha(R/item['whole_native_page']),retained_logical_cells=cells,scales=scales,Original_black_512_samples=int(black.sum()),Original_functional_512_samples=int(functional.sum()),all_Source_black_and_functional_512_RGB_exact=True,these_samples_new_HD_credit=0)) # First hardware route stays historical HOLD: final changes only two declared E notch owners. old=js(P/'hardware2/actual-SourceG2-intrinsic/actual-indexed-source-and-scales.json');prior={r['asset']:r for r in old};notch_changes=[] for a in ['2054d','2054e']: Q=P/'hardware2/actual-SourceG2-two-clamp-notch-retention-successor';B=P/'hardware2/actual-SourceG2-intrinsic';assert prior[a]['source']==banks[a]['source'];assert sha(Q/f'{a}-original.ppm')==sha(B/f'{a}-original.ppm') for i,(bef,aft)in enumerate(zip(prior[a]['scales'],banks[a]['scales'])): s=i+1;x=np.array(bef['indices']).reshape(32*s,32*s);y=np.array(aft['indices']).reshape(x.shape);mask=np.zeros(x.shape,bool) if a=='2054e': for xx,yy in [(3,16),(29,16)]:mask[yy*s:(yy+1)*s,xx*s:(xx+1)*s]=True assert np.array_equal(x[~mask],y[~mask]) if a=='2054d':assert np.array_equal(x,y)and sha(Q/f'{a}-hd-{s}.ppm')==sha(B/f'{a}-hd-{s}.ppm') notch_changes.append(dict(asset=a,scale=s,changed_samples=int(np.count_nonzero(x!=y)),outside_declared_two_notches_changes=0)) # Gray Source contacts stay actual gray; retain the truthful two tiny warm marker-adjacent bottom samples. a=np.array(banks['20581']['scales'][0]['indices']).reshape(32,32);tips=[dict(cell=[x,y],actual_index=int(a[y,x]),RGB=pal[a[y,x]].tolist())for x,y in [(29,11),(30,11),(29,18),(30,18),(29,25),(30,25)]];assert all(t['RGB'][0]==t['RGB'][1]==t['RGB'][2]for t in tips);a=np.array(banks['20588']['scales'][0]['indices']).reshape(32,32);bottom=pal[a[-1]];warm=[dict(x=i,RGB=v.tolist())for i,v in enumerate(bottom)if not(v[0]==v[1]==v[2])];assert warm==[dict(x=8,RGB=[16,8,4]),dict(x=24,RGB=[16,8,4])] code=R/d['different_code_binding_review']['path'];assert sha(code)==d['different_code_binding_review']['sha256'];out=dict(status='PASS_INDEPENDENT_NIGHT5_LITERAL_SOURCE_NATIVE_PPM_BOARD_AND_FUNCTIONAL_AUDIT',handoff_sha256=sha(handoff),records=records,Source_indices=5120,final_native_indices=native,retained_native_SourceNx_samples=retained,whole_board_body_rectangles=board_total,notch_only_successor_changes=notch_changes,gray_20581_contact_tips_native1=tips,20588_bottom_row_dim_warm_points=warm,continuous_rust_fringe=False,code_review_sha256=sha(code),historical_author_execution_counts=d['executions'],new_operations_by_reviewer=dict(cleanup=0,renderer=0,QA=0,generation=0,World=0),script_sha256=sha(__file__));(O/'PASS-INDEPENDENT-NIGHT5-SAVED-NATIVE-AND-MATERIAL-FIDELITY.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps({k:v for k,v in out.items()if k not in ['records','notch_only_successor_changes']},indent=2))