from ops import *
import datetime,re
job='20260923-contextra-pr13-ab-r01'
assert cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()=='f91c9ffd649136e0be6520746af9a0687157cbc5'
assert not cmd(['git','-C',str(REPO),'diff','--cached','--name-only']).strip()
paths=sorted(set(cmd(['git','-C',str(REPO),'diff','--name-only']).splitlines()+cmd(['git','-C',str(REPO),'ls-files','--others','--exclude-standard']).splitlines()))
assert len(paths)==11
cmd(['git','-C',str(REPO),'diff','--check'])
for p in paths:
    if not p.endswith('.md'):continue
    for target in re.findall(r'\]\(([^)]+)\)',(REPO/p).read_text()):
        if '://' not in target and not target.startswith('#'):assert ((REPO/p).parent/target.split('#')[0]).exists()
for p,h in json.loads((HERE/'build-current-intent.json').read_text())['hashes'].items():assert hashlib.sha256((REPO/p).read_bytes()).hexdigest()==h
save('verification.json',dict(cpu_tests=39,python='3.12',medium_single_and_ten_old_current='PASS',
    original_image_config_restored=True,artifact_offline=dict(single_success=3,concurrent_success=2,concurrent_failed=2),
    defect_fixed=False,portfolio='LOW: analysis/diagnostic only',files=paths))
receipt=dict(schema_version='ltb1021.codex_hub.report_receipt.v1',receipt_id=job,
 timestamp=datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).isoformat(),
 session_alias='work-session',task='PR13 전후 Medium 동일조건 비교와 Artifact decoder 실패 재현',
 results=['구버전/current Medium10 완료100.07/99.19FPS; callback복사20.26/20.66ms;90%폐기미재현',
  '공통avdec_h264 폭assertion/SIGABRT와INTRUSION decoder오류offline재현;수정은후속'],
 verify=['Python3.12 표적39PASS;각단계30초및정상Stop/reap',
  '시작image/전체Compose/원본설정정확복귀;35채널stopped/WSS연결/모델4종READY/Artifact On HTTP On'],
 commits=[],remaining=['혼합모델 부하의 CPU/GPU 지연기여도 확인','Artifact decoder 수정후재검증','신규계측 최종Runtime미반영'])
save('report-receipt.json',receipt)
print(cmd(['codex-report-receipt','--profile','ltb1021','--session-alias','work-session','--receipt',str(HERE/'report-receipt.json')]))
out=Path('/tmp/codex/ltb1021/git-closeout')/job;out.mkdir(mode=0o700)
mf=out/'manifest.json'
args=['codex-git-closeout','prepare','--repository',str(REPO),'--output',str(mf),'--job-id',job,
 '--profile','ltb1021','--session-alias','work-session',
 '--title','chore(runtime): PR13 전후 지연 비교와 Artifact decoder 진단 추가',
 '--message','Why=Medium 다채널 누락을 기존 경로와 같은 조건에서 비교하고 FIRE로 보고된 영상 생성 실패의 실제 경계를 확인해야 했다.',
 '--message','What=opt-in bounded pipeline/copy wall-CPU 계측과 renderer 단계/종료코드/stderr8KiB 기록을 추가하고 기존/current image로1/10채널을 비교했다.',
 '--message','Impact=성능정책과모델/instance/batch/FPS/threshold불변. 진단image는임시비교에만사용하고시작image와원본설정으로복귀.최종Runtime신규계측미반영.',
 '--message','Verify=Python3.12 표적39 PASS. Medium10 완료100.07/99.19FPS,PR13응답폐기약5.2%. Artifact 단독3성공/동시4중2실패로decoder assertion재현.35채널stopped/reap,WSS연결,4모델READY.90%누락/16채널혼합원인및수정미확정.',
 '--message','Rollback=운영은이미작업시작pr13-timing image와전체Compose/env로정확복귀.계측source는이commit revert로제거가능하며원본Artifact와privateevidence는보존한다.',
 '--verify','39 targeted Python3.12 tests PASS; four Medium A/B windows and Stop/reap PASS',
 '--verify','Artifact decoder failure reproduced offline; not fixed; original image/config restored and WSS/model readiness verified',
 '--expires-in-seconds','86400']
for p in paths:args+=['--path',p]
print(cmd(args))
batch=out/'batch.json'
print(cmd(['codex-git-closeout','batch-prepare','--output',str(batch),'--batch-id',job,'--profile','ltb1021','--session-alias','work-session','--expected-group-count','1','--repository-label','contextra-analytics','--manifest',str(mf),'--expect-plan-hash',json.loads(mf.read_text())['plan_hash'],'--expires-in-seconds','86400']))
h=json.loads(batch.read_text())['plan_hash']
print(cmd(['codex-git-closeout','batch-plan','--batch-manifest',str(batch),'--expect-batch-plan-hash',h]))
print(cmd(['codex-git-closeout','batch-present','--batch-manifest',str(batch),'--expect-batch-plan-hash',h]))
