import os,json,subprocess,shutil
from pathlib import Path
root=Path.cwd(); out=root/'.spt/preserved/deployah-rca-reclaim-20260911'
pools=[root/'.worktrees/rca-base/target',root/'.worktrees/rca-head/target',root/'.worktrees/gate-293c/target']
errors=[]; links=[]; rows=[]
for base in [root,Path('C:/actions-runner')]:
 for current,dirs,files in os.walk(base,followlinks=False,onerror=lambda e:errors.append(str(e))):
  keep=[]
  for name in dirs+files:
   p=Path(current)/name
   if os.path.isjunction(p) or p.is_symlink():
    resolved=os.path.normcase(os.path.realpath(p))
    if any(resolved==os.path.normcase(str(t)) or resolved.startswith(os.path.normcase(str(t))+os.sep) for t in pools):links.append({'path':str(p),'target':resolved})
   elif name in dirs:keep.append(name)
  dirs[:]=keep
for p in pools:
 assert p.is_dir() and not os.path.isjunction(p) and not p.is_symlink()
 owner=json.loads((p/'POOL-OWNER.json').read_text(encoding='utf-8'))
 assert os.path.normcase(owner['owner_tree'])==os.path.normcase(str(p.parent))
 size=0; suspicious=[]; internal_links=[]
 for current,dirs,files in os.walk(p,followlinks=False,onerror=lambda e:errors.append(str(e))):
  for name in dirs+files:
   q=Path(current)/name
   if os.path.isjunction(q) or q.is_symlink():internal_links.append(str(q))
  for name in files:
   q=Path(current)/name;size+=q.stat().st_size
   if q.suffix.lower() in ['.dmp','.log','.etl','.md','.patch','.diff']:suspicious.append(str(q))
 rows.append({'path':str(p),'bytes':size,'owner':owner,'internal_links':internal_links,'possible_evidence':suspicious})
ps="Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine | ConvertTo-Json -Depth 3"
proc=subprocess.run(['powershell','-NoProfile','-Command',ps],capture_output=True,text=True,check=True)
processes=json.loads(proc.stdout); matches=[]; builders=[]
for p in processes:
 text=(str(p.get('ExecutablePath') or '')+' '+str(p.get('CommandLine') or '')).lower()
 if any(str(t.parent).lower() in text for t in pools):matches.append(p)
 if p['Name'].lower() in ['cargo.exe','rustc.exe','runner.worker.exe']:builders.append(p)
psenv="@{Process=[Environment]::GetEnvironmentVariable('CARGO_TARGET_DIR','Process');User=[Environment]::GetEnvironmentVariable('CARGO_TARGET_DIR','User');Machine=[Environment]::GetEnvironmentVariable('CARGO_TARGET_DIR','Machine')} | ConvertTo-Json"
envs=json.loads(subprocess.run(['powershell','-NoProfile','-Command',psenv],capture_output=True,text=True,check=True).stdout)
result={'pools':rows,'scan_roots':[str(root),'C:/actions-runner'],'inbound_links':links,'scan_errors':errors,'matching_processes':matches,'active_builders':builders,'target_environment':envs,'free_bytes':shutil.disk_usage('C:/').free}
(out/'audit.json').write_text(json.dumps(result,indent=2),encoding='utf-8');print(json.dumps(result),flush=True)
