Files
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

155 lines
8.3 KiB
Python

"""출처 한정 발췌 초안. 사건별 검토 및 보완과 함께 실행한다."""
from pathlib import Path
import re,json,hashlib
HERE=Path(__file__).resolve().parent
ROWS=json.loads((HERE/'batch_0.json').read_text())
NOTES=json.loads((HERE/'agent0_notes.json').read_text())
def sections(text):
matches=list(re.finditer(r'^(#{2,4}) ([^\n]+)\n',text,re.M)); ret=[]
for i,m in enumerate(matches):
ret.append((len(m[1]),m[2],text[m.end():matches[i+1].start() if i+1<len(matches) else len(text)]))
return ret
def clean(s):
s=re.sub(r'\[([^\]]+)\]\(https?://[^\s)]+\)',r'\1',s)
s=re.sub(r'https?://[^\s|<>`]+','',s)
s=re.sub(r'<!--.*?-->','',s,flags=re.S)
# Remove only standalone duplicated machine text, not its legal conditions.
s=re.sub(r'^부대청구 주문 문언[^\n]*\n?','',s,flags=re.M)
s=re.sub(r'^.*`has_branch`.*(?:블록|존재|true)[^\n]*\n?','',s,flags=re.M)
return s.strip()
def pure_evidence(line):
# Proof practice is retained wholesale: many fields contain presumptions and exceptions.
return False
def extract(row):
src=Path(row['source']); s=src.read_text(); meta=s.split('---',2)[1]
def val(k):
m=re.search(r'^'+k+r':\s*(.+)$',s,re.M); return m[1] if m else '"UNKNOWN"'
title=re.search(r'^# (.+)',s,re.M)[1].replace('요건사실론:','').strip()
out=f'''---
case_kind_id: {val('case_kind_id')}
case_kind_name: {val('case_kind_name')}
doc_version: "v2"
source_file: "../raw/{src.name}"
source_sha256: "{row['sha256']}"
source_law_as_of: {val('law_as_of')}
source_verification_status: {val('verification_status')}
extraction_date: "2026-09-28"
verification_scope: "원문 대비 추출; 외부 법령·판례 독립 재검증 미실시"
---
# 요건사실 항목 추출: {title}
[원문](../raw/{src.name})의 요건사실·적용 조건·예외·주장증명책임 및 필요한 항변·기간·주문 특정 조건을 발췌·통합하였다. 원문의 기준일과 검증상태를 승계하며 개별 사건의 사실·금액·날짜를 생성하지 않는다. 아래 절 번호와 본문 `§` 참조는 **원문 위치**를 가리킨다. `LAW`는 조문, `PREC`는 판례, `BOOK:RF13`은 『요건사실과 주장·증명책임』 제13판 면수이며 각 요건·항변에 연결된 식별자를 유지한다. `UNKNOWN`·`UNVERIFIED`·`QUALIFIED`는 삭제하거나 확인 완료로 승격하지 않는다. 원문의 실질 판단·부담 배분을 변경하는 법률적 교정은 하지 않았다.
'''
secmajor=None; minor=None; kept=[]; dropped=[]
for level,h,body in sections(s):
if level==2:
m=re.match(r'§(\d+)',h);secmajor=int(m[1]) if m else -1;minor=None
elif level==3:
m=re.match(r'(\d+\.(?:P\d+|\d+))',h);minor=m[1] if m else None
keep=False
if secmajor in [1]: keep=minor in ['1.1','1.2','1.3','1.4']
if secmajor==2: keep=minor in ['2.1','2.2','2.3']
if secmajor==3: keep=minor in ['3.1','3.2','3.3']
if secmajor==4: keep=level==2 or minor in ['4.0','4.2','4.4'] or h.startswith('R-')
if secmajor in [5,6]:keep=True
if secmajor==8:keep=minor=='8.4'
if secmajor==9:keep=minor=='9.4'
if secmajor==10:keep=minor=='10.4'
if secmajor==11:keep=False
if secmajor==12:keep=minor=='12.6'
# Key applicability exceptions in the statute register, without recreating a source inventory.
if secmajor==12 and minor=='12.1':
special=[]
for line in body.splitlines():
if line.startswith('|'):
c=[x.strip() for x in line.strip('|').split('|')]
if len(c)>2:
tail=c[-1] if not c[-1].startswith('http') else c[-2]
if re.search(r'부칙|경과|시행 전|시행 후|소급|적용례|적용시점|적용 시점|이후.*(?:계약|체결|갱신|개시)|이전.*(?:계약|체결|갱신|개시)',tail) and not re.search(r'경과규정.*(?:없|해당 없)|부칙.*(?:없|해당 없)',tail):
special.append('- '+clean(c[0]+' — '+tail))
elif line.strip() and not line.startswith('|') and re.search(r'부칙|경과규정|적용례|소급|시행 전|시행 후',line):special.append(clean(line))
if special:out+='## 적용 시점·경과규정 보충 (원문 §12.1)\n\n'+'\n\n'.join(special)+'\n\n'
if not keep:
if body.strip():dropped.append({'heading':h,'body':body})
continue
new=clean(body)
# Empty optional fields and evidence collection inventories add no element.
new=re.sub(r'^- \*\*(?:추정·전환|다중 대응)\*\*:\s*없음\s*$', '',new,flags=re.M)
def trim_evidence(m):
sentence=m[0]
if re.search(r'추정|증명책임|주장책임|요건|효력|부담|예외|단서|조건|기준시|도래|무효|한정|선의|악의|법률상|사실상',sentence):return sentence
dropped.append({'heading':h,'body':sentence})
return ''
new=re.sub(r'(?:전형(?:적)? 증거(?:는|로는)|전형적 증거방법은)[^\n]*?(?:다\.|이다\.)',trim_evidence,new)
# Repeated invariant field names become compact lines; all substantive words remain.
new=re.sub(r'^- \*\*소변경·석명 요부\*\*:\s*(?:불요|해당 없음)\s*$', '',new,flags=re.M)
# Source-only bibliographic/research rows in §12.7 do not enter the legal extraction.
if minor=='12.7':
ls=[]
for line in new.splitlines():
if re.search(r'정독 총량|총 정독|목차.*문자열|오프셋|시작면.*종료면|종료면.*교정|SHA-?256|content_hash|fence|자동 점검|파이프라인|Markdown',line) and not re.search(r'UNKNOWN|UNVERIFIED|요건사실|증명책임|부담|적용|항변',line):
dropped.append({'heading':h,'body':line});continue
ls.append(line)
new='\n'.join(ls)
# For the mapping table, repeated full monetary templates add no element information.
if minor=='2.2':
lines=new.splitlines(); mapped=[]; ix=None
for l in lines:
if l.startswith('|'):
cells=l.strip().strip('|').split('|')
if '부대청구 주문 문언' in l:ix=next(i for i,v in enumerate(cells) if '부대청구 주문 문언' in v)
if ix is not None and len(cells)>ix:cells.pop(ix)
l='|'+'|'.join(cells)+'|'
mapped.append(l)
new='\n'.join(mapped)
if not new and level!=4 and not (secmajor==5 and level==3):continue
# Remove empty heading-only root sections; keep original subheadings as source locators.
heading=('#'*min(level,4))+' '+h
out+=heading+'\n\n'+new+'\n\n'
kept.append(h)
out+='## 적용·분류 및 근거의 유보 (원문 §12.7 통합)\n\n'+NOTES[row['case']]+'\n\n'
# Preserve uncertainty attached to a substantive authority without its source inventory.
evidence_notes=[]
for level,hh,bb in sections(s):
if not hh.startswith('12.2'):continue
headers=None
for ll in bb.splitlines():
if not ll.startswith('|'):continue
cells=[c.strip() for c in ll.strip().strip('|').split('|')]
if 'fulltext_verified' in cells:
headers=cells;continue
if headers and len(cells)==len(headers):
ix=headers.index('fulltext_verified')
if '아니오' not in cells[ix]:continue
ti=next((j for j,v in enumerate(headers) if '적용 요건' in v),None)
if ti is None:continue
target=cells[ti]
if '본문 근거로 쓰지' in target or target in ['해당 없음','9.2']:continue
status=next((cells[j] for j,v in enumerate(headers) if v=='상태'),'')
evidence_notes.append('| '+clean(target)+' | '+clean(cells[0])+' | UNVERIFIED — 전문확인 아니오; 원문 평가: '+clean(status)+' |')
if evidence_notes:
out+='## 요건·항변별 근거 확인의 한계 (원문 §12.2)\n\n원문의 법리 평가와 전문 확인 여부는 별개다. 아래는 본문에 연결된 근거의 미확인 표지이며 출처 목록이 아니다.\n\n| 적용 요건·항 | 근거 식별자 | 승계한 한계 |\n|---|---|---|\n'+'\n'.join(evidence_notes)+'\n\n'
out=re.sub(r'\n{3,}','\n\n',out).rstrip()+'\n'
# All URLs are omitted; local source links remain.
assert not re.search(r'https?://',out)
return out,dropped,kept
if __name__=='__main__':
report=[]
for row in ROWS:
out,drop,kept=extract(row)
p=Path(row['output'])
# Re-runs only touch this batch's own outputs and retain baseline sources.
assert hashlib.sha256(Path(row['source']).read_bytes()).hexdigest()==row['sha256']
p.write_text(out)
report.append({'case':row['case'],'output':row['output'],'bytes':len(out.encode()),'source_bytes':row['bytes'],'kept_sections':kept,'dropped_sections':drop})
(HERE/'agent0_draft_audit.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
print('drafts',len(report),'retained byte ratio',round(sum(x['bytes'] for x in report)/sum(x['source_bytes'] for x in report),3))