import datetime, json, os, shutil, stat, subprocess
from pathlib import Path
ROOT=Path('/home/reavus/projects/spt-core/spt-core')
PROOF=ROOT/'.spt/preserved/304-handoff/consumer-linux-7890ead3'
TARGET=ROOT/'.worktrees/consumer-linux-7890ead3/target'
TREE=ROOT/'.worktrees/consumer-linux-S2-527cd8e8'
SHA='7890ead39bb7f14ed44aaae44b0951f098ffe9ac'
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()
classification=json.loads((PROOF/'closed-target-classification.json').read_text())
row=next(row for row in classification['targets'] if row['path']==str(TARGET))
assert not classification['inbound_links'] and not classification['process_references'] and not classification['scan_errors'] and not row['outbound_links']
st=TARGET.lstat()
assert stat.S_ISDIR(st.st_mode) and not TARGET.is_symlink() and TARGET.resolve()==TARGET and st.st_ino==row['inode'] and st.st_dev==row['device']
active=[]
for p in Path('/proc').iterdir():
    if not p.name.isdigit(): continue
    try:
        name=(p/'comm').read_text().strip()
        exe=os.readlink(p/'exe')
        if any(w in name for w in ('cargo','rustc','nextest','Runner.Worker')) or '/deps/' in exe or exe.startswith(str(TARGET)+'/'): active.append({'pid':int(p.name),'name':name,'exe':exe})
    except OSError: pass
assert not active,active
size=int(subprocess.check_output(['du','-sb',str(TARGET)],env=ENV,text=True).split()[0])
reclaim={'authority':'doyle MNRQVISD via Main','path':str(TARGET),'start_utc':utc(),'apparent_bytes_before':size,'allocated_bytes_from_classification':row['allocated_bytes_unique'],'free_bytes_before':shutil.disk_usage(ROOT).free,'operation':'shutil.rmtree only this validated real target subtree','source_worktree_preserved':True,'proof_preserved':True,'active_before':active}
(PROOF/'approved-reclaim-before.json').write_text(json.dumps(reclaim,indent=2)+'\n')
shutil.rmtree(TARGET)
reclaim.update(end_utc=utc(),free_bytes_after=shutil.disk_usage(ROOT).free,target_absent=not TARGET.exists())
reclaim['measured_free_increase_bytes']=reclaim['free_bytes_after']-reclaim['free_bytes_before']
(PROOF/'approved-reclaim.json').write_text(json.dumps(reclaim,indent=2)+'\n')
WARM=PROOF/'warm-attempt'
WARM.mkdir(exist_ok=False)
results=[]
def run(argv):
    start=utc()
    p=subprocess.run(argv,cwd=TREE,env=ENV,capture_output=True,text=True)
    results.append({'command':argv,'start_utc':start,'end_utc':utc(),'exit':p.returncode,'stdout':p.stdout,'stderr':p.stderr})
    (WARM/'takeover-setup.json').write_text(json.dumps({'authority':'doyle FXGOSVTP and MNRQVISD via Main','tree':str(TREE),'sha':SHA,'commands':results},indent=2)+'\n')
    assert p.returncode==0,results[-1]
    return p.stdout.strip()
assert run(['git','rev-parse','HEAD'])=='527cd8e8d7ef192892d5630fce10e69a6d811893'
assert not run(['git','status','--porcelain=v1','--untracked-files=all'])
assert (TREE/'target').is_dir() and not (TREE/'target').is_symlink()
owner=json.loads((TREE/'target/POOL-OWNER.json').read_text())
assert owner['owner_tree']==str(TREE) and not owner.get('lane'),owner
run(['git','checkout','--detach',SHA])
assert run(['git','rev-parse','HEAD'])==SHA
assert not run(['git','status','--porcelain=v1','--untracked-files=all'])
admission={'utc':utc(),'sha':SHA,'source_clean':True,'free_bytes':shutil.disk_usage(ROOT).free,'floor_bytes':32*1024**3,'target':str(TREE/'target'),'target_preserved':True,'pool_record_before':owner,'producer_started':False}
(WARM/'fresh-admission.json').write_text(json.dumps(admission,indent=2)+'\n')
print(json.dumps({'reclaim':reclaim,'admission':admission}))
