"""Independent exact source/model review, without numbered-step execution."""
from pathlib import Path
from fractions import Fraction as F
import json,hashlib,importlib.util,sys
R=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(R/'prep/covenant_constraints'))
from exact import Matrix
spec=importlib.util.spec_from_file_location('reviewed_covenant_model',R/'evidence/covenant_model.py');cm=importlib.util.module_from_spec(spec);spec.loader.exec_module(cm)
records={x['step']:x for x in json.loads((R/'journal.json').read_text()) if 1032<=x['step']<=1057}
p=json.loads((R/'prep/covenant_constraints/source_packet.json').read_text());diag=json.loads((R/'prep/covenant_constraints/diagnostics.json').read_text());ind=json.loads((R/'prep/covenant_constraints/source_only_reproduction.json').read_text())
v={k:F(x) for k,x in json.loads((R/'model/covenant_source_inputs.json').read_text()).items()};checks={};details={}
checks['contiguous_26_records']=list(records)==list(range(1032,1058))
checks['source_hashes_unchanged']=all(hashlib.sha256(Path(x['path']).read_bytes()).hexdigest()==x['sha256'] for x in p['sources'].values())
def bindings(x):
 if isinstance(x,dict):
  if all(k in x for k in ['path','sha256','bytes']):yield x
  for y in x.values():yield from bindings(y)
 elif isinstance(x,list):
  for y in x:yield from bindings(y)
bs=[a for rec in records.values() for a in bindings(rec['results'])]
checks['artifact_bindings_unchanged']=all(hashlib.sha256((R/a['path']).read_bytes()).hexdigest()==a['sha256'] and (R/a['path']).stat().st_size==a['bytes'] for a in bs)
details['artifact_bindings_checked']=len(bs)
checks['literal_source_inputs_exact']=v=={x['name']:F(x['value']) for x in p['source_local_parameters']}
reg=cm.regular(v);cum=cm.cumulative(v)
checks['regular_12_nodes_match_independent_reproduction']=reg=={k:F(x) for k,x in ind['regular_network'].items()}
checks['cumulative_seven_bases_match']=cum['base']==list(map(F,ind['original_cumulative']))
checks['all_42_phase_clutch_values_match']=cum['rails']==[list(map(F,x['values'].values())) for x in ind['six_rails']]
checks['clutch_not_an_independent_input']=cum['clutch']==14 and cum['half']==7 and not any(k in v for k in ['clutch','half','Ishmael_Levi_birth_gap','Levi_terminal_gap'])
inc=json.loads((R/'model/covenant_incidence_matrix.json').read_text());MI=Matrix(inc['matrix']);II=Matrix(inc['inverse'])
checks['incidence_rank12']=MI.rank()==12
checks['incidence_determinant1']=MI.det()==F(inc['determinant'])==1
checks['incidence_exact_inverse']=(MI*II).tolist()==[[int(i==j) for j in range(12)] for i in range(12)]
checks['incidence_only_differs_from_prep_by_row_order']=abs(F(diag['coordinate_map']['determinant']))==abs(MI.det())==1
cb=json.loads((R/'model/covenant_claim_basis.json').read_text());M=Matrix(cb['matrix'])
checks['claim_coefficients_match_independent_affine_expansion']=cb['matrix']==diag['claim_matrix']
checks['all_source_claim_residuals_zero']=cm.claims(v)==[0]*9
checks['claim_ranks_4_5_6_8']=[Matrix(cb['matrix'][:i]).rank() for i in [4,5,6,8,9]]==[4,5,6,8,8]
checks['complete_dependency_circuit']=all(cb['matrix'][8][i]==-cb['matrix'][1][i]+cb['matrix'][2][i]+cb['matrix'][3][i]+cb['matrix'][4][i] for i in range(13))
checks['E_centered_identity']=all(25*cb['matrix'][7][i]-2*cb['matrix'][6][i]==(21 if i==12 else -25 if i==10 else 0) for i in range(13))
u=v['Q']-reg['Levi_death'];w=v['Q']-reg['Joseph_death'];a=v['Q']-F(25,23)*w;b=v['Q']-F(300,299)*u
checks['mixed_Key_cycle_and_generated_landings']=(u,w,a,b)==(299,276,1566,1566) and a-b==-F(25,299)*(13*w-12*u)
norm=json.loads((R/'model/covenant_normalized_constraints.json').read_text());NM=Matrix(norm['matrix'])
checks['normalization_ranks']=[Matrix(norm['matrix'][:9+i]).rank() for i in range(4)]==[8,9,10,11]
checks['two_residual_directions_exact']=len(norm['kernel'])==2 and all(all(sum(F(a)*F(b) for a,b in zip(row,z))==0 for row in norm['matrix']) for z in norm['kernel'])
ident=norm['matrix']+[[int(i==2) for i in range(13)],[int(i==4) for i in range(13)]]
checks['retained_source_rows_restore_rank13']=Matrix(ident).rank()==13
field=json.loads((R/'model/clutch_array_matrix.json').read_text());FM=Matrix(field['matrix']);labs=field['labels']
checks['clutch_matrix_matches_full_formula']=len(labs)==42 and field['matrix']==[[int(a==i) for a in range(7)]+[j,-k] for i,j,k in labs]
checks['clutch_rank9_and33_dependencies']=FM.rank()==9 and len(FM.T.nullspace())==33
selected=records[1049]['results']['basis_indices'];OM=Matrix([field['matrix'][i] for i in selected])
checks['observation_basis_exact']=OM.det()==-1 and [labs[i] for i in selected]==[[i,0,0] for i in range(7)]+[[0,1,0],[0,0,1]]
checks['missing_phase_shift_row_rank8']=all(Matrix([r for r,(i,j,k) in zip(field['matrix'],labs) if keep(i,j,k)]).rank()==8 for keep in [lambda i,j,k:j==0,lambda i,j,k:k==0,lambda i,j,k:i!=0])
Eqs=Matrix([[0]*7+[-2,1],[0,0,0,1,-1,-1,1,0,0]])
checks['phase_repeat_source_conditions_independent']=Eqs.rank()==2 and 7-2*F(7,2)==0 and 7-2*3==1
checks['forced_Kohath_Levi_joins']=cum['base'][4]-cum['clutch']==cum['regular_full_Levi_death']==1782 and cum['base'][3]-cum['clutch']==reg['Levi_birth']+v['full_state_shift']==1919
zero={k:F(0) for k in cm.KEYS};symbolic=[]
for key in cm.KEYS:
 z=zero.copy();z[key]=F(1);rr=cm.regular(z);cc=cm.cumulative(z)
 symbolic.append([cc['base'][4]-cc['clutch']-cc['regular_full_Levi_death'],cc['base'][3]-cc['clutch']-(rr['Levi_birth']+z['full_state_shift']),cc['base'][2]-cc['clutch']-(rr['Isaac_birth']+z['full_state_shift'])+cm.claims(z)[0]])
checks['forced_joins_and_Jacob_residual_all19_coefficients']=symbolic==[[0,0,0]]*19
z=v.copy();z['Moses_birth']+=1;cz=cm.cumulative(z)
checks['seven_translated_nodes_cancel_Moses_anchor']=[x-cum['clutch'] for x in cum['base']]==[x-cz['clutch'] for x in cz['base']]
offs=[x-cum['clutch']-cum['regular_full_Levi_death'] for x in cum['base']]
checks['complete_root_offsets']=offs==[639,464,284,137,0,-133,-270]
checks['fixed_clutch_keeps_exact_phase']=[a-b for a,b in zip(cum['rails'][5],cum['rails'][2])]==[F(7,2)]*7
checks['separate_full_clutch_cancels_phase']=[x+v['phase']-(cum['clutch']+v['phase']) for x in cum['base']]==cum['rails'][2]
def outs(x):return list(cm.regular(x).values())+[x['L_A']]+[y for r in cm.cumulative(x)['rails'] for y in r]
CM=Matrix(cm.coefficient_matrix(outs,cm.KEYS))
checks['coupled_field_rank19_outputs55']=CM.shape==(55,19) and CM.rank()==19
ledger=json.loads((R/'model/covenant_clutch_dependency_ledger.json').read_text())
checks['author_and_phase_guards_retained']=all(any(needle in s for s in ledger['source_authority']) for needle in ['2081 author-designated','2051 / Isaac age15 proposed','1936 whole-year separate'])
z=v.copy();z['Q']+=215;z['T']+=215;tr=cm.regular(z)
checks['C1034_formal_translation_math_correct']=all(tr[k]-reg[k]==215 for k in reg)
checkpoint_path=R/'model/checkpoint_1070.json'
checkpoint=json.loads(checkpoint_path.read_text())
integration_record=next(x for x in json.loads((R/'journal.json').read_text()) if x['step']==1070)
checkpoint_binding=integration_record['results']['integration_checkpoint']
qualification=checkpoint['accepted_qualifications']['C1034']
checks['C1034_qualification_sealed_at_C1070']=('formal covariance only' in qualification and 'retains that terminal' in qualification and hashlib.sha256(checkpoint_path.read_bytes()).hexdigest()==checkpoint_binding['sha256'] and checkpoint_path.stat().st_size==checkpoint_binding['bytes'])
details['C1034_scope_qualification']={'formal_test_terminal':int(tr['terminal']),'source_terminal':int(reg['terminal']),'finding':'The +215 test is whole-frame covariance, not the admitted MT Minimum/full-state source operation. It also moves the terminal to 1621. The explicit clarification is sealed at C1070; the original record remains unchanged.','resolved_at_step':1070,'checkpoint_sha256':checkpoint_binding['sha256'],'sealed_wording':qualification}
details['clutch_phase_qualification']='The phase-cancellation comparison concerns the fully translated seven-node rail. It must not be generalized to every intermediate half-clutch state.'
out={'scope':'C1032–C1057 independent source/model review, including resolution of C1034 wording at C1070','status':'PASS' if all(checks.values()) else 'FAIL','checks':checks,'passed':sum(checks.values()),'total':len(checks),'details':details,'corrections_required':[],'C1057_record_sha256':records[1057]['sha256']}
(R/'evidence/INDEPENDENT_C1032_C1057.json').write_text(json.dumps(out,indent=2,ensure_ascii=False)+'\n')
print(json.dumps({'status':out['status'],'passed':out['passed'],'total':out['total'],'failed':[k for k,v in checks.items() if not v]}))
