from ops import *
import datetime,re
job='20260926-contextra-provider-linear-r01'
assert cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()=='cb7d2a81545921b6a1d1454a7387746bf33e8187'
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(),target
image=json.loads((HERE/'image-7d7a97e883.json').read_text())
first=json.loads((HERE/'image-c1e0fa2fe0.json').read_text())
assert [p for p,h in first['hashes'].items() if h!=image['hashes'][p]]==['app/provider_linear_results.py']
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['wss'] and not final['linear_trial']
for mode,levels in [('pose',[16]),('combined',[1])]:
    trial=json.loads((HERE/mode/'trial-result.json').read_text())
    assert not trial['errors'] and trial['cleanup']['reaped']
    assert [s['level'] for s in trial['stages'] if s['status']=='PASS']==levels
    assert all(p['last_cleanup']['completed'] and not p['last_cleanup']['forced'] and
        p['last_cleanup']['diagnostic']['exit_code']==0 for v in trial['cleanup']['states'].values() for p in v['providers'].values())
for lane in json.loads((HERE/'lanes-v2.json').read_text()):
    assert lane['completed']==lane['accepted'] and lane['late']==0
    for d in lane['durations'].values():assert d['count']==sum(d['histogram']) and min(d['histogram'])>=0
comparison=json.loads((HERE/'comparison.json').read_text())
assert not any(comparison['condition_differences'].values())
assert all(not r['queue_drop'] and not r['queue_expired'] for r in comparison['b_lanes'])
artifacts=json.loads((HERE/'natural-artifacts.json').read_text())
assert len(artifacts)==5 and all(r['artifact_state']=='READY' and r['http_status']==200 for r in artifacts)
rows=api('/api/v1/streams')['streams']
save('verification.json',dict(final_targeted_tests=49,python='3.12',
    first_test_attempt='one loader error: nonexistent test_frame_ingress; corrected to test_det_result_path',
    pose16_image=first['tag'],combined_image=image['tag'],image_difference='pending request stall guard only',
    final=final,current_states={k:sum(r['state']==k for r in rows) for k in set(r['state'] for r in rows)},
    files=paths,natural_artifacts=artifacts,portfolio='MEDIUM; throughput-latency tradeoff and production adoption 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='Contextra 단일-provider Linear B 구현과 Pose16/복합1 비교',
 results=['tee/강제격리복사/완료relay/추론전slot 없는 명시적 B,완료queue32/1초와공통Event/Stop보호 유지',
 '최종표적49PASS,기동Stop/Pose16/복합3child 정상회수;Pose16평균5.96→7.97FPS',
 '선택→제출223→508ms,TritonQueue44→300ms로지연증가;처리량우선조건부채택추천',
 '자연Event5건 ArtifactREADY/HTTP200;FIRE/FALL자연Event와재생품질은미확인'],
 verify=['source/image,conditions,counter/histogram,diff/link checks','36stopped/child0/WSSconnected/modelsREADY/ArtifactHTTPOn,운영A/freshnessOn/CAS복귀/비대상보존'],
 commits=[],remaining=['B운영기본전환은별도승인','동시진행량과지연tradeoff,실제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','feat(runtime): 단일 provider Linear 시험 경로와 비교 근거 추가',
 '--message','Why=provider-process 내부의 PR13 분기 및 직렬완료 비용을 구분할 실행 비교군이 필요했다.',
 '--message','What=명시적LinearB직선경로/완료queue32와1초대기제한/SDK운반private timing/미완료작업stall보호를구현하고공통Event/Artifact/Stop을재사용했다.',
 '--message','Impact=기본A/운영freshnessOn유지.tee/강제복사/relay/추론전slot우회는B에서만적용한다.모델/instance/batch/FPS/threshold/decoder/공개Metadata/채널소유권은보존한다.',
 '--message','Verify=최종Python3.12표적49PASS.BPose16평균7.97FPS대직전A5.96FPS,선택→제출508ms대223ms.Pose16측정후stallguard만보완한최종image에서복합1검증.자연Artifact5READY/HTTP200.모든child정상회수.과거A와동시동일Frame시험아님.',
 '--message','Rollback=이전image/config/자료보존,자동rollback없음.최종provider-linear-7d7a97e883에서B옵션해제/운영A와freshnessOn복귀,36stopped/WSS연결/ArtifactHTTPOn.채택은지연증가를조건으로별도승인한다.',
 '--verify','49 targeted PASS; Pose16 B and final-image combined1; startup Stop/unforced reap; natural Artifact 5 READY/HTTP200',
 '--verify','source/image/conditions/diff/links/histograms; settings restored, default A/freshness ON, WSS/models ready, non-target preserved',
 '--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]))
