import os,json,subprocess,shutil,hashlib
from pathlib import Path
root=Path.cwd(); out=root/'.spt/preserved/deployah-rca-reclaim-20260911'; audit=json.loads((out/'audit.json').read_text(encoding='utf-8'))
assert not audit['inbound_links'] and not audit['scan_errors'] and not audit['matching_processes'] and not audit['active_builders']
assert not any(audit['target_environment'].values())
allowed={str(root/'.worktrees'/n/'target') for n in ['rca-base','rca-head','gate-293c']}
assert {r['path'] for r in audit['pools']}==allowed
results=[]
for row in audit['pools']:
 p=Path(row['path']); assert not row['internal_links'] and not row['possible_evidence']
 assert p.is_dir() and not os.path.isjunction(p) and not p.is_symlink()
 assert json.loads((p/'POOL-OWNER.json').read_text(encoding='utf-8'))==row['owner']
 ps="Get-CimInstance Win32_Process | Select-Object ProcessId,Name,ExecutablePath,CommandLine | ConvertTo-Json -Depth 3"
 procs=json.loads(subprocess.run(['powershell','-NoProfile','-Command',ps],capture_output=True,text=True,check=True).stdout)
 for proc in procs:
  text=(str(proc.get('ExecutablePath') or '')+' '+str(proc.get('CommandLine') or '')).lower()
  assert str(p.parent).lower() not in text, proc
  assert proc['Name'].lower() not in ['cargo.exe','rustc.exe','runner.worker.exe'], proc
 source=p.parent/'Cargo.toml'; beforehash=hashlib.sha256(source.read_bytes()).hexdigest()
 before=shutil.disk_usage('C:/').free
 print(json.dumps({'deleting':str(p),'logical_bytes':row['bytes'],'free_before':before}),flush=True)
 shutil.rmtree(p)
 after=shutil.disk_usage('C:/').free
 assert not p.exists() and hashlib.sha256(source.read_bytes()).hexdigest()==beforehash
 results.append({'path':str(p),'logical_before':row['bytes'],'logical_after':0,'free_before':before,'free_after':after,'observed_gain':after-before,'source_cargo_sha256':beforehash,'source_preserved':True})
 (out/'reap-results.json').write_text(json.dumps(results,indent=2),encoding='utf-8');print(json.dumps(results[-1]),flush=True)
print('All three authorized target subtrees removed; enclosing source trees preserved.',flush=True)
