Files
Liti-agent-Development/요건사실론/tmp/rf_draft/_shared/rf_gate.py
T
jhogyuandClaude Fable 5.1 5f9853e44b chore: snapshot of work since 2026-10-05 (Stage 1 v.8, S2_00 v7.4/v7.5 handoff, S2_10 rewrite research v.2, 청구취지·요건사실 corpora)
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>
2026-10-12 13:02:13 +09:00

510 lines
28 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""요건사실론 문서 게이트 — 골격 v4 제6부 L1 표준 구현체.
사용: python3 rf_gate.py <문서.md> [--project] [--check-idempotent]
--project §7 총괄표를 §4.2·§5.P#.2·§6에서 재투영한 뒤 검사(멱등)
--check-idempotent 투영을 2회 연속 실행해 바이트 동일성을 확인
종료코드 0 = 전 항목 PASS."""
import sys, re, os, io, hashlib, unicodedata as U
RF_GATE_VERSION = 'v4.2' # 절차 1의 버전 확인 대상. 정본은 tmp/rf_draft/_shared/rf_gate.py이며 워커는 저장·덮어쓰기하지 않는다.
# v4.2 (골격 v4-r7, 2026-09-09): L-f의 추정·전환 값에 「경로별 상이 — <기본값>」 형식을 추가 허용.
# 허용 집합을 넓히기만 하므로 v4.1에서 PASS하던 문서는 전부 그대로 PASS한다(코퍼스 회귀 없음).
# v4.1 (골격 v4-r6, 2026-09-09): §6.6 신설(L-d 범위), S1 content_hash 형식, S10b 면제 단위 정정·범위 표기 면제,
# §7 소속 절 열에 절 제목 병기, 린트 L-f(블록 필드 존재·순서·형식) / L-g(본문 조문의 §12 등재) 신설.
SEC = [(0,'문서 메타 (front matter)'),(1,'재판모델과 청구경로 지도'),(2,'소송물·주문·집행 연결'),
(3,'소송요건과 절차효과'),(4,'공통 청구원인사실'),(5,'경로별 분기 요건사실'),
(6,'상대방의 응답: 부인·항변·재항변'),(7,'주장·증명책임 총괄표'),(8,'증거계획'),
(9,'판결효과·보전·집행'),(10,'서면 변환'),(11,'체크리스트·금지규칙·오류 카탈로그'),
(12,'근거자료와 검증상태')]
TRI_RE = re.compile(r'^(?:해당 없음|UNKNOWN|UNVERIFIED) — .{5,}$')
def TRI_(x):
"""3분 값 판정. 백틱·굵게(**)로 감싼 표기도 허용한다."""
return bool(TRI_RE.match(x.strip().strip('`').strip('*').strip()))
class _T:
match = staticmethod(lambda x: TRI_(x))
TRI = _T
RID = re.compile(r'R-(?:[A-Z]{3}|PROV)[0-9]{3}-[0-9]+(?:\.[0-9]+)?-[0-9]{2}')
RID_FULL = re.compile(r'^R-(?:[A-Z]{3}|PROV)[0-9]{3}-[0-9]+(?:\.[0-9]+)?-[0-9]{2}$')
FIX_TITLES = set() # 골격 고정 절·항 제목 (L-c 예외)
for _n,_t in SEC: FIX_TITLES.add(_t)
FIX_TITLES |= {'당사자적격','소의 이익(확인의 이익 포함)','기간제한: 출소기간·제척기간·소멸시효',
'관할·중복소송·기판력','소장 요건과 인지','소송물의 특정','요건사실과 주문의 대응','주문 유형별 유의사항',
'재판모델 분류','청구경로 목록','경로 관계','인접 사건종류와의 경계','이 문서가 다루지 않는 것',
'원고가 부담하는 사실','요건사실 목록','요건별 상술','서술 순서','부수급부: 구간표',
'부인과 항변의 구별','권리장애 항변','권리멸각 항변','권리저지 항변','기간·시효 항변','신의칙·권리남용',
'소송요건의 소멸·흠결',
'요건별 증거 매핑','표준 서증 목록','직권·보조 수단','증명 곤란','판결효과','보전처분','집행방법',
'병합·소변경·반소, 다수당사자','소장 청구원인 서술 순서','답변서·준비서면 대응 순서','흠결의 효과',
'청구취지','작성 전 체크리스트','금지규칙','오류 카탈로그','법령','판례','헌법재판소 결정',
'『요건사실과 주장·증명책임』 제13판','웹 자료','학설','검증상태와 미해결'}
SIL_OK = ['감정평가서','감정서','평가서면'] # L-e 예외 (B6)
SIL_BAD = ['프롬프트','평가서','자료 파일','.md','.pdf','_v1']
DENY_LEAK = ['불성립','미교부','부존재','없었다'] # L-d
SUNG_OK = {'부인','권리장애 항변','권리멸각 항변','권리저지 항변','기간·시효 항변',
'신의칙·권리남용','직권 참작사유'}
PROC_OK = {'이송','보정명령 후 소장각하명령','소각하판결','본안기각'}
CHU_OK = {'법률상 추정','의사해석규정상 추정','증거법칙적 추정','사실상 추정','전환규정','간주','없음'} # §4.2 추정·전환 기본 7값 (v4-r6: 간주 신설)
CHU_MIXED = re.compile(r'^경로별 상이 — (.+)$') # v4.2: 경로별로 갈리는 경우의 복합 형식. 오른쪽은 다수 경로의 기본값
REQ_FIELDS = ['적용 경로','규범적 근거','요건분류','주장의 정도','주장책임 / 증명책임','추정·전환','다중 대응','증명 실무','흠결 빈발점','권위 ID']
DEF_FIELDS = ['대상요건','요건사실','주장책임 / 증명책임','재항변','재재항변','주문에 미치는 영향','소변경·석명 요부','권위 ID']
SEC_TITLE = {'4':'§4(공통 청구원인사실)','5':'§5(경로별 분기 요건사실)'} # §7 소속 절 열 (v4-r6: 제목 병기)
def nfc(x): return U.normalize('NFC', x)
# ── 파싱 ────────────────────────────────────────────────────────────────
def split_fm(text):
"""front matter, 본문, front matter 시작줄이 1행인지"""
lines = text.split('\n')
if lines and lines[0].strip() == '---':
for i in range(1, len(lines)):
if lines[i].strip() == '---':
return '\n'.join(lines[1:i]), '\n'.join(lines[i+1:]), True
m = re.search(r'^---$', text, re.M)
if m:
rest = text[m.end():]
m2 = re.search(r'^---$', rest, re.M)
if m2: return rest[:m2.start()], rest[m2.end():], False
return '', text, False
FENCE = chr(96)*3 # 리터럴 3연속 백틱을 쓰지 않는다(이 파일이 코드펜스 안에 실릴 수 있다)
def fence_mask(lines):
"""코드펜스 안이면 True"""
inside=False; out=[]
for ln in lines:
if ln.lstrip().startswith(FENCE): inside = not inside; out.append(True); continue
out.append(inside)
return out
def headings(body):
"""[(level, num_or_None, title, start_idx, end_idx)] — 본문 줄 인덱스 기준"""
lines = body.split('\n'); mask = fence_mask(lines); hs=[]
for i,ln in enumerate(lines):
if mask[i]: continue
m = re.match(r'^(#{1,6}) (.*)$', ln)
if m: hs.append([len(m.group(1)), m.group(2).strip(), i, None])
for j,h in enumerate(hs): h[3] = hs[j+1][2] if j+1 < len(hs) else len(lines)
return hs, lines, mask
def sec_of(hs, lines, num):
"""§num 절의 (시작줄, 끝줄)"""
st=None
for j,(lv,t,i,e) in enumerate(hs):
if lv==2 and re.match(r'^§%d\.\s' % num, t):
st=i
for k in range(j+1, len(hs)):
if hs[k][0]==2: return (st, hs[k][2])
return (st, len(lines))
return None
def sec_text(lines, rng): return '\n'.join(lines[rng[0]:rng[1]]) if rng else ''
def prose_lines(lines, mask, lo, hi):
for i in range(lo, hi):
if mask[i]: continue
ln = lines[i]
if ln.startswith('#') or ln.lstrip().startswith('|'): continue
yield i, ln
def table_rows(txt):
for ln in txt.split('\n'):
t=ln.strip()
if t.startswith('|') and t.endswith('|') and set(t) - set('|-: '):
yield [c.strip() for c in t.strip('|').split('|')]
# ── §7 투영 (멱등) ──────────────────────────────────────────────────────
def field(block, name):
m = re.search(r'^- \*\*%s\*\*:\s*(.*)$' % re.escape(name), block, re.M)
return m.group(1).strip() if m else ''
def req_blocks(body_lines, hs):
"""요건 블록: #### R-… 헤딩"""
out=[]
for lv,t,i,e in hs:
if lv==4 and t.startswith('R-'):
rid = t.split()[0]
out.append((rid, t[len(rid):].strip(), '\n'.join(body_lines[i:e])))
return out
def def_blocks(body_lines, hs):
"""항변 블록: #### 6.N.x …"""
out=[]
for lv,t,i,e in hs:
if lv==4 and re.match(r'^6\.[1-9]\d*\.\d+ ', t):
out.append((t.split()[0], '\n'.join(body_lines[i:e])))
return out
def project_s7(text):
fm, body, _ = split_fm(text)
hs, lines, _ = headings(body)
rb = req_blocks(lines, hs); db = def_blocks(lines, hs)
tgt={}
for no, blk in db:
for rid in RID.findall(field(blk, '대상요건')): tgt.setdefault(rid, []).append(no)
rows=['| 요건 ID | 요건사실 | 소속 절 | 요건분류 | 주장책임 | 증명책임 | 추정 | 대응 항변 ID |',
'|---|---|---|---|---|---|---|---|']
for rid, stmt, blk in rb:
_sn = rid.split('-')[2].split('.')[0]
sec = SEC_TITLE.get(_sn, '§' + _sn)
bur = field(blk, '주장책임 / 증명책임')
ba, bp = (bur.split('/',1) + [''])[:2] if '/' in bur else (bur, bur)
rows.append('| %s | %s | %s | %s | %s | %s | %s | %s |' % (
rid, stmt.replace('|','\\|'), sec, field(blk,'요건분류') or '-',
ba.strip() or '-', bp.strip() or '-', field(blk,'추정·전환') or '없음',
', '.join(tgt.get(rid, [])) or '-'))
# 원문 전체 줄 배열에서 §7 구간만 치환한다. front matter를 재조립하지 않아야 멱등이 보장된다.
full = text.split('\n'); st=None; en=len(full)
for i,ln in enumerate(full):
if st is None and re.match(r'^## §7\.\s', ln): st=i; continue
if st is not None and re.match(r'^## §\d+\.\s', ln): en=i; break
if st is None: return text, False
new = [full[st], ''] + rows + ['']
return '\n'.join(full[:st] + new + full[en:]), True
# ── 게이트 ──────────────────────────────────────────────────────────────
def run(path):
res=[]
def ck(i, ok, msg=''): res.append((i, 'PASS' if ok else 'FAIL', msg))
raw = io.open(path, encoding='utf-8').read()
fm, body, fm_first = split_fm(raw)
hs, lines, mask = headings(body)
doc_dir = os.path.dirname(os.path.abspath(path))
root = os.path.dirname(doc_dir)
# S1 front matter
try:
import yaml; Y = yaml.safe_load(fm) or {}; yok=True
except Exception:
Y={}; yok=False
for m in re.finditer(r'^([A-Za-z_]+):\s*"?([^"\n]*)"?$', fm, re.M): Y[m.group(1)]=m.group(2)
req = ["schema_version","case_kind_id","case_kind_name","case_kind_slug","action_type",
"claim_paths","path_relation","filing_deadline","law_as_of","verification_status","doc_version"]
e1=[k for k in req if k not in Y]
if 'case_kind_id' in Y and not re.match(r'^(?:[A-Z]{3}|PROV)-[0-9]{3}$', str(Y['case_kind_id'])): e1.append('case_kind_id 형식')
if 'case_kind_slug' in Y and not re.match(r'^[a-z0-9]+(?:-[a-z0-9]+)*$', str(Y['case_kind_slug'])): e1.append('slug 형식')
if str(Y.get('action_type')) not in ['이행','확인','형성','형식적형성','집행관계','재판공격']: e1.append('action_type')
if str(Y.get('path_relation')) not in ['단일','청구권경합','법조경합','택일','독립']: e1.append('path_relation')
fd = Y.get('filing_deadline')
if isinstance(fd, dict) and str(fd.get('kind')) not in ['없음','출소기간','제척기간','소멸시효']: e1.append('filing_deadline.kind')
if str(Y.get('verification_status')) not in ['VERIFIED','QUALIFIED','UNVERIFIED']: e1.append('verification_status')
if isinstance(Y.get('claim_paths'), list) and str(Y.get('path_relation'))=='단일' and len(Y['claim_paths'])>1: e1.append('단일인데 경로 복수')
if not re.fullmatch(r'sha256:[0-9a-f]{64}', str(Y.get('content_hash',''))): e1.append('content_hash 형식(sha256:<64hex>)') # v4.1
if str(Y.get('action_type'))=='형성' and isinstance(fd,dict) and str(fd.get('kind')) not in ['출소기간','제척기간']: e1.append('형성인데 kind')
ck('S1', not e1, ('yaml 모듈 없음 — 정규식 최소 구현. ' if not yok else '') + ('; '.join(e1)))
# S2a/S2b/S2c
got=[t for lv,t,_,_ in hs if lv==2 and t.startswith('§')]
exp=['§%d. %s' % (n,t) for n,t in SEC]
ck('S2a', got==exp, '기대 %d개 / 실제 %d개; 최초 불일치=%s' % (len(exp), len(got),
next((f'{a}|{b}' for a,b in zip(exp,got) if a!=b), '-')))
ck('S2b', sum(1 for lv,_,_,_ in hs if lv==1)==1, 'H1 %d개' % sum(1 for lv,_,_,_ in hs if lv==1))
order_ok = fm_first and bool(re.match(r'^\s*# 요건사실론:', '\n'.join(
[l for l in body.split('\n') if l.strip()][:1] or [''])))
ck('S2c', order_ok, 'front matter 첫 바이트=%s, 본문 첫 헤딩=%s' % (fm_first,
([l for l in body.split('\n') if l.strip()] or ['-'])[0][:40]))
# S3 빈 절·항 (leaf 헤딩만)
BLK = lambda t: t.startswith('R-') or re.match(r'^6\.[1-9]\d*\.\d+ ', t)
bad3=[]
for j,(lv,t,i,e) in enumerate(hs):
if lv<2: continue
if BLK(t): continue # 요건·항변 블록은 S3 대상이 아니다
if j+1 < len(hs) and hs[j+1][0] > lv: continue # 하위 레벨 자식을 가진 컨테이너
if j+1 < len(hs) and hs[j+1][0] == lv and BLK(hs[j+1][1]): continue # 동일 레벨 블록을 자식으로 가진 컨테이너
cont=[l.strip() for l in lines[i+1:e] if l.strip()]
if not cont: bad3.append(t+'(내용 없음)'); continue
if len(cont)==1 and not TRI.match(cont[0]) and len(cont[0])<12: bad3.append(t)
ck('S3', not bad3, '; '.join(bad3[:5]))
# S4
ids=[rid for rid,_,_ in req_blocks(lines, hs)]
dup=[x for x in set(ids) if ids.count(x)>1]
badf=[x for x in ids if not RID_FULL.match(x)]
ck('S4', not dup and not badf, 'dup=%s bad=%s' % (dup[:3], badf[:3]))
# S5 / S6 — 귀속은 ID의 절 필드로 판정(§4.0은 -4-nn)
s4={x for x in ids if x.split('-')[2].split('.')[0]=='4'}
s5={x for x in ids if x.split('-')[2].split('.')[0]=='5'}
r7 = sec_of(hs, lines, 7); t7 = sec_text(lines, r7)
row_ids={r[0] for r in table_rows(t7) if RID_FULL.match(r[0])}
ck('S5', row_ids==(s4|s5), '§7만=%s / 본문만=%s' % (sorted(row_ids-(s4|s5))[:3], sorted((s4|s5)-row_ids)[:3]))
ck('S6', not (s4 & s5), '교집합=%s' % sorted(s4 & s5)[:3])
# S7 항변 블록의 대상요건
bad7=[]
for no, blk in def_blocks(lines, hs):
v=RID.findall(field(blk,'대상요건'))
if not v: bad7.append(no+'(대상요건 없음)')
else:
miss=[x for x in v if x not in (s4|s5)]
if miss: bad7.append('%s→%s' % (no, miss))
ck('S7', not bad7, '; '.join(bad7[:5]))
# S8
cp = Y.get('claim_paths') if isinstance(Y.get('claim_paths'), list) else []
fm_ids={str(p.get('id')) for p in cp if isinstance(p,dict)}
br_ids={str(p.get('id')) for p in cp if isinstance(p,dict) and p.get('has_branch')}
r1=sec_of(hs,lines,1)
t11=[r for r in table_rows(sec_text(lines,r1))] if r1 else []
p_in_11={c for row in t11 for c in row if re.fullmatch(r'P\d+', c)}
p_in_5={t.split()[0][2:] for lv,t,_,_ in hs if lv==3 and re.match(r'^5\.P\d+', t)}
ck('S8', fm_ids==p_in_11 and br_ids==p_in_5,
'fm=%s §1.1=%s / branch=%s §5=%s' % (sorted(fm_ids), sorted(p_in_11), sorted(br_ids), sorted(p_in_5)))
# S9 사건번호 (조문 표기 배제)
EXCL={'조','항','호','목','면','분','년','조의','조제','항제','호의','부','편','장','절','권'}
cases=set()
for i,ln in enumerate(lines):
if mask[i]: continue
for m in re.finditer(r'(\d{2,4})([가-힣]{1,3})(\d+)', ln):
if m.group(2) in EXCL: continue
if m.start()>0 and ln[m.start()-1]=='제': continue
pre=ln[max(0,m.start()-8):m.start()]
if '100분의' in pre or '연 ' in pre[-3:]: continue
cases.add(m.group(0))
r12=sec_of(hs,lines,12); t12=sec_text(lines,r12)
miss9=sorted(c for c in cases if c not in t12)
ck('S9', not miss9, '§12.2∪§12.3 미등재=%s' % miss9[:5])
# S10 상호참조 (산문 줄에만)
# S10b (골격 v4 제6부, 적대검증 후 개정):
# (1) 산문 줄만 대상.
# (2) 면제 단위는 **항(H3) 구간**이다. 그 구간에서 그 참조의 첫 등장 1회만 제목 병기를 요구한다.
# 절(H2)이 아니다 — 제5부의 적재 청크 단위가 H3/H4이므로 절 단위 면제는 청크보다 넓다.
# (3) 절 번호가 참조가 아니라 문장 구성요소인 두 형태만 면제한다.
# 계수 `§N에 <숫자>`, 소유격 `§N의`. 줄 전체 면제는 두지 않는다(회피 경로가 된다).
refs=set(); noparen=[]
body_start = hs[0][2] if hs else 0
# v4.1: H3 구간은 다음 **동급 이상**(level<=3) 헤딩까지다. v4.0은 h[3](다음 헤딩, 레벨 불문)을 써서
# 첫 H4 앞에서 구간이 끊기고 블록 산문이 전부 단일 면제 단위를 공유했다(골격 제6부 사양과 괴리).
_units=[]
for j,h in enumerate(hs):
if h[0]!=3: continue
_end=len(lines)
for k in range(j+1,len(hs)):
if hs[k][0]<=3: _end=hs[k][2]; break
_units.append((h[2],_end))
def _unit_at(idx):
for a,b in _units:
if a<=idx<b: return a
return -1
_seen=set()
for i,ln in prose_lines(lines, mask, body_start, len(lines)):
ms=list(re.finditer(r'§(\d+(?:\.\d+)*(?:\.P[\d#]+(?:\.\d+)*)?)', ln))
for m in ms: refs.add(m.group(1))
_cur=_unit_at(i)
for m in ms:
_k=(_cur, m.group(1))
if _k in _seen: continue
_seen.add(_k)
tail=ln[m.end():]
if re.match(r'\s*[((]', tail[:2]): continue # 제목 병기됨
if tail[:1]=='~' or (m.start()>0 and ln[m.start()-1]=='~'): continue # v4.1 범위 표기 §6.1~§6.5 (집합 지정)
if re.match(r'에\s*\d', tail): continue # 계수: §4에 1개
if re.match(r'의(?![가-힣])', tail): continue # 소유격: §3의 세 값
noparen.append(m.group(0))
have={str(n) for n,_ in SEC}
for lv,t,_,_ in hs:
if lv==3: have.add(t.split()[0])
if lv==4: have.add(t.split()[0])
for lv,t,_,_ in hs:
if lv==3 and re.match(r'^5\.P\d+', t): have.add(t.split()[0])
unres=sorted(r for r in refs if r not in have and r.split('.')[0] not in have)
ck('S10', not unres, '미해소=%s' % unres[:5])
ck('S10b', len(noparen)<=0, '제목 병기 누락 %d건 예:%s' % (len(noparen), noparen[:3]))
# S11 §4.4 (위치 무관) + §2.2 합집합
h44=next((h for h in hs if h[0]==3 and h[1].startswith('4.4')), None)
e11=[]
if h44:
t44='\n'.join(lines[h44[2]:h44[3]])
# §4.4 안에는 표가 여럿 올 수 있다(경로별 구간표, 보조표). 헤더에 기산사건과 이율이 함께
# 있는 블록만 '구간표'로 보고, 각 블록의 헤더 행은 건너뛴다.
blocks=[]; cur=None
for ln in t44.split('\n'):
t=ln.strip()
if t.startswith('|') and t.endswith('|'):
cells=[c.strip() for c in t.strip('|').split('|')]
if set(t) <= set('|-: '): continue
if cur is None: cur={'hdr':cells,'rows':[]}
else: cur['rows'].append(cells)
elif cur is not None:
blocks.append(cur); cur=None
if cur is not None: blocks.append(cur)
gu=[b for b in blocks if '기산사건' in b['hdr'] and any('이율' in c for c in b['hdr'])]
if gu:
for b in gu:
for r in b['rows']:
if len(r)<5 or any(not c for c in r[1:5]): e11.append('§4.4행 결측:%s' % r[:2])
elif not any(TRI.match(l) for l in t44.split('\n')):
e11.append('§4.4에 구간표(기산사건·이율 헤더)도 3분값도 없음')
else: e11.append('§4.4 없음')
lit=set(re.findall(r'부대청구 주문 문언\[[^\]]+\]:\s*"([^"]*)"', body))
def _norm_lit(x):
x = re.sub(r'^\s*부대청구 주문 문언\[[^\]]*\]:\s*', '', x.strip())
return x.strip().strip('"').strip('`').strip()
# §2 안에서 헤더에 '부대청구 주문 문언'이 있는 표 블록만, 그 열만 대조한다.
r2=sec_of(hs,lines,2); col=None; started=False
for ln in (lines[r2[0]:r2[1]] if r2 else []):
t=ln.strip()
if t.startswith('|') and t.endswith('|'):
cells=[c.strip() for c in t.strip('|').split('|')]
if set(t) <= set('|-: '): continue
if not started:
if '부대청구 주문 문언' in cells:
col=cells.index('부대청구 주문 문언'); started=True
continue
if col is not None and len(cells)>col and cells[col] and cells[col] != '-':
if lit and _norm_lit(cells[col]) not in lit:
e11.append('§2.2 문언 불일치:%s' % cells[col][:24])
elif started and t: break
ck('S11', not e11, '; '.join(e11[:4]))
# S12 §3 5필드 (3분 값 항은 면제)
e12=[]
for j,(lv,t,i,e) in enumerate(hs):
if lv!=3 or not re.match(r'^3\.\d', t): continue
seg='\n'.join(lines[i+1:e]); cont=[l.strip() for l in seg.split('\n') if l.strip()]
if cont and TRI.match(cont[0]): continue # 면제
for f in ('조사방식','증명책임','절차효과'):
if f not in seg: e12.append('%s:%s' % (t.split()[0], f))
ck('S12', not e12, '; '.join(e12[:6]))
# S13 §6.0
r6=sec_of(hs,lines,6); h60=next((h for h in hs if h[0]==3 and h[1].startswith('6.0')), None)
e13=[]
if not h60: e13.append('§6.0 없음')
else:
seg=lines[h60[2]:h60[3]]; blk=[]; started=False
for ln in seg: # 헤더 행에서 시작해 표가 끊기면 종료
t=ln.strip()
if t.startswith('|') and t.endswith('|'):
cells=[c.strip() for c in t.strip('|').split('|')]
if not started:
if len(cells)>=2 and cells[1]=='성질': started=True
continue
if set(t) <= set('|-: '): continue
blk.append(cells)
elif started and t: break
rows=blk
if not rows: e13.append('§6.0 표(헤더 `| 상대방 주장 | 성질 | …`) 없음')
for r in rows:
if len(r)<2 or r[1] not in SUNG_OK: e13.append('성질 이상:%s' % (r[1] if len(r)>1 else '-'))
ck('S13', not e13, '; '.join(e13[:5]))
# S14
e14=[]
for sm in (Y.get('source_materials') or []):
p = sm.get('path') if isinstance(sm, dict) else str(sm)
if not p: continue
cand=[os.path.join(root,p), os.path.join(os.getcwd(),p)]
# 자료 파일은 사건 완료 후 <폴더>_done/ 으로 이관된다. 같은 파일명을 그곳에서도 찾는다.
for b in list(cand):
d,f0=os.path.split(b)
if d and not d.endswith('_done'): cand.append(os.path.join(d+'_done', f0))
ok=False
for c in cand:
d,b=os.path.dirname(c), nfc(os.path.basename(c))
if os.path.isdir(d) and b in {nfc(x) for x in os.listdir(d)}: ok=True; break
if not ok: e14.append(p)
ck('S14', not e14, '미실재=%s' % e14[:3])
# ── 린트
ck('L-a', all(re.match(r'^[\x00-\x7f]+$', k) for k in Y.keys()) if Y else True,
'비ASCII 키=%s' % [k for k in Y if not re.match(r'^[\x00-\x7f]+$', k)][:3])
eb=[]
for h in hs:
if h[0]==3 and (h[1].startswith('4.4') or re.match(r'^5\.P\d+', h[1])):
for row in table_rows('\n'.join(lines[h[2]:h[3]])):
j=' | '.join(row)
if re.search(r'연\s*\d+(?:\.\d+)?%', j) and not re.search(r'시행|부칙|\d{4}\.\s*\d', j):
eb.append(j[:40])
ck('L-b', not eb, '; '.join(eb[:3]))
toc = os.path.join(root, '요건사실과주장증명책임_13판_목차_페이지표시.txt')
ec=[]
if os.path.exists(toc):
titles={t.strip() for t in io.open(toc,encoding='utf-8',errors='replace').read().split('\n')
if 4 <= len(t.strip()) <= 40}
r124=next((h for h in hs if h[0]==3 and h[1].startswith('12.4')), None)
span=range(r124[2], r124[3]) if r124 else range(0,0)
for lv,t,i,_ in hs:
if i in span or lv==1: continue
core=re.sub(r'^[\d.]+\s*|^§\d+\.\s*|^R-\S+\s*', '', t).strip()
if core in FIX_TITLES: continue
if core in titles: ec.append(t)
ck('L-c', not ec, '13판 표제와 동일한 헤딩=%s' % ec[:3])
ed=[t for lv,t,_,_ in hs if lv in (3,4) and re.match(r'^6\.[1-6]', t)
and any(w in t for w in DENY_LEAK)]
ck('L-d', not ed, '; '.join(ed[:3]))
r1s = sec_of(hs,lines,1); r12s = sec_of(hs,lines,12)
ee=[]
if r1s and r12s:
for i,ln in prose_lines(lines, mask, r1s[0], r12s[0]):
s2=ln
for ok in SIL_OK: s2=s2.replace(ok,'')
for bad in SIL_BAD:
if bad in s2: ee.append('%d행:%s' % (i, bad))
ck('L-e', not ee, '; '.join(ee[:5]))
# L-f (v4.1) 요건 블록 10필드·항변 블록 8필드의 존재와 순서, 주장책임/증명책임의 슬래시 1개, 추정·전환 열거값
ef=[]
def _fields(blk):
return re.findall(r'^- \*\*(.+?)\*\*:', blk, re.M)
def _chk(no, blk, want):
got=_fields(blk); miss=[f for f in want if f not in got]
if miss: ef.append('%s 결측:%s' % (no, miss[:2])); return
idx=[got.index(f) for f in want]
if idx!=sorted(idx): ef.append('%s 순서' % no)
bur=field(blk,'주장책임 / 증명책임')
if bur.count('/')!=1 or not all(p.strip() for p in bur.split('/')): ef.append('%s 슬래시:%s' % (no, bur[:20]))
for rid,_,blk in req_blocks(lines, hs):
_chk(rid, blk, REQ_FIELDS)
v=field(blk,'추정·전환').strip('`*').strip()
if v:
m=CHU_MIXED.match(v)
base=m.group(1).strip() if m else v
if base not in CHU_OK: ef.append('%s 추정·전환:%s' % (rid, v[:24]))
for no,blk in def_blocks(lines, hs): _chk(no, blk, DEF_FIELDS)
ck('L-f', not ef, '%d건 예:%s' % (len(ef), ef[:3]))
# L-g (v4.1) 본문(§1~§11)에 등장하는 조문 토큰이 §12 텍스트에 등재되어 있는가 (범위 표기 제A조~제B조는 전개)
eg=[]
if r1s and r12s:
t12=sec_text(lines, r12s)
have12=set(re.findall(r'제(\d+조(?:의\d+)?)', t12))
for a,b in re.findall(r'제(\d+)조\s*(?:[~∼~-]|내지|부터)\s*제(\d+)조', t12): # 범위 표기 전개
for n in range(int(a), int(b)+1): have12.add('%d조' % n)
seen=set()
for i in range(r1s[0], r12s[0]):
if mask[i]: continue
for tok in re.findall(r'제(\d+조(?:의\d+)?)', lines[i]):
if tok in seen: continue
seen.add(tok)
if tok not in have12: eg.append('제'+tok)
ck('L-g', not eg, '§12 미등재 %d건 예:%s' % (len(eg), eg[:4]))
return res
def main():
args=[a for a in sys.argv[1:] if not a.startswith('--')]
if not args: print('사용: rf_gate.py <문서.md> [--project] [--check-idempotent]'); return 2
path=args[0]
if '--project' in sys.argv or '--check-idempotent' in sys.argv:
t0=io.open(path,encoding='utf-8').read()
t1,ok=project_s7(t0)
if ok: io.open(path,'w',encoding='utf-8').write(t1)
if '--check-idempotent' in sys.argv:
t2,_=project_s7(t1)
same = hashlib.sha256(t1.encode()).hexdigest()==hashlib.sha256(t2.encode()).hexdigest()
print('IDEMPOTENT %s' % ('PASS' if same else 'FAIL'))
res=run(path); bad=[r for r in res if r[1]=='FAIL']
for i,st,msg in res: print('%-5s %-4s %s' % (i, st, msg))
print('\n%d/%d PASS' % (len(res)-len(bad), len(res)))
return 1 if bad else 0
if __name__=='__main__': sys.exit(main())