import datetime,json,os,pathlib,re,subprocess
os.umask(0o077)
repo=pathlib.Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
here=pathlib.Path(__file__).parent
job='20260921-contextra-icerti-incremental-r01'
def cmd(args):return subprocess.check_output(args,text=True,timeout=60)
assert cmd(['git','-C',str(repo),'rev-parse','HEAD']).strip()=='40a788c3d7ec6a8ad81a1c84731de56f68f1af89'
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)==14,paths
cmd(['git','-C',str(repo),'diff','--check'])
for name in paths:
    if name.endswith('.md'):
        for link in re.findall(r'\]\(([^)]+)\)',(repo/name).read_text()):
            if '://' not in link and not link.startswith('#'):
                assert ((repo/name).parent/link.split('#')[0]).exists(),(name,link)
receipt={'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 현장 시나리오 증분 패치 및 Web 시험 대기 준비',
 'results':['기존 FULL/Medium/인증 보존, source/native Analytics와 Sidecar 및 Gateway template 반영',
            'Pose/Fire/CROWD 현장 GPU 변환 및 네 모델 instance8 상주 준비',
            'FALL 현장 기본On과 명시적Off 보존, legacy 배포의 증분 검토 guard 추가'],
 'verify':['최종 Python3.12 표적44 PASS, 신규3모델 batch1~4 shape/dtype/finite PASS',
           '4모델 READY, WSS bootstrap, Redis reader 및 관리명령 거부, Artifact On, 3채널 stopped',
           'source114 hash 및 원장/인증/비대상 보존; 임시 sudo 파일 삭제'],
 'commits':[],'remaining':['사용자 브라우저 영상/시나리오/Event 수용 대기','실제 Web Redis 소비와 부하/정확도 미검증']}
(here/'report-receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2))
print(cmd(['codex-report-receipt','--profile','ltb1021','--session-alias','work-session','--receipt',str(here/'report-receipt.json')]))
out=pathlib.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(deployment): 현장 시나리오 증분 패치와 네 모델 준비 완료',
 '--message','Why=기존 FULL과 현장 인증을 보존하면서 최신 시나리오를 소형 source/native 증분으로 반영한다.',
 '--message','What=CROWD512 도구와 Pose receipt 출력순서 보호, FALL 현장 기본값과 명시적Off 보존, 증분 원장 및 legacy deploy/rollback 검토 guard를 추가했다.',
 '--message','Impact=현장 대상 Analytics/Sidecar/Gateway만 반영. Medium 재사용과 신규3모델 현장 변환, 모든 등록채널stopped. test Runtime과 관제/비대상 서비스는 유지한다.',
 '--message','Verify=최종 Python3.12 표적44 PASS; 신규3모델 batch1~4 finite/shape/dtype PASS; 모델4 READY/WSS/Redis reader/Artifact On. source114 hash 및 기존 원장/인증 보존. 실제 사용자 브라우저 수용과 정확도 미실행.',
 '--message','Rollback=자동 rollback/Start 없음. 별도 승인 후 이전 image/Compose/model 원장으로 대상만 복구하며 DB/Artifact 삭제와 과거 Event 재전송은 하지 않는다. FALL 개별Off는 stopped Settings/CAS로 적용한다.',
 '--message','Related=ICERTI-INCREMENTAL-01; 원본 FULL 보존 및 최종 증분 r02; 현장 transaction incremental-20260921-r03',
 '--verify','Target Python3.12 44 PASS; 3 new GPU engines batches1-4 PASS; native build and source114 hashes PASS',
 '--verify','4 models READY, WSS bootstrap, Redis reader/admin denial, Artifact On, 3 cameras stopped; preserved credentials/ledger/non-targets',
 '--verify','git diff --check and guide links PASS; manual browser acceptance NOT RUN; sudo temporary file deleted',
 '--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]))
