from ops import *
import datetime,re
job='20260926-contextra-linear-scale-r01'
assert cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()=='46f932b26a9a6d92f3f2d0b35100795db1d50de5'
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)==4 and all(p.endswith('.md') for p in paths)
cmd(['git','-C',str(REPO),'diff','--check'])
for p in paths:
    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
trial=json.loads((HERE/'scale/trial-result.json').read_text())
assert [s['level'] for s in trial['stages'] if s['status']=='PASS']==[1,2,4,8]
assert trial['errors']==[{'type':'RuntimeError','reason':'CHANNEL_ERROR_8'}] and trial['cleanup']['reaped']
assert all(not p['last_cleanup']['forced'] and p['last_cleanup']['child_reaped'] and p['last_cleanup']['diagnostic']['exit_code']==0
    for r in trial['cleanup']['states'].values() for p in r['providers'].values())
for lane in json.loads((HERE/'lanes-v2.json').read_text()):
    assert lane['completed']==lane['accepted'] and not lane['late']
    for d in lane['durations'].values():assert d['count']==sum(d['histogram']) and min(d['histogram'])>=0
final=json.loads((HERE/'final-state.json').read_text())
assert final['states']=={'stopped':36} and final['children']==0 and final['wss'] and final['linear'] and not final['freshness']
current=api('/api/v1/streams')['streams']
assert all(r['state']=='stopped' and not r.get('cleanup_pending') for r in current)
save('verification.json',dict(python='3.12',targeted_tests=24,
    initial_test_attempt='docker exec loader errors2: image excludes tests; corrected by readonly repository mount',
    stages_completed=[1,2,4,8],stage16='expansion interrupted; no steady benchmark',
    attempted_channels=11,reaped_children=33,failure='Artifact global DB row lock timeout, Event handoff rejection',
    source_build_changes=False,default_scope='test persistent Compose flags only',
    final=final,files=paths,portfolio='LOW: configuration promotion/measurement documentation; no new code milestone'))
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='Contextra B/OFF test 기본값 전환과 복합 단계 계측',
    results=['기존image/source재사용,persistent B/Off정합화,Python3.12표적24PASS',
      '복합1/2/4/8각30초;8채널평균완료Pose4.22/Fire5.35/Crowd5.50,Redis1.82/1.96/1.89FPS',
      '16확장중DB예약행lock timeout->EventCapture/인계실패;11채널시도33child정상reap,16benchmark없음',
      'batch분포/Queue/compute/자원/자연Artifact원자료분리,튜닝0'],
    verify=['36stopped/child0/WSS연결/4모델READY/ArtifactHTTPOn/CAS복귀/비대상보존',
      'source image hashes,diff/links,counter/histogram,batch denominator checks'],commits=[],
    remaining=['Artifact 공통예약행 lock holder와 critical section 원인','16채널미측정','실제Web수용과영상재생품질미확인'])
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','docs(runtime): B 기본값과 복합 부하 측정 및 DB lock 실패 기록',
 '--message','Why=사용자 승인 B/Off 기본값에서 복합1~16채널 처리량과batch분포의 객관적 판단자료가 필요했다.',
 '--message','What=test private Compose 두옵션을B/Off로승격하고 기존image/helper로1/2/4/8측정,16확장실패SOT와영역별해석을분리했다.',
 '--message','Impact=코드/build/모델/instance/batch/decoder 변경없음. Runtime persistent B/Off유지,시험채널설정CAS복귀,16채널수용완료아님.',
 '--message','Verify=Python3.12표적24PASS,1/2/4/8각30초.16확장중camera8Pose가Artifact DB lock timeout뒤Event인계실패.11채널시도33child reap/exit0/unforced.36stopped/4모델READY/WSS연결/ArtifactHTTPOn.',
 '--message','Rollback=private 이전Compose/image보존.명시승인시Stop/reap후전체Compose조합에서A/On복귀.자동rollback재Start없음.공통예약행lock경계와16재시험은후속이다.',
 '--verify','24 targeted Python3.12 PASS; persistent/runtime B OFF; source/image unchanged',
 '--verify','1/2/4/8 measurements; 16 blocked by DB lock; 33 children reaped; CAS restore/WSS/readiness/non-target 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]))
