"""Final storage integrity only; does not repeat semantic/format audit.""" from pathlib import Path import json,hashlib,subprocess ROOT=Path.cwd() def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest() for key in ['지료청구','진료비치료비의료비청구']: w=ROOT/f'tmp/규칙문서재작성_{key}_20260913_batch5' snap=json.loads((w/'snapshot.json').read_text());draft=w/'draft.md';out=Path(snap['output']) for p,h in [(Path(snap['source']),snap['source_sha']),(ROOT/'case_kind_registry.json',snap['registry_sha']),(ROOT/'1. 베타 0.5 다듬기/output_format_v1.txt',snap['format_sha'])]: if sha(p)!=h:raise RuntimeError('Input changed: '+str(p)) data=draft.read_bytes();text=data.decode('utf8') if out.exists(): status='동일 최종본 존재' if out.read_bytes()==data else '기존 최종본 덮어쓰기 승인 필요' else: patch='*** Begin Patch\n*** Add File: '+str(out.relative_to(ROOT))+'\n'+''.join('+'+l+'\n' for l in text.splitlines())+'*** End Patch\n' subprocess.run(['apply_patch',patch],check=True,capture_output=True);status='재작성·단일 검증·개선 반영 후 신규 저장' target=draft if status=='기존 최종본 덮어쓰기 승인 필요' else out saved=target.read_bytes();decoded=saved.decode('utf8') if target==out and saved!=data:raise RuntimeError('Saved bytes differ') if decoded.splitlines()[0]!=snap['title']:raise RuntimeError('Title mismatch after save') r={'key':key,'display':snap['display'],'status':status,'path':str(target),'lines':len(decoded.splitlines()),'bytes':len(saved),'sha256':sha(target),'source_unchanged':True,'work_directory':str(w),'verification_rounds':1} result=json.dumps(r,ensure_ascii=False,indent=2) rp=w/'storage_result.json' if rp.exists():raise RuntimeError('Do not repeat publishing') subprocess.run(['apply_patch','*** Begin Patch\n*** Add File: '+str(rp.relative_to(ROOT))+'\n'+''.join('+'+l+'\n' for l in result.splitlines())+'*** End Patch\n'],check=True,capture_output=True) print(result)