"""Replay retrospective prompt coverage and all matching stages from saved masks."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import numpy as np
from r112_grouped_baseline import iou_matrix,match
R=Path(__file__).resolve().parents[1];B=R/'results/r112/grouped-baseline';O=R/'results/r112/grouped-prompt-diagnostic';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());assert d['protocol_sha256']==sha(O/'protocol.json') and d['script_sha256']==sha(R/'research/r112_grouped_prompt_diagnostic.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
baseline=json.loads((B/'results.json').read_text());assert len(baseline['records'])==len(d['records'])==48
for a,b in zip(baseline['records'],d['records']):
 assert a['scene_id']==b['scene_id'];path=B/a['archive'];assert sha(path)==a['archive_sha256']==b['archive_sha256'];z=np.load(path);sh=tuple(z['mask_shape']);masks=np.unpackbits(z['mask_bits'])[:np.prod(sh)].reshape(sh).astype(bool);rh=tuple(z['reference_shape']);refs=np.unpackbits(z['reference_bits'])[:np.prod(rh)].reshape(rh).astype(bool);ids=np.flatnonzero(refs.sum((1,2))>=50);iou=iou_matrix(refs,masks[:256]);points=z['points']
 for n in (64,256):
  saved=b['policies'][str(n)];grid=points[:n];covered=refs[:,grid[:,1],grid[:,0]].any(1);assert saved['references']==len(ids) and saved['grid_covers']==int(covered[ids].sum()) and saved['grid_covered_indices']==ids[covered[ids]].tolist() and saved['raw_candidate_exists_for_support']==int((iou[ids,:n]>=.5).any(1).sum());raw=list(range(n));eligible=[j for j in raw if z['sam_eligible'][j]];kept=a['policies'][f'sam{n}']['ranking']
  for name,rank in [('raw_oracle',raw),('eligible_oracle',eligible),('kept_oracle',kept),('top30',kept[:30])]:
   pairs=match(iou,ids,rank,.5);assert saved['stages'][name]=={'matched':len(pairs),'assignments':pairs}
for n in ('64','256'):
 rows=[x['policies'][n] for x in d['records']];assert d['summary'][n]=={'references':sum(x['references'] for x in rows),'grid_covers':sum(x['grid_covers'] for x in rows),'raw_candidate_exists_for_support':sum(x['raw_candidate_exists_for_support'] for x in rows),'stages':{k:sum(x['stages'][k]['matched'] for x in rows) for k in ('raw_oracle','eligible_oracle','kept_oracle','top30')}}
out={'scenes_checked':48,'checks':'Recomputed grid coverage, candidate existence and reference-assisted matching from archived masks with shared score helpers. No model inference replay, independent reference masks or real-world validation.'};(O/'verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
