import datetime, hashlib, json, os, shutil, subprocess
from pathlib import Path
ROOT=Path('/home/reavus/projects/spt-core/spt-core')
TREE=ROOT/'.worktrees/consumer-linux-7890ead3'
TARGET=TREE/'target'
PROOF=ROOT/'.spt/preserved/304-handoff/consumer-linux-7890ead3'
ENV={k:v for k,v in os.environ.items() if not k.startswith(('OWL_','SPT_'))}
def utc(): return datetime.datetime.now(datetime.timezone.utc).isoformat()
def census():
    active=[]
    owned=[]
    for p in Path('/proc').iterdir():
        if not p.name.isdigit(): continue
        try:
            name=(p/'comm').read_text().strip()
            exe=os.readlink(p/'exe')
            row={'pid':int(p.name),'name':name,'exe':exe,'stat':(p/'stat').read_text(),'cmd':(p/'cmdline').read_bytes().replace(b'\0',b' ').decode(errors='replace')}
            if any(w in name for w in ('cargo','rustc','nextest','Runner.Worker')) or '/deps/' in exe: active.append(row)
            if exe.startswith(str(TARGET)+'/'): owned.append(row)
        except OSError: pass
    return {'utc':utc(),'free_bytes':shutil.disk_usage(TREE).free,'active':active,'owned_survivors':owned}
initial=census()
(PROOF/'cleanup-before.json').write_text(json.dumps(initial,indent=2)+'\n')
assert not initial['owned_survivors'], initial
argv=[str(ROOT/'.worktrees/consumer-linux-304-b8482445/target/debug/xtask'),'pool-release','--pool',str(TARGET)]
start=utc()
with (PROOF/'pool-release-cleanup.log').open('xb') as log:
    r=subprocess.run(argv,cwd=TREE,env=ENV,stdout=log,stderr=subprocess.STDOUT)
receipt={'command':argv,'start_utc':start,'end_utc':utc(),'exit':r.returncode,'log_sha256':hashlib.sha256((PROOF/'pool-release-cleanup.log').read_bytes()).hexdigest(),'reason':'First bookkeeping release was killed by producer disk-floor guard; safe cleanup-only release, no cargo/test retry.','environment_names':sorted(ENV)}
(PROOF/'pool-release-cleanup-receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
final=census()
final['source_sha']=subprocess.check_output(['git','rev-parse','HEAD'],cwd=TREE,env=ENV,text=True).strip()
final['source_status']=subprocess.check_output(['git','status','--porcelain=v1','--untracked-files=all'],cwd=TREE,env=ENV,text=True)
final['own_target_size_bytes']=int(subprocess.check_output(['du','-sb',str(TARGET)],env=ENV,text=True).split()[0])
final['pool_release_exit']=r.returncode
final['source_clean']=not final['source_status']
final['cache_retained']=True
(PROOF/'final-census.json').write_text(json.dumps(final,indent=2)+'\n')
print(json.dumps({'cleanup_release':receipt,'final':final}))
assert r.returncode==0 and not final['owned_survivors'] and final['source_clean'] and final['source_sha']=='7890ead39bb7f14ed44aaae44b0951f098ffe9ac'
