"""Freeze exact joins for the canonical research report. Never calls providers."""
import hashlib,json
from collections import Counter
from pathlib import Path
LAB=Path(__file__).resolve().parents[1];OUT=LAB/'funded-rounds';R2=OUT/'round2'
ROOT=Path('/home/researcher/dry-lint-round');CENTRAL=ROOT/'jobs/judge-operations/.lab-results'
def read(p):return[json.loads(l)for l in p.open()if l.strip()]
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
source_path=ROOT/'reports/research-experiments/promotion/funded-round1-source/coordinator-decisions.jsonl';source={r['case_identity']['case_id']:r for r in read(source_path)if r['case_identity'].get('method')=='operation-blocks'}
producers=[R2,R2/'supplement-004-pairs-v1'];packets={p['id']:p for d in producers for p in read(d/'queue.jsonl')};side={r['id']:r for d in producers for r in read(d/'review-private-sidecar.jsonl')};planned={r['request_key']:r for d in producers for p in d.glob('**/canonical-request-plan.jsonl')for r in read(p)}
# Main root intake plus the four-pair, separately frozen supplement only.
rootpaths=[CENTRAL/'promotion-operations/intakes/operation-blocks/round2/14eb9e401661314e-4cbb628cfd97/completed.jsonl',CENTRAL/'promotion-operations/intakes/operation-blocks/round2/b9e6b8cf1dba09c3-4cbb628cfd97/completed.jsonl']
rows=[];counts=Counter();cost=0.;keys=set()
for path in rootpaths:
 for r in read(path):
  packet=packets[r['id']];assert packet==r['packet'];s=side[r['id']];audit=s['arm']!='baseline_control';obs=[]
  for o in r['observations']:
   key=o['request_key'];assert key not in keys;keys.add(key);p=planned[key];assert o['identity']==p['identity'];assert o['response_state']=='success'and not o.get('cached')and not o.get('error');v=o['verdict'];emits=v['label']in['duplicate','drifted']and v['score']>=.8;cost+=o['usd'];counts['observations']+=1
   obs.append({'kind':o['kind'],'request_key':key,'label':v['label'],'score':v['score'],'actual_usd':o['usd'],'status':o['response_state'],'original_diagnostic_report':emits,'residual_counterfactual_report':emits and not audit,'new_residual_emission_credit':0,'matched_policy':{'judge':o['identity']['judge'],'version':o['identity']['version'],'model':o['identity']['model'],'output_tokens':o['identity']['max_output_tokens'],'report_at':.8}})
   counts[('audit'if audit else'baseline_control')+'_'+o['kind']+'_original_reports']+=emits
   counts[('audit'if audit else'baseline_control')+'_'+o['kind']+'_counterfactual_reports']+=emits and not audit
  counts['rejection_audit_pairs'if audit else'baseline_control_pairs']+=1
  rows.append({'id':r['id'],'profile':s['profile'],'arm':s['arm'],'original_normal_funding':True,'residual_candidate_included':not audit,'revised_exclusion':s.get('revised_exclusion'),'no_new_residual_emission_credit':True,'source_status':'independent review requested; no accepted coordinator decision artifact joined at freeze','observations':obs,'source_proofs':packet['source_proofs'],'root_feed':str(path),'root_feed_sha256':sha(path)})
assert round(cost,8)==.2277608 and len(rows)==29 and len(keys)==58
(OUT/'final-round2-observation-joins.jsonl').write_text(''.join(json.dumps(r,sort_keys=True)+'\n'for r in rows))
stages=json.loads((R2/'full-source-stage-summary.json').read_text());transitions=json.loads((R2/'paired-selector-transitions.json').read_text());r1=json.loads((OUT/'round1/concept-outcomes-v1/summary.json').read_text());rf=next(r for r in read(OUT/'round1/source-joined-v2/scoped-usefulness.jsonl')if r['review_id']=='RF14');normal=rf['normal_04_concept_funding'];assert normal['baseline_target_funded']is False and normal['variant_target_funded']is True
summary={'canonical_report':str(LAB/'DECISION.md'),'status':'FINAL_BOTH_ROUNDS_PAID_COMPLETE_NO_MORE_CALLS','decision':'Keep original bounded plugin opt-in. Do not promote the residual-coverage veto. No default/balanced emission gain inferred.','round1_fresh_owned_usd':r1['round1_total_fresh_usd'],'round2_fresh_owned_usd':round(cost,8),'both_minima_met':r1['round1_total_fresh_usd']>=.2 and cost>=.2,'historical_pre_promotion_spend_excluded':{'pilot':.1122898,'intake_seven':.01916576},'worker_provider_calls':0,'no_more_calls':True,'round1_main':{'judged_novel_pairs':4,'judged_baseline_controls':12,'answered_observations':32,'unstarted_unknown_observations':64,'novel_sharedops_reports':1,'novel_jev_reports':0,'source_accepted_useful_novel_pairs':1,'source_accepted_useful_controls':3},'concept_supplement':{'pairs':4,'emitted_source_positive_pairs':2,'positive_families':1,'known_negative_control_reports':0,'matched_TFIDF20_incremental_gains':0,'original_policy':'anthropic/concept/dry-v2:claude-sonnet-5-5/output8000; retries2->0 separately recorded'},'RF14':{'human_case':'Reuse token-or-error helper in Responses login error translation','source_accepted_scope':source['OBR1-cd803a8002adba3e']['bounded_extractable_scope'],'source_family':rf['source_family'],'accepted_usefulness_not_whole_function_equivalence':True,'matched_baseline3_plus_TFIDF20_before_retrieved':False,'matched_before_funded':False,'original_block_after_funded':True,'whole_function_score':.3476082995964823,'TFIDF20_floor':.35,'block_score':.9769644016846665,'sharedops_report':{'label':'duplicate','score':.8},'concept_report':'unknown: separately queued but no root returned feed; no more calls','balanced_Haiku_report':'unknown','residual_gate_rejects':True,'source_confirmed_utility_loss':True,'sharedops_actual_report_counterfactual_loss':True,'no_retune_to_restore_survival':True},'round2':{'pairs':len(rows),'responses':len(keys),'counts':dict(counts),'original_profile_counts':dict(Counter(r['profile']for r in rows)),'new_residual_emissions':0,'audit_provider_positive_is_not_source_truth':True,'unexecuted_adaptive_reserve_pairs':20,'independent_source_case_links':str(ROOT/'reports/research-experiments/promotion/revised-source-c/private-map.jsonl')},'full_source_census':stages,'paired_query_transitions':transitions,'discovery_default':{'enabled':False,'blocks_enabled':False,'incremental_block_reports':0},'balanced_default':{'enabled':True,'blocks_enabled':False,'implicit_TFIDF20':True,'judge_model':'claude-haiku-5-5','policy':'shared-operations','max_tokens':2048,'report_at':.5},'balanced_with_explicit_blocks':{'cold_admission_diagnostics_only':True,'matched_model_answers':0,'real_persistent_PR_ledger_supplied':False,'held_reservation_exploration_displacements':20,'protected_baseline_displacements':0,'not_actual_report_losses':True},'source_receipts':[{'path':str(source_path),'sha256':sha(source_path)}],'full_gold_comparison_reused':str(LAB/'full-corpus-followup/span-v2-migration/paired-summary.json'),'implementation_commit':'dd0a448e027f1dd9984a2154da51e1e5982e9f3b'}
(OUT/'FINAL_EVIDENCE.json').write_text(json.dumps(summary,indent=2,sort_keys=True)+'\n');(OUT/'NO-MORE-CALLS.json').write_text(json.dumps({'status':summary['status'],'no_more_calls':True,'round1_fresh_owned_usd':summary['round1_fresh_owned_usd'],'round2_fresh_owned_usd':summary['round2_fresh_owned_usd'],'unexecuted_reserves_remain_unknown':True,'queued_RF14_concept_not_returned_do_not_dispatch':True},indent=2)+'\n');print('final evidence:',round(cost,8),'R2',dict(counts),'both minima met',summary['both_minima_met'])
