from ops import *
import datetime,re
job='20260926-contextra-provider-scale-r01'
assert cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()=='e74cc54373ef71514247ea4d619c89e4574b1810'
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)==12
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(),target
image=json.loads((HERE/'image-d086494ab6.json').read_text())
for p,h in image['hashes'].items():assert hashlib.sha256((REPO/p).read_bytes()).hexdigest()==h
final=json.loads((HERE/'final-state.json').read_text());assert final['stopped']==36 and not final['provider_pids'] and final['gateway']=='stopped'
trial=json.loads((HERE/'attempt2'/'trial-result.json').read_text());assert trial['cleanup']['reaped']
assert [s['level'] for s in trial['stages'] if s['status']=='PASS']==[1,2,4,8]
summary=json.loads((HERE/'summary-v2.json').read_text())
assert all(s['observed_children']==s['expected_children'] for s in summary)
for lane in json.loads((HERE/'lanes-v2.json').read_text()):
    assert lane['completed']-lane['late']==lane['accepted']
    for duration in lane['durations'].values():
        assert duration['count']==sum(duration['histogram']) and min(duration['histogram'])>=0
artifacts=json.loads((HERE/'artifact-evidence.json').read_text())
assert len(artifacts)==83 and sum(r['state']=='FAILED' for r in artifacts)==6
assert sum((r.get('diagnostic') or {}).get('returncode')==-6 for r in artifacts)==3
save('verification.json',dict(cpu_tests=39,python='3.12',measured_levels=[1,2,4,8],unmeasured_levels=[16,17],
     natural_artifacts=dict(total=83,failed=6,sigabrt=3),offline='NOT RUN: natural failure reproduced',
     histogram_and_counter_sanity=True,independent_review='one read-only agent; interpretation limits retained',
     final=final,files=paths,portfolio='MEDIUM improvement and scale acceptance pending'))
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 실패 경계 확인',
 results=['계측39PASS;1/2/4/8 각30초 측정과 순수SOT/영역별분석/독립교차검토 분리',
 '2→4 수락악화,4→8 완료량감소와99%이상폐기;CPU실행대기 및Triton Queue/compute 동반증가',
 '16확장 중10번째의Pose 최초응답전stall/강제회수로 중단;16/17미측정',
 '자연Artifact83건 중6실패,3건기존avdec_h264 assertion;decoder변경/추가offline재현없음'],
 verify=['Python3.12 targeted39 PASS;numeric histogram/counter sanity;source/image hash match',
 '전체child회수,같은image정상재기동으로관리오류정리,36stopped/4모델READY/Artifact HTTP On,Gateway/WSS안전보류'],
 commits=[],remaining=['startup-stall/강제종료경계와16/17시험미완료','공유경합원인기여율미확정;capture크기정합화후보미적용','Artifact병렬decoder실패미해결','Gateway재개및실제브라우저수용대기'])
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','feat(diagnostics): 복합 채널 부하 계측과 단계별 한계 기록',
 '--message','Why=provider-process 구조의 다채널 한계와 소프트웨어 개선 후보를 판단하고 기존 Artifact 병렬 실패를 분리 관측할 필요가 있었다.',
 '--message','What=bounded histogram/acceptance silence/Redis 성공전송 counter/renderer 시간 계측과 read-only probe를 추가했다. 조건과 수치SOT,영역별 해석,독립검토를 분리해 기록했다.',
 '--message','Impact=모델/instance/batch/FPS/100ms/decoder 불변. 상세진단은 기존metrics API의 최대60초 창에서 수집한다. 기존 활성화설정은 복귀했으나 비활성 Fire 기본값 명시화가 남는다.',
 '--message','Verify=Python3.12 표적39PASS,1/2/4/8 각30초.16확장 중10번째Pose 첫응답전stall/강제종료로 중단하여16/17미측정.자연Artifact83중6실패/3SIGABRT.최종36stopped/4모델READY/Artifact On,Gateway/WSS안전보류.',
 '--message','Rollback=이전image/config와원자료보존.자동rollback/재Start는없다.같은계측image로관리상태만정상복구했다.후속은capture크기정합화후보와startup/회수경계검토이며추가튜닝은별도승인이다.',
 '--verify','targeted39 PASS; diff/link/hash/histogram checks; numeric SOT and read-only independent review',
 '--verify','scale1/2/4/8 measured,16 expansion failed before completion,17 NOT RUN;all child reaped,Gateway safety hold',
 '--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]))
