#!/usr/bin/env python3 """Alternate root check: forced pivots, integer affine DP and output-first membership. No primary CALCULATION.py is imported. No independent-agent review is claimed. """ import argparse,json,hashlib from pathlib import Path from fractions import Fraction as Q from itertools import product from math import gcd,lcm def main(src,out): def load(name):return json.loads((src/name).read_text()) checks=[] def ck(name,value): assert value,name assert name not in checks,name checks.append(name) reg=load('C286_DATA.json')['target_register'];cum=load('C365_DATA.json')['cumulative_register'];coords={r['center'] for r in reg};cums={r['coordinate'] for r in cum};keys=['tradition','rail','Cainan','Terah60','full430'] def fam(r):return tuple(r.get(k) for k in keys) noahs=[r for r in reg if r['role']=='Noah birth'];found=[] # The main census iterates all family pairs. Here an endpoint edge forces both pivots. for low in [r for r in noahs if r['gear'] in [1,2]]: g=low['gear'];f=fam(low);high=next(r for r in noahs if r['gear']==g+1 and fam(r)==f);y=low['center'];x=high['center'];num=25*x-23*y ck('source adjacent Noah edge '+str((f,g)),x-y==2 and num%2==0) N=num//2;A=y-299*(x-y) held=[r for r in noahs if r['gear']==g and r['center']==N] floods=[r for r in reg if r['gear']==g+1 and r['role'] in ['Flood start','Flood close'] and r['center']==A and all(r.get(k)==v for k,v in zip(keys,f) if k!='rail')] for nr in held: for ar in floods:found.append({'g':g,'edge_family':f,'held_family':fam(nr),'boundary':ar['role'],'x':x,'y':y,'N':N,'A':A}) def sig(h):return(h['g'],h['edge_family'],h['held_family'],h['boundary']) expected={(h['lower_Gear'],tuple(h['edge_family'].get(k) for k in keys),tuple(h['held_Noah_family'].get(k) for k in keys),h['J_Flood_boundary']) for h in load('C396_DATA.json')['hits']} ck('forced-pivot source census',len(found)==12 and {sig(h) for h in found}==expected) loops=sorted({(h['N'],h['x'],h['y'],h['A']) for h in found});ck('six coordinate loops',loops==[tuple(x) for x in load('C396_DATA.json')['coordinate_loops']] and len(loops)==6) complete=[(N,x,y,A,y-138) for N,x,y,A in loops if y-138 in coords];ck('two complete three-operator loops',complete==[(3056,3033,3031,2433,2893),(3058,3035,3033,2435,2895)]) for k,h in enumerate(load('C394_DATA.json')['rows']): for t in h['pivot_tests']: den=69 if t['operator']=='P' else 299;required=t['input']-den*(t['output']-t['input']) ck('initial unique pivot '+str((k,t['orientation'],t['operator'])),required==t['unique_required_pivot'] and (required in coords)==bool(t['source_record_indices'])) for k,h in enumerate(load('C394_DATA.json')['reflections']): images=h['reflected_coordinates'];ck('initial Mirror obstruction '+str(k),images['held_Noah'] in cums and all(v not in cums for key,v in images.items() if key!='held_Noah')) # Canonical integer affine triple(a,b,d): t -> (a*t+b)/d. def norm(t): g=gcd(gcd(abs(t[0]),abs(t[1])),abs(t[2]));return tuple(v//g for v in t) def dil(p,q,c):return norm((p,(q-p)*c,q)) def comp(A,B):return norm((A[0]*B[0],A[0]*B[1]+A[1]*B[2],A[2]*B[2])) def at(T,x):return Q(T[0]*x+T[1],T[2]) def eqrecord(T,v):return [str(Q(T[0],T[2])),str(Q(T[1],T[2]))]==v phasecount=0 for k,h in enumerate(load('C395_DATA.json')['rows']): N,A,x,y=[h[t] for t in ['Noah_pivot','Flood_pivot','E_input','E_output']];E=dil(25,23,N);J=dil(300,299,A);JE=comp(J,E);EJ=comp(E,J) ck('integer primitive loop maps '+str(k),JE==dil(7500,6877,x) and EJ==dil(7500,6877,y) and eqrecord(JE,h['J_after_E_coefficients']) and eqrecord(EJ,h['E_after_J_coefficients'])) good=[] for eps in product([-1,1],repeat=4): n,a,u,v=[4*z+e for z,e in zip([N,A,x,y],eps)] if 25*(u-n)==23*(v-n) and 300*(v-a)==299*(u-a):good.append(eps) ck('integer component loop census '+str(k),good==[(-1,)*4,(1,)*4]);phasecount+=len(good) ck('950 biography residuals '+str(k),at(E,x-950)-(y-950)==-Q(1900,23) and at(J,y-950)-(x-950)==-Q(950,299) and at(JE,x-950)-(x-950)==-Q(591850,6877)) edges=[] for k,(N,x,y,A,B) in enumerate(complete): E=dil(25,23,N);P=dil(70,69,B);J=dil(300,299,A) for c,Lp,Lj in [(y,comp(E,P),comp(E,J)),(x,comp(P,E),comp(J,E))]: ck('integer commuting source circuits '+str((k,c)),Lp==dil(1750,1587,c) and Lj==dil(7500,6877,c) and comp(Lp,Lj)==comp(Lj,Lp)) ck('individual operators remain noncommuting '+str(k),comp(E,P)!=comp(P,E) and comp(E,J)!=comp(J,E) and comp(P,J)!=comp(J,P)) for op,u,v,T in [('E',x,y,E),('P',y,x,P),('J',y,x,J)]:edges.append((op,u,v,T)) req=N+215;ck('original17K translated pivot missing '+str(k),req in [3271,3273] and req not in coords and at(E,x+215)-(y+215)==Q(430,23)) components={4*r['center']+e for r in noahs for e in [-1,1]} ck('translated component pivot absent '+str(k),all(Q(25*(4*(x+215)+ex)-23*(4*(y+215)+ey),2) not in components for ex,ey in product([-1,1],repeat=2))) ret=[] for field in load('C378_DATA.json')['fields']: menu=coords if field['field']=='regular' else cums for h in field['hits']: u,v,A,B=[h[t] for t in ['input','output','J_pivot','P_pivot']];V=Q(25*v-23*u,2);support=V in menu;ret.append((field['field'],u,v,str(V),support)) expectedret={(r['field'],r['common_edge'][0],r['common_edge'][1],r['unique_E_return_pivot'],r['source_E_P_J_loop']) for r in load('C399_DATA.json')['rows']} ck('all ten common-edge return pivots',set(ret)==expectedret and len(ret)==10 and sum(t[-1] for t in ret)==2) # Dynamic programming merges paths by endpoints/counts, unlike primary path enumeration. verts=[3031,3033,3035];level={(v,v,0,0,0):((1,0,1),1) for v in verts};states={};routecount=0;mergecount=0 for length in range(7): nxt={} for key,(T,multiplicity) in level.items(): start,current,e,p,j=key;states[key]=T;routecount+=multiplicity if length==6:continue for op,u,v,A in edges: if u!=current:continue inc={'E':(1,0,0),'P':(0,1,0),'J':(0,0,1)}[op];newkey=(start,v,e+inc[0],p+inc[1],j+inc[2]);newT=comp(A,T) if newkey in nxt: oldT,n=nxt[newkey];assert oldT==newT;mergecount+=1;nxt[newkey]=(newT,n+multiplicity) else:nxt[newkey]=(newT,multiplicity) level=nxt primary={tuple(r[k] for k in ['start','end','E_count','P_count','J_count']):r['affine_coefficients'] for r in load('C400_DATA.json')['normal_form_classes']} ck('integer DP coverage',set(states)==set(primary) and len(states)==78 and routecount==402) for key,T in sorted(states.items()): u,v,e,p,j=key;ck('integer DP normal form '+str(key),eqrecord(T,primary[key]) and (v-u)//2==p+j-e and Q(T[0],T[2])==Q(25,23)**e*Q(70,69)**p*Q(300,299)**j) ck('prime count certificate',load('C400_DATA.json')['prime_valuation_certificate']=={'7':[0,1,0],'13':[0,0,-1],'5':[2,1,2]}) # Enumerate possible source outputs and invert each circuit to find source inputs. domainhits=0 for c in verts: for op,num,den in [('P',1750,1587),('J',7500,6877)]: T=dil(num,den,c);pairs=[] for target in coords: n=T[2]*target-T[1] if n%T[0]==0 and n//T[0] in coords:pairs.append((n//T[0],target)) ck('output-first circuit source domain '+str((c,op)),pairs==[(c,c)]);domainhits+=len(pairs) ck('circuit denominator source-range bound '+str((c,op)),max(abs(x-c) for x in coords)max(abs(x-c) for x in coords for c in verts)) for p in range(4): for j in range(4):ck('reduced circuit denominator '+str((p,j)),(Q(1750,1587)**p*Q(7500,6877)**j).denominator==3**max(p-j,0)*13**j*529**(p+j)) # Authenticate source excerpts and reconstruct current table baselines independently. d402=load('C402_DATA.json');cards={c['id']:c for c in d402['source_excerpt_cards']} for key,c in cards.items(): raw=(src/c['source']).read_text().splitlines();t='\n'.join(raw[c['line_start']-1:c['line_end']]);ck('source excerpt identity '+key,t==c['text'] and hashlib.sha256(t.encode()).hexdigest()==c['excerpt_sha256']) mt=next(l for l in cards['MT_NOAH']['text'].splitlines() if l.startswith('| Noah |')).split('|')[2].strip().split('/')[1].split()[0] sp=next(l for l in cards['SP_FIELD']['text'].splitlines() if l.startswith('| G1 |')).split('|')[2].strip().split('/')[0] lx=next(l for l in cards['NOAH_BASES']['text'].splitlines() if l.startswith('| LXX | Noah |')).split('|')[4].strip().split('–')[0] bases={'MT':int(mt),'SP':int(sp),'LXX':int(lx)};flood={} for tr,label in [('MT','MT'),('SP','SP'),('LXX','LXX — native Cainan ON')]:flood[tr]=int(next(l for l in cards['FLOOD']['text'].splitlines() if l.startswith('| '+label+' |')).split('|')[4].strip().split('→')[0]) slots=0 for case in d402['reconstruction_rows']: for slot in case['reconstructed_records']: r=slot['source_record'];tr=r['tradition'];native=int(tr=='LXX');g=r['gear'];v=130*(r['Cainan']-native)+60*r['Terah60']+2*(g-1) if r['role']=='Noah birth':v+=bases[tr]+215*r['full430']-int(tr=='SP' and r.get('rail')=='companion') else:v+=flood[tr]+215*(r['full430']-1)-int(r['role']=='Flood close') ck('independent source reconstruction '+str((case['case'],slot['role_in_loop'])),v==r['center']==slot['reconstructed_coordinate']);slots+=1 ck('source reconstruction coverage',slots==52 and 'converts a gap, not a date' in cards['J_GAP']['text']) result={'status':'passed','performed_by':'root agent','new_independent_agent_review':False,'method':'Source endpoint pairs force E/J pivots; integer affine dynamic programming merges path counts; output-first circuit source membership; independent source-table reconstruction. No primary calculation imported.','check_count':len(checks),'checks':checks,'source_labelled_E_J_loops':12,'coordinate_E_J_loops':6,'coordinate_E_P_J_loops':2,'source_vertices':3,'source_operator_edges':6,'integer_DP_path_count':routecount,'integer_DP_affine_classes':len(states),'DP_merges':mergecount,'matched_component_loops':phasecount,'nonfixed_circuit_source_images':0,'source_record_slots_reconstructed':slots,'C404_executed':False,'canonical_or_graph_edits':False} out.mkdir(parents=True,exist_ok=True);(out/'ROOT_SECOND_METHOD_RESULTS.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print(json.dumps({'status':'passed','root_secondary_checks':len(checks)})) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--sources',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args();main(a.sources,a.out)