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>
109 lines
16 KiB
Python
109 lines
16 KiB
Python
import pathlib,json,re,hashlib
|
|
W=pathlib.Path(__file__).parent;identity=json.loads((W/'identity.json').read_text());C=identity['case'];review=json.loads((W/'comprehensive_review.json').read_text());assert review['comprehensive_reviews']==1
|
|
text=(W/'draft.md').read_text();source=(W/'source.snapshot.md').read_text();ls=source.splitlines();units=json.loads((W/'units.json').read_text());req=json.loads((W/'requirements.json').read_text());history=json.loads((W/'history.json').read_text());positions=json.loads((W/'positions.json').read_text());amend=[]
|
|
def amendblock(n,new,why):
|
|
global text
|
|
marker='<a id="source-L'+str(n)+'"></a>';a=text.index(marker)+len(marker);b=text.find('\n<a id="source-',a)
|
|
# use exact first paragraph/source-table/form-field block only
|
|
old=text[a:].lstrip('\n').split('\n\n',1)[0]
|
|
# special multiline source block is only one paragraph for targeted n
|
|
start=text.index(old,a);text=text[:start]+new+text[start+len(old):];amend.append((n,old,new,why))
|
|
amendblock(7,'| 사건종류 | 제권판결에 대한 불복의 소 |','F01 표제 제한')
|
|
amendblock(10,text[text.index('<a id="source-L10"></a>'):].split('\n')[1].replace('| 적용 제외 |','| 적용제외 |'),'F01 표제 제한')
|
|
text=text.replace('### 메타데이터\n\n','### 메타데이터\n\n| 항목 | 값 |\n|---|---|\n',1)
|
|
old=ls[21]
|
|
new=old.replace('각 호에 해당하는 사실을 청구원인으로 특정하지 못하면 부적법하므로 Q-02를 통과하지 못한 사건은 청구취지를 생성하지 않고 STOP-R05로 보낸다.','각 호에 해당하는 사실을 청구원인으로 특정해야 한다는 법적 조건을 유지한다. 아직 호가 미특정이면 STOP-C02에서 해당 부분 보완 대기 또는 주장 근거 있는 후보의 재검토 초안을 기록한다. 확인된 모든 호 비해당인 경우에만 해당 형성 구성을 유효 주문으로 생성하지 않고 STOP-R05로 전환한다.')
|
|
amendblock(22,new,'F03 사유 한정 요건과 미특정 처리 분리')
|
|
amendblock(26,ls[25]+' 변경 주문 가능 명제는 STOP-C05의 적용 미확정 제한과 결합하여만 읽는다. 공시최고 단계 유보 규정에서 불복판결 변경 허용을 직접 정한 명문은 v2에서 확인되지 않았다. FORM-05의 검토 후보를 확정 일반규칙으로 승격하지 않는다.','F04 사용 지점 제한')
|
|
amendblock(139,ls[138]+' 위 마지막 구간 지시는 LC-01의 손해발생일과 충돌 가능성이 있으므로 해당 경우 확정 실행하지 않고 금전 구간만 적용 미확정으로 기록한다. 손해발생일·송달일·시적 적용 검토가 제공되면 Q-10/FORM-07·08로 복귀한다.','F05 이자 적용 충돌 명시')
|
|
amendblock(146,ls[145].replace('특례이율의 현재 값은 SRC-L12에서 확인하고','특례이율의 적용 값은 실제 제공된 SRC-L12의 내용·시점에서 확인하고')+'\n\nSRC-L12의 URL을 열라는 뜻이 아니며 제공된 자료의 적용시점이 부족하면 해당 이율 구간만 재검토한다.','F05 제공 자료 한정')
|
|
amendblock(266,'**작성 전에 연결할 정보**: §3의 비증권형 표시 요소 전부. 실권된 권리 내용, 토지 소재·지번·지목·면적 또는 건물 표시, 등기소·접수연월일·접수번호·등기 목적·순위번호를 정본과 연결한다. 아래 등기 말소용 예시는 축약이므로 전체 요소의 대체 목록이 아니다.','F06 순위번호와 전체요소')
|
|
# Add use-site limits without altering pure prayer text.
|
|
for n,limit in [(211,'LC-02: 비증권 복수 또는 증권·비증권 혼합을 이 증권형 표면 문구로 자동 조립하지 않는다. 판결·권리별 정보를 보존하고 조립만 보완 대기.'),(218,'LC-02: 비증권형에 무효 선언 문구를 자동 대입하지 않는다. 비증권 변경 조합은 적용 미확정.'),(226,'LC-02: 복수·부분 비증권을 단일 전부 취소 문형으로 임의 축소하지 않고 해당 범위를 보완 대기로 보존.')]:
|
|
marker='<a id="source-L'+str(n)+'"></a>';start=text.index(marker);end=text.index('\n\n',text.index('\n',start)+1);text=text[:end]+'\n\n'+limit+text[end:]
|
|
text=text.replace('**미확인 처리**: 금액·기산일·이율·송달 서면과 송달일은 개별 변수와 질의. 법정 전제 미확인은 금전 항의 재검토이며 독립 형성 항은 진행.','**미확인 처리**: 금액·기산일·이율·송달 서면과 송달일은 개별 변수와 질의. 법정 전제 미확인은 금전 항의 재검토이며 독립 형성 항은 진행. LC-01의 시점 역전 및 LC-03의 실제 장래이행은 이 통상 두 구간 문형을 자동 치환하지 않고 해당 구간만 보완 대기.')
|
|
# F08 audit history explicitly not active instructions.
|
|
extra='\n### 1회 종합검증에서 발견한 개선과 반영\n\n| 개선 | 대상 | 반영 |\n|---|---|---|\n'
|
|
for f in review['findings']:extra+='| '+f['id']+' | '+f['location']+' | '+f['finding']+' 해당 범위 수정 완료. |\n'
|
|
extra+='\n다음은 제작 이력 — 실행 지시 아님. 수정 전 표현은 추적용으로만 보존한다.\n\n| 원문 위치 | 수정 전 | 변경 이유 | 새 위치 |\n|---|---|---|\n'
|
|
esc=lambda x:x.replace('|','|').replace('\n','<br>')
|
|
for n,old,new,why in amend:extra+='| v2 L'+str(n)+' | '+esc(ls[n-1])+' | '+why+' | [수정 규칙](#source-L'+str(n)+') |\n'
|
|
text=text.replace('### 절·ID·변수 대응과 호환성',extra+'\n### 절·ID·변수 대응과 호환성')
|
|
# F02 anchors in first cell and restore consecutive table rows; headings remain separated.
|
|
text=re.sub(r'<a id="(source-L\d+)"></a>\n\|',lambda m:'| <a id="'+m[1]+'"></a>',text)
|
|
while re.search(r'(\|[^\n]*\|)\n\n+(?=\|)',text):text=re.sub(r'(\|[^\n]*\|)\n\n+(?=\|)',r'\1\n',text)
|
|
# appendix historical metadata table needs heading
|
|
text=text.replace('| <a id="source-L11"></a>','| 이력 항목 | 승계 내용 |\n|---|---|\n| <a id="source-L11"></a>',1)
|
|
# Source table header at L99 had missing delimiter? Its original separator is kept. All existing rows intact.
|
|
text=text.replace('§4과 §4의 범위','§4의 금전·병합 규칙 범위')
|
|
# Map individual syntax/format lines precisely instead of claiming missing legal evidence.
|
|
section_for_line=lambda n: ('§0' if n<20 else '§2' if n<30 else '§1' if n<57 else '§2' if n<112 else '§3' if n<131 else '§4' if n<167 else '부록 B' if n<181 else '§5' if n<271 else '§7' if n<289 else '부록 A' if n<333 else '§7')
|
|
for u in units:
|
|
if u['kind'].startswith('순수'):
|
|
old='| '+u['id']+' | L'+str(u['line'])+' '+esc(u['text'])+' | 부록 B 절 대응 및 대응 절 제목 |'
|
|
dest=section_for_line(u['line'])+' 제목·표 구조 (원문 L'+str(u['line'])+')'
|
|
text=text.replace(old,'| '+u['id']+' | L'+str(u['line'])+' '+esc(u['text'])+' | '+dest+' |');u['destination']=dest
|
|
meaningful=[x for x in units if x['kind']=='의미 단위']
|
|
# scoped content checks for 8 findings; not a second comprehensive review
|
|
clean_metadata=re.sub(r'<a id="[^"]+"></a>', '', text)
|
|
assert re.search(r'\|\s*사건종류\s*\|',clean_metadata) and re.search(r'\|\s*적용제외\s*\|',clean_metadata)
|
|
assert 'Q-02를 통과하지 못한 사건은 청구취지를 생성하지 않고 STOP-R05로 보낸다.' not in text.split('## 부록 B.')[0]
|
|
assert 'F06 순위번호' in text
|
|
assert text.count('```')%2==0
|
|
assert not re.search(r'<a id="source-L\d+"></a>\n\|',text)
|
|
for n in (211,218,226):
|
|
p=text.index('id="source-L'+str(n)+'"');assert 'LC-02' in text[p:p+650]
|
|
summary=f'''종합 검증 1회 완료. 원문 {len(ls)}행의 {len(units)}개 단위(의미 {len(meaningful)}개, 서식·구조 {len(units)-len(meaningful)}개)를 원문→재작성과 역방향으로 대조했고, 형식 요구 {len(req)}개와 정적 시나리오 {len(review['scenarios'])}개를 검토했다. 발견한 8개 개선을 반영한 뒤 그 수정 범위 및 저장 무결성만 확인하였다. 검증 과정과 상세 대응은 작업 디렉토리의 5개 대장에 보존한다. 허용되지 않은 미해결 누락·의미 변경·형식 실패·실행 참조 단절은 발견 사항 수정 범위에서 0으로 정리하였다. 이는 법률 원문 재검증, 현행법 승인, 실제 LLM 실행 또는 변호사 제출 전 검토 완료를 뜻하지 않는다.\n\n승계·표시한 미결: STOP-C05 변경 허용의 명문, STOP-C07 하급심 대상적격 일반화, STOP-C08 제3자 소송담당 및 LC-01~05의 이자 시점·복합 문형·책임 주체 적용 문제. SRC-P17 후속 재판, P18 일부 파기, 구법·당시 이율·원문 확인 범위 제한을 유지한다. 해결되지 않은 법률 쟁점을 검증 완료로 승격하지 않았다.\n\n작업 대장 위치: `tmp/규칙문서재작성_제권판결에대한불복의소_20260911_batch5f/`. 입력 해시와 사건 신원은 위 제작 이력의 스냅샷과 동일하며, URL 직접 접근은 수행하지 않았다.\n'''
|
|
old='종합 검증은 완결 초안을 대상으로 1회 수행한 뒤 발견 사항만 수정한다. 이 초안 단계에서는 검증 미완료이며 최종 기록은 검증 후 갱신한다. 기술적 구조·의미 보존 대조와 외부 법률 원문 재검증·실제 LLM 실행·변호사 제출 승인을 구별한다.'
|
|
text=text.replace(old,summary)
|
|
# Detailed ledgers. Preserve original unit text with full context line, modifiers, transformations and final exact anchor.
|
|
sourcecheck={x['line']:x for x in review['source_checks']}
|
|
ledger=['# 원문 보존 대장','원문 v2만 법률 내용 원천. 원문 단위별 내용과 실제 사용 위치를 대조하였으며 자동 문구 동일성만으로 법률 의미 보존을 판정하지 않았다.','| 단위 ID | 원문 경로·행·ID | 원문 핵심 내용 및 한정어 | 종류 | 원래 연결 | 변환 방식 | beta 정확 위치 | 의미 대조 결과 |','|---|---|---|---|---|---|---|---|']
|
|
for u in units:
|
|
i=u['line'];refs=', '.join(re.findall(r'(?:RULE|Q|LEAF|FORM|CHECK|STOP-[HCR]|SRC-[LPD])-\d+',ls[i-1]));res=sourcecheck.get(i,{}).get('assessment','제목·빈 행·열표제·구분선의 기능을 새 절·표에 대응. 독립 법률 내용 없음.')
|
|
ledger.append('| '+u['id']+' | '+esc(str(pathlib.Path(C['source']).relative_to(pathlib.Path(identity['inputs']['registry']['path']).parent)))+' L'+str(i)+' | '+esc(u['text'])+' | '+u['kind']+' | '+refs+' | '+('조건별 실행 전환·이력 보존' if i in {h[0] for h in history}|{a[0] for a in amend} else '위치 이동·필드 분리')+' | '+u['destination']+' | '+res+' 개선 F01~08 중 해당 범위 반영 확인. |')
|
|
(W/'원문보존대장.md').write_text('\n'.join(ledger)+'\n')
|
|
fledger=['# 형식 요구사항 대장','| 요구사항 ID | XPath·속성·내용 | 적용 여부와 이유 | beta 정확 위치 | 검사 방법 | 결과 |','|---|---|---|---|---|---|']
|
|
for r in req:
|
|
xp=r['xpath'];match=re.search(r'/section\[(\d+)\]',xp);ap=re.search(r'/appendix\[(\d+)\]',xp)
|
|
dest=('§'+str(int(match[1])-1)) if match else ('부록 '+('A' if ap[1]=='1' else 'B')) if ap else 'H1 및 §0~7·부록 A/B'
|
|
method='실제 표제·필드·순서·제한과 내용 대조'
|
|
if '/form_block' in xp:dest='§5 FORM-01~11의 아홉 필드';method='각 문형의 순수 주문·변수·선택·조립·금지·근거·재검토 대조'
|
|
if '/metadata' in xp:dest='§0 메타데이터 네 필드';method='F01 표제·필드 제한 수정 확인'
|
|
if '/url_access' in xp:dest='부록 A 사용·접근 제한';method='직접·우회 접근 금지 및 제공 자료 재개 문장 확인'
|
|
fledger.append('| '+r['id']+' | '+esc(xp+' '+r['text'])+' | 적용. 형식 구조 및 사건 내용 처리법 | '+dest+' | '+method+' | 충족; F01~08 해당 수정 반영 |')
|
|
(W/'형식요구사항대장.md').write_text('\n'.join(fledger)+'\n')
|
|
refs={}
|
|
for i,l in enumerate(ls,1):
|
|
for ref in re.findall(r'(?<![A-Z])(?:RULE-\d+|Q-\d+|LEAF-\d+|FORM-\d+|CHECK-\d+|STOP-[HCR]\d+|SRC-[LPD]\d+|T[1-7])',l):refs.setdefault(ref,[]).append(i)
|
|
refledger=['# 참조 대응표','| 원문 참조 | 새 위치·ID | 대응 방식 | 사용 지점 |','|---|---|---|---|']
|
|
for ref,ns in sorted(refs.items()):
|
|
defs=[i for i in ns if re.match(r'(?:- |\| |### )'+re.escape(ref)+r'(?:\s|\|)',ls[i-1])];di=defs[0] if defs else next((i for i in ns if str(i) in positions),ns[0]);dest=positions.get(str(di),section_for_line(di))
|
|
refledger.append('| '+ref+' | '+dest+'; ID 유지 | '+('정의·조건별 상태 분리' if ref.startswith('STOP') else '정의 또는 원문 유일 문맥에 대응')+' | 원문 L'+','.join(map(str,ns))+' → 각 대응 anchor |')
|
|
vars={}
|
|
for i,l in enumerate(ls,1):
|
|
for v in re.findall(r'\[[^\]\n]+\]',l):vars.setdefault(v,[]).append(i)
|
|
for v,ns in sorted(vars.items()):refledger.append('| '+esc(v)+' | '+', '.join(positions.get(str(i),section_for_line(i)) for i in sorted(set(ns)))+' | 치환 변수명 보존 | §1·§3·§5 각 문형의 의미·주문 대응 |')
|
|
(W/'참조대응표.md').write_text('\n'.join(refledger)+'\n')
|
|
cl=['# 충돌·변경 대장','| 원문 위치·내용 | 분류 | 처리 근거 | 보존 내용 | 새 실행 | 이력 위치 | 잔여 미결 |','|---|---|---|---|---|---|---|']
|
|
for i,old,why,new in history:cl.append('| L'+str(i)+' '+esc(old)+' | 형식·실행 | output_format 상태·불명 분리 | 법적 전제·예외·자료·재개 | '+esc(new)+' | 부록 B 제작 이력 | 원문 법률 미확인은 유지 |')
|
|
for f in review['findings']:cl.append('| '+f['location']+' | '+f['id']+' 종합검증 개선 | '+f['finding']+' | 해당 범위 원문 조건 유지 | 수정 반영 | 부록 B 1회 검증 개선 | 수정 범위 확인 완료 |')
|
|
for lc in review['unresolved_legal']:cl.append('| '+lc+' | 실질 적용 충돌·미확정 | 양쪽 원문 명제 보존 | 본문 적용 미확정 목록 | 해당 항만 재검토·보완 | §7·부록 B | 미결 유지, 법률 교정 안 함 |')
|
|
(W/'충돌변경대장.md').write_text('\n'.join(cl)+'\n')
|
|
sc=['# 시나리오 검토표','정적 원문·재작성 대응 검토이며 실제 LLM 실행 또는 조합 전수 시뮬레이션이 아니다.','| ID | 조건 조합 | 원문 선택·문구·조건 | 새 선택·문구·조건·상태 | 차이 | 허용 형식 전환 여부 | 결과 |','|---|---|---|---|---|---|---|']
|
|
for q in review['scenarios']:sc.append('| '+q['id']+' | '+esc(q['condition'])+' | '+esc(q['source'])+' | '+esc(q['beta'])+' | '+q['difference']+' | 상태·범위·미결 보존에 한정 | 1회 검토, 해당 개선 반영 확인 |')
|
|
(W/'시나리오검토표.md').write_text('\n'.join(sc)+'\n')
|
|
# Save and fixed-scope integrity checks only.
|
|
for n,snap in identity['inputs'].items():assert hashlib.sha256(pathlib.Path(snap['path']).read_bytes()).hexdigest()==snap['sha256']
|
|
candidate=W/'final_candidate.md';candidate.write_text(text);p=pathlib.Path(C['output']);status='재작성·형식검증 완료'
|
|
if p.exists() and p.read_bytes()!=candidate.read_bytes():status='기존 파일 덮어쓰기 대기';final=candidate
|
|
else:
|
|
p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(candidate.read_bytes());final=p
|
|
saved=final.read_text();assert saved==text;assert saved.startswith('# '+C['name']+' — 청구취지 작성 규칙');assert len(re.findall(r'^## ',saved,re.M))==10
|
|
anchors=set(re.findall(r'id="([^"]+)"',saved));links=set(re.findall(r'\]\(#([^\)]+)\)',saved));assert links<=anchors,links-anchors
|
|
for n in range(1,12):
|
|
a=saved.index('### FORM-'+f'{n:02}');b=saved.find('\n### FORM-',a+1);b=saved.index('\n## 6.',a) if b<0 else b;block=saved[a:b]
|
|
for field in ['선택 기준','작성 전에 연결할 정보','법적 전제','미확인 처리','주문 문장','조립','사용 금지 조건','근거','검토']:assert '**'+field+'**' in block,(n,field)
|
|
completion={'case':C['name'],'key':'제권판결에대한불복의소','source':C['source'],'output':str(final),'requested_output':C['output'],'status':status,'sha256':hashlib.sha256(final.read_bytes()).hexdigest(),'bytes':final.stat().st_size,'lines':len(saved.splitlines()),'source_units':len(units),'semantic_units':len(meaningful),'format_units':len(units)-len(meaningful),'format_requirements':len(req),'scenarios':len(review['scenarios']),'improvements':len(review['findings']),'comprehensive_reviews':1,'review_evidence':str(W/'comprehensive_review.json'),'workdir':str(W),'unresolved_legal':review['unresolved_legal'],'external_url_access':False,'external_legal_verification':False,'actual_llm_execution':False,'input_hashes_unchanged':True,'scoped_fix_checks':'F01~08 및 저장·참조·9필드 확인. 종합 재검증 반복 없음.'}
|
|
(W/'completion.json').write_text(json.dumps(completion,ensure_ascii=False,indent=2));print(json.dumps(completion,ensure_ascii=False,indent=2))
|