from ops import *
import datetime, re

job = '20260923-contextra-pr13-r01'
assert cmd(['git', '-C', str(REPO), 'rev-parse', 'HEAD']).strip() == '0a0856418be61f7510f2c1c45957691aa6788bb4'
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) == 35
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 '://' in target or target.startswith('#'):
            continue
        assert ((REPO / p).parent / target.split('#')[0]).exists(), (p, target)
snapshot = json.loads((HERE / 'build-intent.json').read_text())
save('verification-closeout.json', dict(python='3.12',
    cpu_batches=[{'passed':108,'subtests':18,'deselected':1}, {'passed':22,'deselected':52}, {'passed':45}],
    counts_overlap=True, guide_default_endpoint_checks=20,
    gpu_pose_fire='FAIL: native ServiceMaker segmentation fault before results',
    gpu_pose_fire_crowd='NOT RUN', browser_ready=False, docs_links=True,
    source_hashes={p:hashlib.sha256((REPO/p).read_bytes()).hexdigest() for p in 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 통합/CPU 검증 및 GPU native crash 경계 기록',
    results=['task worktree에 PR13 참고 후보와 provider queue/FINALIZING/FIRE gap/public300 보완',
             '기존 image 위 source/native 증분 image 반영; 4모델 READY',
             '2-provider GPU 첫 결과 전 native crash로 중단; 3-provider 미실행; 모든 채널 stopped'],
    verify=['Python3.12 108 PASS+18 subtests, Web22 PASS, 최종영향45 PASS (중복 있음)',
            'CPU Gst latest waiting/branch 독립 fixture PASS; 안내범위20 endpoint 확인',
            'Event 원장/비대상서비스 불변; Artifact/HTTP On; Gateway 중지/WSS disconnected'],
    commits=[], remaining=['SDK frame ingress native crash 원인 규명/수정과 GPU 재수용',
                           '새 Web schema 확인/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(runtime): PR13 통합 보완과 GPU 수용 실패 경계 기록',
    '--message','Why=single-decode multi-provider와 새 Web parameters를 통합하되 Frame/Event/Stop 경계와 실제 GPU 검증을 구분한다.',
    '--message','What=독립 leaky queue/native relay, FINALIZING 인계, FIRE gap, public300 참조/대표 보존과 사용/복귀 문서를 보완했다.',
    '--message','Impact=Web confidence 제거, parameters 추가, FIRE Smoke OR, channel limit0. test image만 반영했으며 현장/관제/비대상 서비스는 보존했다.',
    '--message','Verify=Python3.12 표적108+18subtests/Web22/최종영향45 PASS(중복 있음), 문서범위20 PASS. 4모델READY. Pose+Fire GPU는 ServiceMaker native crash로 FAIL, 3-provider NOT RUN. 25채널stopped/원장보존. Web-ready 아님.',
    '--message','Rollback=자동rollback 없음. 이전 image/전체Compose/private baseline 보존. flag false는 Web/FIRE/저장값 전체원복이 아니다. Gateway는 GPU blocker 해결까지 maintenance stopped.',
    '--message','Related=PR13 e514252; PR13-INTEGRATION-01; GPU crash 원인 미확정/아이서티 미반영',
    '--verify','Python3.12 targeted 108+18 subtests; Web22; final45 (overlap); guide20 checks PASS',
    '--verify','GPU Pose+Fire FAIL(native segmentation fault); three-provider NOT RUN; all25 stopped and child reaped; 4models READY',
    '--verify','git diff --check and changed doc links PASS; ledger/non-target preserved; Gateway stopped/WSS disconnected; no readiness acceptance',
    '--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]))
