import os,sys,json,stat,hashlib,shutil,time
from pathlib import Path
root=Path('/home/reavus/projects/spt-core/spt-core')
tree=root/'.worktrees/gate-r3-25e60015'
target=tree/'target'
proof=root/'.spt/preserved/hertz-reclaim-AJM6OBJM'
proof.mkdir(exist_ok=True)
def digest(p):
 h=hashlib.sha256()
 with p.open('rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
def save(name,data):
 with (proof/name).open('x') as f:json.dump(data,f,indent=2)
def census():
 active=[];own=[];errors=[];control=False
 names={'cargo','cargo-nextest','rustc','rustdoc','clippy-driver','xtask','cmake','ninja'}
 for p in Path('/proc').iterdir():
  if not p.name.isdigit():continue
  try:
   uid=p.stat().st_uid;comm=(p/'comm').read_text().strip()
   if int(p.name)==os.getpid():control=True
   exe='';cwd='';cmd=''
   if True:
    cmd=(p/'cmdline').read_bytes().replace(b'\x00',b' ').decode(errors='replace')
    try:exe=os.readlink(p/'exe')
    except FileNotFoundError:pass
    try:cwd=os.readlink(p/'cwd')
    except FileNotFoundError:pass
   row={'pid':int(p.name),'comm':comm,'exe':exe,'cwd':cwd,'cmd':cmd}
   if comm in names or ('/target/' in exe and ('/debug/' in exe or '/release/' in exe)):active.append(row)
   if str(target) in exe or cwd==str(tree) or cwd.startswith(str(tree)+'/') or (str(target) in cmd and int(p.name)!=os.getpid()):own.append(row)
  except FileNotFoundError:continue
  except PermissionError as e:
   if True:errors.append(str(e))
 return {'active':active,'own':own,'errors':errors,'self_positive_control':control,'at':time.time()}
def inspect():
 st=target.lstat();assert stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode)
 assert target.resolve()==target and not target.is_mount()
 owner=json.loads((target/'POOL-OWNER.json').read_text());assert owner['owner_tree']==str(tree) and owner['lane_label']=='hertz-gate-r3-linux'
 holder_exists=(Path('/proc')/str(owner['holder_pid'])).exists();assert not holder_exists,'holder PID still exists'
 inbound=[];sweep_errors=[];symlinks=0
 def walkerr(e):sweep_errors.append(str(e))
 for base,dirs,files in os.walk('/home/reavus/projects',followlinks=False,onerror=walkerr):
  for name in dirs+files:
   p=Path(base)/name
   if p.is_symlink():
    symlinks+=1
    try:
     resolved=p.resolve()
     if resolved==target or target in resolved.parents:inbound.append({'path':str(p),'resolved':str(resolved)})
    except (OSError,RuntimeError) as e:sweep_errors.append(str(e))
 assert not inbound and not sweep_errors,(inbound,sweep_errors)
 mounts=[]
 for line in Path('/proc/self/mountinfo').read_text().splitlines():
  m=line.split()[4].replace('\\040',' ')
  if m==str(target) or m.startswith(str(target)+'/'):mounts.append(m)
 assert not mounts,mounts
 count=0;apparent=0;allocated=0;seen=set();measure_errors=[]
 for base,dirs,files in os.walk(target,followlinks=False,onerror=lambda e:measure_errors.append(str(e))):
  for name in ['.']+files+ [x for x in dirs if (Path(base)/x).is_symlink()]:
   p=Path(base)/name;s=p.lstat();key=(s.st_dev,s.st_ino)
   if key in seen:continue
   seen.add(key);count+=1;apparent+=s.st_size;allocated+=s.st_blocks*512
 assert not measure_errors,measure_errors
 manifest=root/'.spt/preserved/hertz-r3-linux-evidence.MANIFEST.sha256';receipts=[]
 for line in manifest.read_text().splitlines():
  expected,rel=line.split(None,1);p=root/rel.strip();actual=digest(p);assert actual==expected,str(p)
  receipts.append({'path':str(p),'bytes':p.stat().st_size,'sha256':actual})
 for base,dirs,files in os.walk(tree/'.spt',followlinks=False):
  for name in files:
   p=Path(base)/name;assert not p.is_symlink();receipts.append({'path':str(p),'bytes':p.stat().st_size,'sha256':digest(p)})
 for name in ['POOL-OWNER.json','.rustc_info.json','CACHEDIR.TAG']:
  p=target/name
  if p.exists():shutil.copy2(p,proof/('target-'+name))
 sample=census();assert sample['self_positive_control'] and not sample['active'] and not sample['own'] and not sample['errors'],sample
 result={'authority':'AJM6OBJM','target':str(target),'target_identity':[st.st_dev,st.st_ino],'classification':'REALDIR','inbound_scope':'/home/reavus/projects, all entries, no directory symlink traversal','symlinks_inspected':symlinks,'inbound':inbound,'sweep_errors':sweep_errors,'nested_mounts':mounts,'owner':owner,'holder_pid_absent':not holder_exists,'source_head_and_clean':'operator-reported f6110c2a, clean; source not changed','size_before':{'apparent_bytes':apparent,'allocated_bytes':allocated,'unique_entries':count},'free_before':shutil.disk_usage(target).free,'receipt_manifest':str(manifest),'receipt_manifest_sha256':digest(manifest),'preserved_receipts':receipts,'census':sample,'at':time.time()}
 save('admission.json',result);print(json.dumps(result))
if sys.argv[1]=='inspect':inspect()
