"""Prepare only: receipt, exact-path Manifest and read-only Batch Plan."""
import datetime,json,os,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parent;REPO=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
TEMP=Path('/tmp/codex/ltb1021/2026-11-01_contextra-fall-r2-deployment_r01');TEMP.mkdir(parents=True,exist_ok=True);TEMP.chmod(0o700)
os.umask(0o077)
job='contextra-fall-r2-runtime-20261101-r01'
v=json.loads((ROOT/'final-validation.json').read_text());paths=sorted(v['changed_paths'])
assert subprocess.check_output(['git','rev-parse','HEAD'],cwd=REPO).decode().strip()==v['repo_head']
assert not subprocess.check_output(['git','diff','--cached','--name-only'],cwd=REPO).strip()
args=['codex-git-closeout','prepare','--repository',str(REPO),'--output',str(TEMP/'manifest.json'),
      '--job-id',job,'--profile','ltb1021','--session-alias','work-session',
      '--title','feat(fall-r2): 고정 쓰러짐 후보의 Runtime 통합과 현장 기본 적용',
      '--message','Why=수용한 R2를 Web 패치 없이 기존 Start·Redis·Event에 연결하고 전체 채널 기본으로 사용해야 했다.',
      '--message','What=고정 규칙 adapter, 원자적 버전 설정·score 하한·reset, 알림 연결, 현장 최소 source-only 배포와 Web 전달 명세를 추가했다.',
      '--message','Impact=아이서티 기존28채널·신규template FALL R2. FIGHT·On/Off·ROI·높은 score·Tracker·모델은 보존. 공용 fallback legacy 유지.',
      '--message','Verify=36입력20145표시관측 판정·기여·유지·Event 위치 일치. 현장image157검사+110subtest, 설정CAS·readiness, HTML6화면·JSON11예시·전송지문 PASS. 개발검사 기존실패2건 분리. 브라우저/장시간/DB동시성2검사는 미실시.',
      '--message','Rollback=코드 revert만으로 현장 복귀하지 않는다. 별도 승인과 actual CAS 뒤 이전 image68823dd 및 settings-before/previous-active를 함께 복원한다.',
      '--verify','저장 R2 36입력20145표시관측/준비포함20715 비교 차이0; 원본 cache와 기준 규칙 보존',
      '--verify','현장 image157검사+110subtest; persistent28채널/template R2와 FALL 외 설정 보존; Gateway 복구',
      '--verify','HTML 오프라인1440/768/390px6조건·JSON예시11개·링크·AST·git diff --check PASS; 시험 컨테이너0',
      '--expires-in-seconds','172800','--remote','origin']
for p in paths:args+=['--path',p]
result=subprocess.run(args,capture_output=True,text=True);(ROOT/'git-prepare.log').write_text(result.stdout+result.stderr);result.check_returncode()
m=json.loads((TEMP/'manifest.json').read_text());h=m.get('plan_hash') or m.get('plan_sha256')
assert h,m.keys()
args=['codex-git-closeout','batch-prepare','--output',str(TEMP/'batch.json'),'--batch-id',job+'-batch',
      '--profile','ltb1021','--session-alias','work-session','--expected-group-count','1',
      '--repository-label','contextra-analytics-runtime-lifecycle-refactor','--manifest',str(TEMP/'manifest.json'),
      '--expect-plan-hash',h,'--expires-in-seconds','172800']
result=subprocess.run(args,capture_output=True,text=True);(ROOT/'git-batch-prepare.log').write_text(result.stdout+result.stderr);result.check_returncode()
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='고정 FALL R2 Runtime 통합·전체 채널 기본 배포와 FIGHT/FALL Web 전달 문서 준비',
 results=['FALL R2를 기존 Start·Redis·Event에 통합하고 source-only image로 기본 적용했다. FIGHT·모델·Tracker·기존 높은 score와 On/Off는 보존했다.',
          '브라우저 확인 질문·알람 유도·별도Start 없이 AI readiness와 설정 검증까지만 완료했다. HTML/Markdown 전달4종을 준비했다.'],
 verify=['36입력20145표시관측/전체20715 판정·기여·유지·Event 위치 차이0.',
         '현장image157검사+110subtest PASS. 개발162검사+114subtest PASS/기존HEAD 동일실패2건 분리.',
         '설정 migration no-op/CAS·타 시나리오 보존·소스16파일·모델 readiness·Gateway 복구 확인. HTML오프라인6조건/JSON예시11개/링크·지문 PASS.'],
 commits=[],remaining=['브라우저 FALL 표시·알람·미디어 수용은 사용자 확인 전까지 미확인. 장시간·일반화·PostgreSQL 동시성2검사 보류.',
                       'Git Manifest/Batch 준비만 수행하며 실제 add/commit/push 미실행. Portfolio는 브라우저 수용 전 MEDIUM 후보만 보존.'])
(TEMP/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2));(TEMP/'receipt.json').chmod(0o600)
print(TEMP/'batch.json');print('RECEIPT_READY',TEMP/'receipt.json')
