import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess

os.umask(0o077)
ROOT=Path(__file__).parent
def write(name, value):
    with (ROOT/name).open('x') as f:json.dump(value,f,indent=2)
def call(args,timeout=30):
    p=subprocess.run(args,capture_output=True,text=True,timeout=timeout)
    return {'returncode':p.returncode,'stdout':p.stdout,'stderr':p.stderr}
def runtime():
    ids=subprocess.check_output(['docker','ps','-aq'],text=True).split()
    ds=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
    return sorted([{'id':d['Id'],'image':d['Image'],'pid':d['State']['Pid'],
                    'started':d['State']['StartedAt'],'running':d['State']['Running']} for d in ds],key=lambda x:x['id'])
before=shutil.disk_usage('/').free
state=runtime()
write('before.json',{'free_bytes':before,'runtime':state})
tag='contextra-analytics:smoke-7262bce'
image=json.loads(subprocess.check_output(['docker','image','inspect',tag],text=True))[0]
assert image['Id']=='sha256:9894a2ba4c5039f518601d68f18d134b132f015e1abfbad65ca6f8ce0fcc5ecf'
assert not subprocess.check_output(['docker','ps','-aq','--filter','ancestor='+tag],text=True).strip()
write('image-metadata.json',{'id':image['Id'],'tags':image['RepoTags'],'layers':image['RootFS']['Layers']})
r=call(['docker','image','rm',tag],120);write('image-removal.json',r)
after_image=shutil.disk_usage('/').free
# No forced deletion, pruning, or retry when Docker refuses this exact image.
r=call(['journalctl','--rotate','--vacuum-size=1G'],60);write('journal-vacuum.json',r)
after_journal=shutil.disk_usage('/').free
old=Path('/tmp/codex/ltb1021/2026-09-09_contextra-medium-video_r01')
assert (old/'medium-fp32-vs-fp16.mp4').is_file() and (old/'receipt.json').is_file()
deleted=[]
for name,size in [('comparison.rgb',700416000),('frames.rgb',552960000)]:
    p=old/name;st=p.stat()
    assert p.is_file() and not p.is_symlink() and st.st_size==size and st.st_nlink==1
    check=call(['fuser',str(p)])
    assert check['returncode']==1 and not check['stdout'].strip() and not check['stderr'].strip(),'FILE_BUSY_OR_CHECK_FAILED'
    h=hashlib.sha256()
    with p.open('rb') as f:
        for b in iter(lambda:f.read(1024**2),b''):h.update(b)
    assert p.stat().st_mtime_ns==st.st_mtime_ns and p.stat().st_size==size
    record={'path':str(p),'size':size,'sha256':h.hexdigest(),'reason':'regenerable decoded RGB; final MP4 and evidence retained'}
    write(name+'.intent.json',record)
    p.unlink();deleted.append(record)
after=shutil.disk_usage('/').free
final=runtime()
write('result.json',{'free_before_bytes':before,'free_after_bytes':after,'gained_bytes':after-before,
 'image_delta_bytes':after_image-before,'journal_delta_bytes':after_journal-after_image,
 'temporary_delta_bytes':after-after_journal,'deleted_temporary':deleted,
 'runtime_preserved':state==final,'other_images_cache_volumes':'UNCHANGED','full_export':'NOT_RETRIED'})
print((ROOT/'result.json').read_text())
