Case_02_Comparison_Research - Stage 1 v.8: Part 1~4 YAMLs with R1~R3 patches, F-1/F-2 fixes, 피고과식별방지 prompt (defendant_qualification), dated backups, 실행검사/실패분석 reports - Stage 2 S2_00: v7.4 handoff (Task_S2_00_handoff, 경량화 전략서 + §2 개정) and v7.5 defendant qualification gate (피고관련작업_개정_S2_00.md), copies v.7/v.10/v.11, dated backups, 실행보고서/실패분석/결과물 리스트 - Stage 2 S2_10: v6/v7/v8 failure analyses, 재작성전략 10_06/10_08, case_kind_registry.json, 연구조사보고서_S2_10_재작성용.md (v.1), _추가.md (multi-claim methodology) and merged _v.2.md (claims[] 1~4, join PRELIMINARY/SELECTIVE/INDEPENDENT, V1~V6), S2_10_Test run outputs, 실행검사 v.10/v.11 - Stage_2 MEMORY.md / CLAUDE.md / work-history notes, AGENTS.md and README_KO.md updates Other corpora and tooling - Default_Agent_청구취지기재방법: 청구취지 규칙문서 전체 모음(원문·사건종류별·raw) and tmp drafts - 요건사실론: 사건종류별 문서(raw·filtered), plans, rf_draft - 판례모음, STT_앱구성_연구, API Crowdness 조사, update_numbers.py Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
117 lines
7.2 KiB
Python
117 lines
7.2 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""기계 검사. 인자: 검사할 md 경로."""
|
|
import re, sys, json, os, hashlib, unicodedata
|
|
WD=os.path.dirname(os.path.abspath(__file__))
|
|
p=sys.argv[1]
|
|
raw=open(p,'rb').read()
|
|
txt=raw.decode('utf-8') # UTF-8 재읽기
|
|
lines=txt.split('\n')
|
|
res={}
|
|
def chk(name, ok, detail=''):
|
|
res[name]={'ok':bool(ok),'detail':detail}
|
|
print(('PASS ' if ok else 'FAIL '), name, detail if not ok else '')
|
|
|
|
chk('utf8', True)
|
|
chk('title', lines[0]=='# 계약금 청구 — 청구취지 작성 규칙', lines[0])
|
|
# 코드펜스 짝
|
|
fences=[i for i,l in enumerate(lines) if l.strip().startswith('```')]
|
|
chk('fence_pairs', len(fences)%2==0, len(fences))
|
|
infence=set()
|
|
for a,b in zip(fences[0::2],fences[1::2]): infence.update(range(a,b+1))
|
|
# 최상위 절 순서
|
|
h2=[l for i,l in enumerate(lines) if l.startswith('## ') and i not in infence]
|
|
exp=['## 0. 메타데이터와 사용법','## 1. 청구권·사실정보 연결과 보완','## 2. 유형 선택과 작성 경로','## 3. 당사자·대상·범위의 작성 규칙','## 4. 금액·기간·조건·부수청구','## 5. 표준 문형과 조립','## 6. 청구원인 작성 단계에 전달할 사항','## 7. 진행·보완·전환·중단 기준','## 부록 A. 근거와 적용 제한','## 부록 B. 문서 관리·제작 검증']
|
|
chk('h2_order', h2==exp, h2)
|
|
# 메타데이터 4항목
|
|
m0=lines.index('## 0. 메타데이터와 사용법')
|
|
meta=[l for l in lines[m0:m0+12] if l.startswith('| ') and not l.startswith('| 항목') ]
|
|
fields=[l.split('|')[1].strip() for l in meta]
|
|
chk('metadata_fields', fields==['사건종류','사건키','적용범위','적용제외'], fields)
|
|
chk('metadata_values', '| 사건종류 | 계약금 청구 |' in lines and '| 사건키 | 계약금청구 |' in lines)
|
|
# 템플릿 잔재
|
|
body='\n'.join(l for i,l in enumerate(lines))
|
|
res_tpl=[m.group(0) for m in re.finditer(r'(?<!#)###(?![# ])',body)]
|
|
chk('template_hash', not res_tpl, res_tpl[:5])
|
|
for tok in ['CASE_KEY','CASE_DISPLAY_NAME','RUN_ID','${']:
|
|
hits=[i+1 for i,l in enumerate(lines) if tok in l]
|
|
chk('residue_'+tok, not hits, hits[:5])
|
|
ihd=''.join(['이하',' ','동일']); ihd2=''.join(['이하','동일'])
|
|
chk('no_ellipsis_phrase', ihd not in body and ihd2 not in body)
|
|
# 표 열 수(펜스 밖) — 이스케이프 파이프 제외
|
|
bad=[]
|
|
i=0
|
|
while i<len(lines):
|
|
if i in infence or not lines[i].startswith('|'): i+=1; continue
|
|
j=i; cols=None
|
|
while j<len(lines) and lines[j].startswith('|') and j not in infence:
|
|
n=len(re.split(r'(?<!\\)\|',lines[j].strip())[1:-1])
|
|
if cols is None: cols=n
|
|
elif n!=cols: bad.append((j+1,n,cols))
|
|
j+=1
|
|
i=j
|
|
chk('table_columns', not bad, bad[:10])
|
|
# ID 보존
|
|
src=[x for x in os.listdir(os.path.join(WD,'..','..')) if unicodedata.normalize('NFC',x)=='사건종류_계약금청구'][0]
|
|
srcf=os.path.join(WD,'..','..',src,[x for x in os.listdir(os.path.join(WD,'..','..',src)) if unicodedata.normalize('NFC',x)=='청구취지작성규칙_계약금청구_v2.md'][0])
|
|
sraw=open(srcf,'rb').read(); stxt=sraw.decode('utf-8')
|
|
sids=set(re.findall(r'(?:Q|STOP|RULE|LEAF|FORM|EVID|CHECK)-KG-(?:S1|C0[1-5]|R0[1-3]|H0[12]|\d{2}[NPEDT]?)',stxt))
|
|
bids=set(re.findall(r'(?:Q|STOP|RULE|LEAF|FORM|EVID|CHECK)-KG-(?:S1|C0[1-5]|R0[1-3]|H0[12]|\d{2}[NPEDT]?)',body))
|
|
chk('ids_preserved', sids<=bids, sorted(sids-bids))
|
|
chk('no_new_ids', bids<=sids, sorted(bids-sids))
|
|
# 근거·조문·사건번호·URL 보존
|
|
for name,pat in [('statutes',r'제\d+조'),('cases',r'\d{2,4}다\d+'),('urls',r'https?://[^\s\)\|]+'),('dates',r'\d{4}-\d{2}-\d{2}')]:
|
|
s=set(re.findall(pat,stxt)); b=set(re.findall(pat,body))
|
|
chk('preserve_'+name, s<=b, sorted(s-b))
|
|
# 문형 9필드
|
|
forms=re.findall(r'^### (FORM-KG-\d{2}) — .+$',body,re.M)
|
|
chk('form_count', len(forms)==13, forms)
|
|
fields9=['선택 기준','작성 전에 연결할 정보','법적 전제','미확인 처리','주문 문장','조립','사용 금지 조건','근거','검토']
|
|
missing=[]
|
|
secs=re.split(r'^### FORM-KG-\d{2} — .+$',body,flags=re.M)[1:]
|
|
for f,s in zip(forms,secs):
|
|
s=s.split('### 5.14')[0]
|
|
for fd in fields9:
|
|
if f'- **{fd}**' not in s: missing.append((f,fd))
|
|
if s.count('```text')<1: missing.append((f,'fence'))
|
|
chk('form_fields', not missing, missing)
|
|
# 다섯 상태·작성/검토 상태·URL 금지
|
|
for s in ['작성 진행','재검토를 붙여 진행','해당 부분 보완 대기','다른 구성·절차로 전환','해당 구성 중단']:
|
|
chk('state_'+s, s in body)
|
|
chk('writing_statuses','작성됨 / 부분 작성 / 보완 대기 / 전환 / 해당 구성 중단' in body)
|
|
chk('review_statuses','문구 검사 미완료 / 문구 검사 완료 / 법률·사실 쟁점 재검토 필요 / 변호사 제출 전 검토 완료' in body)
|
|
chk('url_prohibition','URL을 직접 열거나 브라우저·검색·HTTP 요청' in body and 'A.2' in body)
|
|
# § 참조 해결
|
|
heads=set()
|
|
for l in lines:
|
|
m=re.match(r'^##+ (?:(\d+(?:\.\d+)?)\.?|(부록 [AB])|([AB]\.\d+))',l)
|
|
if m: heads.add(m.group(1) or m.group(2) or m.group(3))
|
|
pre_b=body.split('## 부록 B.')[0]
|
|
pre_b_clean=re.sub(r'원문 §\d+(?:\.\d+)?','',pre_b)
|
|
refs=set(re.findall(r'§(\d+(?:\.\d+)?)',pre_b_clean))
|
|
bad_refs=sorted(r for r in refs if r not in heads)
|
|
chk('section_refs', not bad_refs, bad_refs)
|
|
b_refs=sorted(set(re.findall(r'§(\d+(?:\.\d+)?)',body.split('## 부록 B.')[1]))-heads)
|
|
print('INFO 부록 B 내 원문 절 참조(허용):',b_refs)
|
|
brefs=set(re.findall(r'\b(B\.\d)\b',body))|set(re.findall(r'\b(A\.\d)\b',body))
|
|
bad_b=sorted(r for r in brefs if r not in heads)
|
|
chk('appendix_refs', not bad_b, bad_b)
|
|
# 입력 해시 불변
|
|
idl=json.load(open(os.path.join(WD,'identity_ledger.json'),encoding='utf-8'))
|
|
chk('source_hash', hashlib.sha256(sraw).hexdigest()==idl['source_sha256'])
|
|
root=os.path.join(WD,'..','..')
|
|
chk('registry_hash', hashlib.sha256(open(os.path.join(root,'case_kind_registry.json'),'rb').read()).hexdigest()==idl['registry_sha256'])
|
|
fmt=[x for x in os.listdir(root) if unicodedata.normalize('NFC',x)=='1. 베타 0.5 다듬기'][0]
|
|
chk('format_hash', hashlib.sha256(open(os.path.join(root,fmt,'output_format_v1.txt'),'rb').read()).hexdigest()==idl['format_sha256'])
|
|
# 금지 38, CHECK 18, 정보 21, 노드 20, LEAF 13, RULE 16, EVID 14
|
|
chk('prohibitions_38', len(re.findall(r'^\| (\d+) \| .+ \| .+ \|$',body.split('### 7.3')[1].split('### 7.4')[0],re.M))==38)
|
|
chk('check_items_18', body.split('### 7.4')[1].split('### 7.5')[0].count('- [ ] ')==18)
|
|
chk('info_rows_21', len([l for l in body.split('### 1.2')[1].split('### 1.3')[0].split('\n') if l.startswith('| ') and not l.startswith('| 필요한 정보')])==21)
|
|
chk('evid_rows_14', len(re.findall(r'^\| EVID-KG-\d{2} ',body,re.M))==14)
|
|
chk('rule_rows_16', len(re.findall(r'^\| RULE-KG-\d{2} ',body,re.M))==16)
|
|
chk('leaf_rows_13', len(re.findall(r'^\| LEAF-KG-\d{2} \| ',body.split('### 2.3')[1].split('### 2.4')[0],re.M))==13)
|
|
chk('node_rows_20', len(re.findall(r'^\| Q-KG-',body.split('### 2.2')[1].split('### 2.3')[0],re.M))==20)
|
|
allok=all(v['ok'] for v in res.values())
|
|
res['_summary']={'all_ok':allok,'bytes':len(raw),'lines':len(lines) if not txt.endswith('\n') else len(lines)-1,'sha256':hashlib.sha256(raw).hexdigest()}
|
|
json.dump(res,open(os.path.join(WD,'validate_result.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1)
|
|
print('ALL OK' if allok else 'FAILURES', res['_summary'])
|