from ops import *
import datetime,re
job='20260923-contextra-artifact-mixed-r02'
assert cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()=='dd5948af48d6add3a56a237fb4a6163ba737ec21'
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)==5
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-intent.json').read_text())['hashes'].items():assert hashlib.sha256((REPO/p).read_bytes()).hexdigest()==h
final=json.loads((HERE/'final-state.json').read_text())
assert final['wss'] and final['stopped']==35 and not final['diagnostics_enabled']
live=json.loads((HERE/'closeout-live-state.json').read_text())
save('verification-r02.json',dict(cpu_tests=42,python='3.12',artifact_baseline=6,artifact_no_direct=6,artifact_fix_proven=False,
 phases=['medium10','plus-pose','plus-fire'],crowd='BLOCKED_CHILD_EXIT',initial_restored=final,latest=live,files=paths,portfolio='LOW diagnostic-only'))
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='Artifact decoder 설정 비교와 PR13 provider별 혼합 부하 계측',
 results=['Artifact baseline/설정변경 각6PASS; 실패미재현으로 수정효과 미입증 및 decoder변경0',
 'Medium10에 Pose/Fire 추가시 응답폐기4.35/19.59/36.68%; 완료처리량은99.49/99.55/97.69FPS',
 'Crowd 기동시 여러child_exit로 시험중단; child/writer회수 확인; 근본원인 미확정'],
 verify=['Python3.12 표적42PASS, provider별 Frame/copy scope 격리; 실제3단계30초 비교',
 '진단image/source hash 일치,진단Off/원본설정보존/WSS연결/4모델READY/Artifact HTTP On',
 '이전r01 Receipt의35stopped는당시readback. 관제복구후6재Start를각1회Stop했으나재실행되어최신29stopped/6running'],
 commits=[],remaining=['관제추가Start중단/사용자Stop으로종료상태확보','Artifact 실패재현/실제renderer diagnostic 확보','Crowd 기동중 동시child 종료의 exitcode/terminal 원인 확인','자원별 지연기여도와 수락정책 후속판단'])
save('report-receipt-r02.json',receipt)
print(cmd(['codex-report-receipt','--profile','ltb1021','--session-alias','work-session','--receipt',str(HERE/'report-receipt-r02.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): provider별 지연 계측 분리와 혼합 부하 중단 근거 기록',
 '--message','Why=혼합 provider의 동일 Frame 계측 충돌을 제거하고 Artifact 설정 변경의 실제 효과와 응답 수락 손실을 구분해야 했다.',
 '--message','What=고정 provider별 bounded 진단과 thread-local copy scope 및 회귀 테스트를 추가했다. Artifact baseline/direct-rendering 비교와 Medium10에 Pose/Fire 추가30초 비교를 기록했다.',
 '--message','Impact=추론/instance/batch/FPS/deadline/threshold/decoder 계약불변. 진단image 반영,기본Off와원래채널설정보존. Crowd warmup child_exit와 Artifact 미해결은 완료판정에서 제외한다.',
 '--message','Verify=Python3.12 표적42PASS. Artifact 양쪽6/6성공으로 효과미입증. Medium응답폐기4.35->19.59->36.68%,완료99.49->97.69FPS. Crowd기동실패후 child/writer회수,WSS연결,4모델READY,Artifact HTTP On. 관제복구후6채널재Start로최신29stopped/6running이며종료상태확보대기.',
 '--message','Rollback=이전pr13-timing image와전체Compose/env/private설정보존. 명시승인후Stop/reap및image한값복귀로진단코드제거가능. 이번자동rollback/자동채널재Start는없다.',
 '--verify','42 targeted Python3.12 unittest tests PASS; git diff --check PASS',
 '--verify','Artifact 6+6 offline PASS but fix unproven; three 30s mixed windows; Crowd warmup failed; Web reStart leaves29stopped/6running, WSS/models ready',
 '--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]))
old=out.parent/'20260923-contextra-artifact-mixed-r01'/'manifest.json'
print(cmd(['codex-git-closeout','supersede','--old-manifest',str(old),'--old-expect-plan-hash',json.loads(old.read_text())['plan_hash'],
 '--replacement-manifest',str(mf),'--replacement-expect-plan-hash',json.loads(mf.read_text())['plan_hash']]))
print(cmd(['codex-git-closeout','batch-present','--batch-manifest',str(batch),'--expect-batch-plan-hash',h]))
