from pathlib import Path import re,json,hashlib,subprocess,unicodedata ROOT=Path.cwd() def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest() def add(p,s): assert not p.exists() subprocess.run(['apply_patch','*** Begin Patch\n*** Add File: '+str(p.relative_to(ROOT))+'\n'+''.join('+'+l+'\n' for l in s.splitlines())+'*** End Patch\n'],check=True,capture_output=True) for key in ['지료청구','진료비치료비의료비청구']: w=ROOT/f'tmp/규칙문서재작성_{key}_20260913_batch5';snap=json.loads((w/'snapshot.json').read_text());s=Path(snap['source']).read_text();d=(w/'draft.md').read_text(); checks=[] def ck(name,ok,detail=''):checks.append((name,bool(ok),detail)) ck('원본 해시',sha(Path(snap['source']))==snap['source_sha']) ck('형식 해시',sha(ROOT/'1. 베타 0.5 다듬기/output_format_v1.txt')==snap['format_sha']) ck('registry 해시',sha(ROOT/'case_kind_registry.json')==snap['registry_sha']) ck('UTF8 재읽기',d.encode().decode('utf8')==d) ck('정확한 표시명 제목',d.splitlines()[0]==snap['title']) calc=''.join(c for c in unicodedata.normalize('NFC',snap['display']) if unicodedata.category(c)[0] in 'LN');ck('표시명에서 산출한 키',calc==key) ck('메타데이터 4개',len([l for l in d.split('### 사용 순서')[0].splitlines() if l.startswith('| ')])-1==4) ck('최상위 0~7 A B',re.findall(r'^## (.*)',d,re.M)==['0. 메타데이터와 사용법','1. 청구권·사실정보 연결과 보완','2. 유형 선택과 작성 경로','3. 당사자·대상·범위의 작성 규칙','4. 금액·기간·조건·부수청구','5. 표준 문형과 조립','6. 청구원인 작성 단계에 전달할 사항','7. 진행·보완·전환·중단 기준','부록 A. 근거와 적용 제한','부록 B. 문서 관리·제작 검증']) ck('코드펜스 짝',len(re.findall(r'^```',d,re.M))%2==0) ck('치환 잔재 없음',not re.search(r'CASE_KEY|CASE_DISPLAY_NAME|RUN_ID|\$\{',d)) for name,rx in [('Q',r'Q-[A-Z0-9]+(?:-[A-Z0-9]+)*'),('RULE',r'RULE-[A-Z0-9]+(?:-[A-Z0-9]+)*'),('FORM',r'FORM-[A-Z0-9]+(?:-[A-Z0-9]+)*'),('LEAF',r'LEAF-[A-Z0-9]+(?:-[A-Z0-9]+)*'),('STOP',r'STOP-[A-Z0-9]+(?:-[A-Z0-9]+)*'),('CHECK',r'CHECK-[A-Z0-9]+(?:-[A-Z0-9]+)*'),('사건번호',r'\d{2,4}(?:다|두)\d+'),('URL',r'https?://[^\s)<>|]+')]: a=set(re.findall(rx,s));b=set(re.findall(rx,d));ck(name+' 원문 집합 보존',a<=b,str(sorted(a-b))) sourceforms=re.findall(r'^### (FORM-\S+) —',s,re.M);df=re.findall(r'^### (FORM-\S+) —',d,re.M);ck('전체 문형 개수·이름',sourceforms==df,str(len(df))) for field in ['선택 기준','작성 전에 연결할 정보','법적 전제','미확인 처리','주문 문장','조립','사용 금지 조건','근거','검토']: ck('문형별 '+field,len(re.findall(r'^- '+field+':',d,re.M))==len(df)) ck('처리상태5',all(x in d for x in ['작성 진행','재검토를 붙여 진행','해당 부분 보완 대기','다른 구성·절차로 전환','해당 구성 중단'])) ck('작성·검토 별개',all(x in d for x in ['문구 검사 미완료','변호사 제출 전 검토 완료','작성 상태는'])) ck('URL직접·우회금지',all(x in d for x in ['HTTP 요청','우회 원문 수집도 금지','필요한 원문·검토 결과의 제공'])) # Deterministic source-unit correspondence; nonliteral candidates require human semantic decision. lines=(w/'source_ledger.md').read_text().splitlines(); misses=[]; matches=[] norm=lambda x:re.sub(r'[`*#]','',x).strip().rstrip('.') dn=norm(d) for l in lines: if not l.startswith('| U'):continue c=re.split(r'(?