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>
129 lines
7.6 KiB
Python
129 lines
7.6 KiB
Python
from pathlib import Path
|
|
import json,re,hashlib
|
|
|
|
ROOT=Path.cwd()
|
|
BASE=ROOT/'plans/extract-remaining-elements'
|
|
batch=json.loads((BASE/'batch_3.json').read_text())
|
|
case_notes=json.loads((BASE/'agent3_case_notes.json').read_text())
|
|
|
|
def clean(s):
|
|
s=re.sub(r'\[([^\]]+)\]\(https?://[^)]+\)',r'\1',s)
|
|
s=re.sub(r'https?://[^\s<>|)]+','',s)
|
|
s=re.sub(r'(?m)^---\s*$','',s)
|
|
return re.sub(r'\n{3,}','\n\n',s).strip()
|
|
|
|
def pieces(t):
|
|
matches=list(re.finditer(r'^#{2,4} .+$',t,re.M))
|
|
return [(m.group(),t[m.end():matches[i+1].start() if i+1<len(matches) else len(t)]) for i,m in enumerate(matches)]
|
|
|
|
def getsection(t,num):
|
|
m=re.search(r'^### '+re.escape(num)+r'(?:\s|\.)[^\n]*',t,re.M)
|
|
if not m:return ''
|
|
tail=t[m.end():]
|
|
end=re.search(r'^#{2,3} ',tail,re.M)
|
|
return t[m.start():m.end()+(end.start() if end else len(tail))]
|
|
|
|
def fields(body,kind):
|
|
# Drop source bibliography repetition and evidence-gathering instructions only.
|
|
# Every substantive condition, presumption, alternative and burden remains.
|
|
paras=re.split(r'(?m)(?=^- \*\*)',body)
|
|
keep=[]
|
|
for p in paras:
|
|
m=re.match(r'- \*\*([^*]+)\*\*',p)
|
|
if m and m.group(1)=='규범적 근거':
|
|
if re.search('시행|개정|경과|부칙|이전|이후|종전|현행|단서|적용제외',p):keep.append(p)
|
|
continue
|
|
if m and m.group(1)=='증명 실무':
|
|
# Legal presumptions/burden exceptions embedded in the evidence field
|
|
# must not disappear along with the list of exhibits.
|
|
ss=re.findall(r'.*?(?:[다임함됨]\.\s+|$)',p,re.S)
|
|
legal=[s for s in ss if re.search('증명책임|추정|전환|반증|법률상|처분문서|진정성립|의제|증명도|증명방해|단정|만으로|아니|않|없|요구|충분|요건|기산|기준|성질|조건|불문|권한|효력|부족|부담|당연|별개|공제|상계|시효|제척|예외|무효|적격',s)]
|
|
if legal:keep.append('- **증명상 적용 조건**: '+' '.join(re.sub(r'^- \*\*증명 실무\*\*:\s*','',s) for s in legal)+'\n')
|
|
continue
|
|
keep.append(p)
|
|
return ''.join(keep)
|
|
|
|
def limitation(t):
|
|
s=getsection(t,'12.7')
|
|
lines=s.splitlines();out=[]
|
|
for l in lines:
|
|
# Pure record/errata rows are not extraction conditions.
|
|
if l.startswith('|') and re.search(r'\|\s*기록\s*\||골격 v2 errata',l):continue
|
|
# Remove concrete audit-history sentences while preserving limitation text.
|
|
l=re.sub(r'라운드\s*\d+에서.*?갱신\*\*하였다\.', '', l)
|
|
out.append(l)
|
|
return '\n'.join(out).replace('### 12.7 검증상태와 미해결','### 원문 §12.7: 적용상 한계와 미해결')
|
|
|
|
def uncertain_authorities(t,body):
|
|
result=[];header=[]
|
|
for line in getsection(t,'12.2').splitlines():
|
|
if not line.startswith('|'):continue
|
|
cols=[c.strip() for c in line.strip('|').split('|')]
|
|
if '사건번호' in cols:
|
|
header=cols;continue
|
|
if len(cols)!=len(header) or not header:continue
|
|
record=dict(zip(header,cols));flag=record.get('fulltext_verified',record.get('전문',''))
|
|
if not re.search('false|아니[오요]|미확인|T1',flag):continue
|
|
case=record.get('사건번호','');cm=re.search(r'\d{2,4}[가-힣]+\d+',case)
|
|
if not cm or cm.group() not in body:continue
|
|
target=next((v for k,v in record.items() if '적용 요건' in k or '적용 위치' in k),'본문 인용')
|
|
if '본문 미사용' in target:continue
|
|
result.append('| PREC:'+cm.group()+' | '+target+' | '+record.get('상태','원문 참조')+' | '+flag+' |')
|
|
if not result:return ''
|
|
return '\n'.join(['### 요건·항변에 연결된 근거의 미확인 표지 (원문 §12.2)','원문의 전문확인 여부와 평가반영 상태를 구별한다. 아래 표는 근거 목록이 아니라 본문에 연결된 미확인 범위이며, 새 검증을 뜻하지 않는다.','| 근거 ID | 적용 연결 | 원문 상태 | 원문 전문확인 값 |','|---|---|---|---|']+result)
|
|
|
|
def extract(x):
|
|
src=ROOT/x['source'];t=src.read_text()
|
|
assert hashlib.sha256(src.read_bytes()).hexdigest()==x['sha256']
|
|
meta={k:re.search(r'^'+k+r':\s*(.+)$',t,re.M).group(1) for k in ['case_kind_id','case_kind_name','law_as_of','verification_status']}
|
|
out=['---','document_type: "요건사실 항목 추출"','doc_version: "v2"']
|
|
out.extend(k+': '+v for k,v in meta.items())
|
|
out.extend(['source_file: '+json.dumps(src.name,ensure_ascii=False),'source_sha256: "'+x['sha256']+'"','---','',f'# 요건사실 항목: {x["case"]}','',
|
|
f'> 원문: [요건사실론_{x["case"]}_v1_edit.md](../raw/{src.name})',
|
|
'> 원문에 기재된 대한민국 민사청구의 요건·적용 조건·예외·주장증명책임을 추출한 검토용 자료다. 법령 기준일 및 검증 표지는 원문에서 승계하며, 이번 편집에서 법령·판례를 독립적으로 재검증하지 않았다. 구체적 사건의 사실·적용시점은 별도로 대조한다.',
|
|
'> 절 번호와 요건·항변·권위 ID는 원문 연결을 위해 유지한다. 생략된 절을 가리키는 참조는 원문의 해당 절을 뜻한다. 원문 총괄표보다 개별 요건의 조건과 말미 유보사항을 함께 적용한다.',''])
|
|
# Retain routing and exclusions that decide which elements can be used.
|
|
out.append('## 청구경로와 적용 범위')
|
|
out.extend(['### 적용 경로 선택',case_notes[x['case']]['scope']+' (원문 §1·§4·§5·§12 대조 요약)'])
|
|
for n in ['1.1','1.2','1.4']:out.append(getsection(t,n))
|
|
out.append('## 주문 특정·청구 조건·기간')
|
|
for n in ['2.2','2.3','3.1','3.2','3.3']:out.append(getsection(t,n))
|
|
sec4=t[t.index('## §4.'):t.index('## §6.')]
|
|
# Redundant element inventories are replaced by the actual element records.
|
|
for h,b in pieces(sec4):
|
|
if h.startswith('### 4.1') or h.startswith('### 4.3'):continue
|
|
if h.startswith('## §4.') or h.startswith('## §5.'):
|
|
out.extend([h,b]);continue
|
|
if re.match(r'#### R-',h):b=fields(b,'element')
|
|
# Remove only fenced duplicate requirement inventories, not prose criteria.
|
|
b=re.sub(r'```[^\n]*\n(?:R-[^\n]*\n)+```','',b)
|
|
b=re.sub(r'(?m)^\*\*요건 목록\*\*\s*$','',b)
|
|
out.extend([h,b])
|
|
s6=t[t.index('## §6.'):t.index('## §7.')]
|
|
out.append(s6)
|
|
# §7 includes potentially lossy summaries; keep target links only and rely
|
|
# on full conditional burden text above.
|
|
s7=t[t.index('## §7.'):t.index('## §8.')]
|
|
rows=[l for l in s7.splitlines() if l.startswith('| R-')]
|
|
if rows:
|
|
out.extend(['## 요건별 대응 항변 연결','| 요건 ID | 대응 항변 ID |','|---|---|'])
|
|
for r in rows:
|
|
cols=[c.strip() for c in r.strip('|').split('|')]
|
|
out.append('| '+cols[0]+' | '+cols[-1]+' |')
|
|
out.append('## 요건 분류와 미해결 사항')
|
|
out.append(getsection(t,'12.6').replace('### 12.6 학설','### 원문 §12.6: 요건 분류에 관련된 견해'))
|
|
out.append('### 원문 §12.7에서 승계한 적용상 한계')
|
|
out.extend('- '+s for s in case_notes[x['case']]['limits'])
|
|
out.append(uncertain_authorities(t,'\n'.join(out)))
|
|
text='\n\n'.join(s for s in out if s.strip())
|
|
# Preserve front matter, but collapse superfluous blank lines in body.
|
|
front,body=text.split('# 요건사실 항목:',1)
|
|
return re.sub(r'\n\n','\n',front).rstrip()+'\n\n# 요건사실 항목: '+clean(body)+'\n'
|
|
|
|
if __name__=='__main__':
|
|
for x in batch:
|
|
p=ROOT/x['output']
|
|
if p.exists():raise RuntimeError('Existing output: '+str(p))
|
|
p.write_text(extract(x))
|
|
print('Drafts created:',len(batch))
|