import os, json, subprocess, shutil, datetime, hashlib
from pathlib import Path
ROOT=Path('/home/reavus/projects/spt-core/spt-core')
PROOF=ROOT/'.spt/preserved/304-handoff/consumer-linux-7890ead3'
TREE=ROOT/'.worktrees/consumer-linux-7890ead3'
SHA='7890ead39bb7f14ed44aaae44b0951f098ffe9ac'
PARENT='527cd8e8d7ef192892d5630fce10e69a6d811893'
env={k:v for k,v in os.environ.items() if not k.startswith(('SPT_','OWL_'))}
def utc(): return datetime.datetime.now(datetime.timezone.utc).isoformat()
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:
            active.append({'pid':int(p.name),'name':name,'exe':exe,'stat':(p/'stat').read_text()})
    except OSError: pass
preflight={'utc':utc(),'free_bytes':shutil.disk_usage(ROOT).free,'active':active,'tree_existed':TREE.exists(),'target_existed':(TREE/'target').exists(),'inherited_environment_names':sorted(os.environ),'scrubbed_environment_names':sorted(env),'bundle_sha256':hashlib.sha256((PROOF/'candidate.bundle').read_bytes()).hexdigest()}
(PROOF/'remote-preflight.json').write_text(json.dumps(preflight,indent=2)+'\n')
assert not active and preflight['free_bytes']>=32*1024**3 and not TREE.exists(), preflight
results=[]
def run(argv, cwd=ROOT):
    start=utc()
    r=subprocess.run(argv,cwd=cwd,env=env,capture_output=True,text=True)
    row={'command':argv,'start_utc':start,'end_utc':utc(),'exit':r.returncode,'stdout':r.stdout,'stderr':r.stderr}
    results.append(row)
    (PROOF/'worktree-setup.json').write_text(json.dumps({'sha':SHA,'parent':PARENT,'target_existed':False,'results':results},indent=2)+'\n')
    assert r.returncode==0,row
    return r.stdout.strip()
run(['git','bundle','verify',str(PROOF/'candidate.bundle')])
run(['git','fetch',str(PROOF/'candidate.bundle'),'refs/heads/fix/297-enforcement-shape:refs/heads/consumer-linux-7890ead3'])
assert run(['git','rev-parse','consumer-linux-7890ead3'])==SHA
assert run(['git','rev-parse','consumer-linux-7890ead3^'])==PARENT
run(['git','worktree','add',str(TREE),'consumer-linux-7890ead3'])
assert run(['git','rev-parse','HEAD'],TREE)==SHA
assert not run(['git','status','--porcelain=v1','--untracked-files=all'],TREE)
print(json.dumps({'sha':SHA,'parent':PARENT,'tree':str(TREE),'free_bytes':shutil.disk_usage(ROOT).free,'active':active,'bundle_sha256':preflight['bundle_sha256']}))
