feat(stage2): S2_20 v.2 YAMLs (G1, G2 draft/verify, G3 CU repair) and legal reference PDFs #4

Merged
jhogyu merged 2 commits from stage2/s2-20-index-coverage-build into main 2026-10-28 12:26:54 +00:00
428 changed files with 226285 additions and 428 deletions
@@ -0,0 +1,966 @@
# 2026-10-28 신규(v.2 G1): 작업구조도설계_S2_20_v.2.md의 6개 묶음 중 G1 준비(T0 prepare)를 구현한다.
# 옛 S2_20(Stage_2_S2_20.yml, Default_Agent/Stage_2_Clean 자산·weaviate)은 Stage_2_S2_20_outdated_kept.yml로 보존했고 이 파일과 무관하다.
# 범위: task는 T0 하나다. task_procedure는 G1 → G2(T2a draft_lead_* → T3a verify_lead_{same_ordinal} → T1 load_rest →
# T2b draft_rest_* → T3b verify_rest_{same_ordinal})까지 적고 OUT으로 닫는다. G2 task를 넣기 전에는 이 파일만으로 돌리지 않는다.
# G3를 붙일 때 OUT 자리에 T4p load_repair_cu(wait: all verify_lead_*, all verify_rest_*, load_rest)를 둔다.
# 원칙: 단순 해법 우선. 코드는 결정적 결속·상태·크기만 정하고, 법리 판단(경로 확정·요건 배정·문안)은 G2 LLM이 블록 2 원문을 읽고 한다.
#
# 입력(모두 raw 바이트 sha로 결속하고 s2_20/snapshot/에 복사한다; I5·I6 원본 폴더와 I7 전체는 읽지 않는다)
# I3 S2_10 7.3.3: filter/filter_status.json(FILTER_COMPLETE 계열만) → claim_identity_review.json(artifacts sha) →
# claims_index.json(bound sha) → claims/RC-NN.json(index sha); s2_10_status.json(bound sha) → work/plan.json(본문 정규 JSON sha =
# plan_sha256 = s2_10_status.plan_sha256, S2_10과 같은 계산)
# → plan의 source·artifacts sha와 registry_sha256·mapping_sha256. 각 파일은 한 번만 읽고 검사한 바이트를 그대로 쓰고 복사한다
# I2 S2_00 v7_7 handoff: S2_10 plan이 sha로 결속한 사본 work/source/RC-NN.json(분할 RC 병합본)·work/llm_input/common.json으로 읽는다
# I1 Stage 1 원본: s2_00/v7_7/ingress/stage1_input_manifest.json의 path·raw_sha256(쓰는 파일만 읽음, sha 불일치 = run BLOCKED).
# manifest 자체는 S2_10 결속 사슬 밖이다(plan ingress_status_sha256 경유 결속은 백엔드 파일 확인 뒤 추가); sha는 snapshot에 남긴다
# I4 등록부: S2_10 plan registry_sha256(S2_10 설정에 내장된 등록부의 sha)을 색인 manifest registry_sha256과 대조
# I7 사전 색인 Default_Agent/Stage_2/rulebook_build/: rulebook_index/{manifest.json, NNN.json}, rulebooks/{claim,elements}/NNN.md
# I8 세 표: Default_Agent/Stage_2/rulebook_build/tables/{relief_invariants, object_class_spans, module_registry}.json
# (빌드 산출물에 없으므로 indexing_scratchpad/의 세 파일을 업로드할 때 함께 올린다, v.2 §11-8)
# I9 stage2_control/s2_20_values.json(선택): {"objects": {"OBJ-…": 가액 자료}}. 없으면 NEEDS_INPUT
# I10 stage2_control/s2_20_request.json(선택): {"prefer": "cost|speed", "hold_mode": "questions|draft",
# "answers": {"CU-NNN": "HOLD 질문에 대한 답(HOLD → 전송)"}, "path_hint": {"CU-NNN": "P2"}, "cp_split": [["CU-…", …], …]}
# 출력(root stage2_runs/from-stage1/s2_20, 실행마다 delete_folder로 비우고 다시 쓴다; S2_10 root 밖)
# snapshot/{입력 경로 사본, index/{manifest.json, NNN.json}, snapshot_manifest.json}
# bundle/{case_bundle.json, complaints/CP-NN.json, claims/CU-NNN.json} (CU 묶음: S2_10 청구문·issues·relief_method_order·
# legality flags·holds·relations·relief 행·객체 행·요건 행 목록·STOP 목록·thread 범위·ref 원본 본문(facts)·evidence_refs·allowed_refs)
# packet/{1_common.md(블록 1), 2_kind/NNN.md(블록 2 = 두 정리본 파일 전체), 2_kind/none.md(종 null), 2_kind/NNN-CU-NNN.md(경로 절 제외본),
# 3_cu/CU-NNN.json(블록 3 = bundle/claims/CU-NNN.json과 같은 바이트)}. 이름순이 블록 순서와 같다(동적 preflight 정렬 방식과 무관하게)
# items/{lead.json, rest.json} review/holds.json prepare.json(마지막에 쓴다)
# 항목: {run_id, cu_id, cp_id, case_kind_index, status, block2_path, block3_path, cache_key "s2_20:draft:NNN", cache_shared, packet_chars}
# stdout: {"status": "PREPARED", …, "dynamic_fanout": lead 항목}. 실패하면 {"status": "BLOCKED", "error", "dynamic_fanout": []}과
# 빈 items/lead.json·rest.json을 써서 G2 로더가 빈 fan-out으로 지나가게 한다.
#
# 상태(v.2 §8.7 → 설계 §4 T0 0.5): 우선순위 BLOCKED > EXCLUDE_RECOMMENDED > HOLD > DRAFT_WITH_LAWYER_NOTE > DRAFT_WITH_PLACEHOLDERS > READY
# BLOCKED: CU ref가 Stage 1 원본에서 풀리지 않음. EXCLUDE: 무조건(conditional false) 제외 권고.
# HOLD: CU 결정 HOLD, S2_10 holds 대상, 청구 standing DOUBTFUL, 상속 단위 provisional, 색인 STALE, 패킷 한도 초과.
# LAWYER_NOTE: 조건부 제외 권고, CONFIRMATION_EXCEPTION, 종 null, BRANCH 구성원(방법 분기), 주위적 CU가 HOLD인 예비적 CU, I10 답변 반영.
# PLACEHOLDERS: relief_detail 빈 값, RELIEF_DETAIL_MISSING·RELIEF_KIND_UNRESOLVED, 부대청구 이율·기산일 미정.
# review(전송하되 변호사 검토): 정리 기록 REC_CROSS_KIND·REC_RESTORE_BLOCKED, 구성원 종 불일치, 상류 문면의 가나 문자(NON_KOREAN_TEXT,
# 7.3.3 미해결 혼입; T2가 옮겨 쓰지 않게 알린다), object_class 미정(OBJECT_CLASS_FOLLOWS_RELIEF·OBJECT_CLASS_UNRESOLVED).
# HOLD·EXCLUDE·BLOCKED는 항목을 만들지 않고 review/holds.json에 사유·질문만 낸다(hold_mode=draft면 색인 STALE 외의 HOLD도 전송).
# 로컬 하네스(S2_10 7.3.3 실출력 + handoff 본문으로 만든 합성 Stage 1) 결과: N=15, L=9, HOLD 6(CU-010·015·016·017·018·020),
# LAWYER_NOTE 5(CU-002·004·005·019·021), wave 단일 2 = 두 stage 2 → prefer=cost. 최대 패킷 79(CU-007) 229,654자, 135(CU-005)
# 204,405자(블록 1을 예산 20,000자로 계산, 합성 본문 기준). 실제 Stage 1 본문은 더 클 수 있어 CU-007이 넘칠 위험이 있다(추정):
# 그때는 아래 한도 처리 ①로 맥락 thread 본문을 빼고(하네스 222,203자), 그래도 넘으면 HOLD다. 실제 크기는 온라인 G1 실행으로 확인한다.
#
# 설계서와 다르게 단순화한 곳(이유)
# 1. 상속 S1~S7 판정을 코드로 하지 않는다. 관계(배우자·자녀)와 포기 수리가 원본에 문장으로만 있어 결정적으로 읽을 수 없다.
# provisional 상속 단위의 CU는 HOLD로 두고 등록부 heirs·renounced로 만든 질문을 낸다. 답은 I10 answers로 받는다.
# 2. 경로 힌트는 후보 경로 전부 + relief_kind만 준다(경로 확정은 T2). 한도 처리 순서: ① 맥락 thread 사실(own=false)의 본문을 빼고
# ref·evidence_index만 남긴다(CU 자신의 ref 본문은 그대로) ② I10 path_hint로 경로가 지정된 CU만 restrict_paths ③ 그래도 넘으면
# CU를 급부 성분 단위로 나누는 대신 HOLD(PACKET_OVERFLOW) 질문을 낸다(T5 재결합 계약을 만들지 않는다).
# 3. 모듈은 발동 목록(REMEDY/{index}, STANDING/SUCCESSION, JOINDER)만 적는다. 규칙 본문은 블록 2 원문에 있다.
# 코드 값은 135 가액배상의 checks(가집행·특례이율 배제) 하나다.
# 4. 블록 1은 세 표 데이터와 "Lnnnn 주석 무시" 안내만 둔다. 과업 규칙·출력 스키마·실무제요 발췌는 G2 T2 프롬프트에 둔다.
# 5. object_class는 CU 종의 구간표 후보로만 정한다(객체별 교집합 생략). 후보 하나면 그 값, EACH_OF면 후보 목록,
# FOLLOWS(급부 대상 클래스를 따름)면 null + OBJECT_CLASS_FOLLOWS_RELIEF, ONE_OF 후보 둘 이상이면 null + OBJECT_CLASS_UNRESOLVED.
# 6. 증거 폐포는 ref 본문의 E-NNN과 포인터가 속한 증거 항목의 evidence_index다.
# 7. 패킷 한도는 설계 §5.2대로 블록 1(예산 20,000자로 계산; 나머지는 T2 정적 프롬프트 몫)+2+3 합계 240,000자로 잰다. 백엔드 한도(agent.py:34 파일당 240,000자, 38행 합계 500,000자)보다
# 보수적이라 두 한도를 모두 지키고, 넘는 경우 HOLD가 더 일찍 생길 뿐이다.
# 8. 묶음 설계(최적정보묶음 v.2)에서 이번에 만들지 않은 칸: 기간(제척기간) 위험의 LAWYER_NOTE 발동, registrations[]·목적물 표시 행,
# 이름 규칙(§10-7), requested_scope_check(§7, 대신 CP에 primary_goal·constraints), coverage{refs_resolved}, handoff 본문과 원본 대조(§10-4).
# 급부 성분의 obligor·recipient·counter_performance와 금액·이율 출처 규칙(§8.3 R1~R5, §8.4), non_parties·원고 자격 상태,
# LES source_bo_ids 풀이(§10-4)도 만들지 않는다. 이번 사건 상태 배정은 이것 없이 설계값과 같다. 해당 판단은 T2가 원문·ref 본문으로 하고
# T3·T7이 검사한다. CU 단위 BLOCKED가 있어도 run은 PREPARED이고 prepare.json counts.BLOCKED와 holds.json에 나온다.
# 10. 패킷 한도 초과로 HOLD가 된 주위적 CU에는 "예비적 CU에 변호사 판단 사항" 규칙이 다시 적용되지 않는다(예비적 판정이 패킷 측정보다 앞선다).
# 9. 같은 급부 성분을 공유하는 PRIMARY·BRANCH 구성원은 relief 행 하나로 합친다(member에 둘 다 적음).
#
# G2 작성 시 지킬 것: T2a·T2b는 같은 명시 llm_prompt_cache_key 하나를 쓴다(자동 키는 task 이름별이라 둘이 갈린다; 항목별 키는 P6 뒤).
# T2 프롬프트 어디에도 {{item.*}}를 넣지 않는다(첫 user 메시지가 접두어 경계다). CU별 값은 전부 블록 3에 있다. T1은 {{prev.Task_S2_20_prepare.status}}가 PREPARED가 아니거나 항목 run_id가 prepare.json run_id와 다르면 빈 목록을 낸다
# (Localdocs 초기화 실패 시 옛 items가 남을 수 있다). T3는 rbidx/2.1.0의 valid_ids·required_rids·stop_ids를 그대로 옮기고
# s2_20/snapshot/index/NNN.json을 읽는다(write_binary_file 사본이라 raw sha가 같다).
# 온라인 probe만 먼저 돌릴 때는 task_procedure를 IN → Task_S2_20_prepare → OUT으로 바꾼 사본을 쓴다.
# 미확인(실행 전 probe): P7 code task가 Default_Agent/Stage_2/rulebook_build/를 read_binary_doc로 읽는가;
# P8 stage1_input_manifest의 path가 stage1_run_root_ref 기준이고 signal ref 접두사가 "signal:<경로>" 행과 맞는가;
# P9 delete_folder가 s2_20 root를 지우는가(S2_10 reset과 같은 호출).
Agent:
name: Stage_2_S2_20_v2
description: "S2_20 v.2(사전 색인 rbidx/2.1.0) — G1 준비(T0 prepare): 스냅샷·색인 적재·coverage 확인·세 층 묶음·상태 판정·항목과 패킷 조립, 종별 선두 CU fan-out을 연다. task_procedure는 G1 → G2(T2a·T3a·T1·T2b·T3b) 연결까지 적는다."
version: 2.0.0-g1
Stages:
- name: S2_20_draft_pleadings
description: S2_10 7.3.3 CU별 청구취지·청구원인 초안과 소장 묶음(CP) 병합. 이 파일은 G1(T0)만 구현한다.
skip_confirm: true
tools:
mcpServers:
localdocs:
type: streamable-http
url: http://mcp-localdocs:8012/mcp
description: workspace-bound documents
code-executor:
type: streamable-http
url: https://code-executor.mcp.eroomai.com/mcp
description: inline Python execution
tasks:
- task_name: Task_S2_20_prepare
description: T0 prepare — 0.1 입력 결속·스냅샷, 0.2″ 색인 적재(sha 대조), 0.3 coverage 확인, 0.4 묶음 3층, 0.5 상태 판정, 0.6 항목·패킷. dynamic_fanout = 종별 선두 CU 항목(items/lead.json).
mcp: code-executor
tool_name: run_code
parameters:
language: python
requirements: httpx
network: agent-network
timeout: 300
code: |
import base64, datetime, hashlib, itertools, json, math, re, unicodedata
import httpx
CFG = {
"output_root": "stage2_runs/from-stage1/s2_20",
"s2_10_root": "stage2_runs/from-stage1/s2_10",
"s2_00_root": "stage2_runs/from-stage1/s2_00/v7_7",
"build_root": "Default_Agent/Stage_2/rulebook_build",
"request_path": "stage2_control/s2_20_request.json",
"values_path": "stage2_control/s2_20_values.json",
"packet_limit": 240000,
"common_budget": 20000,
"concurrency": 14,
"kind_checks": {
"135": {"금전지급": {"가집행": "붙이지 않는다", "특례이율": "적용하지 않는다",
"근거": "요건사실론 사해행위취소 §4.4(판례 2000다3583 UNVERIFIED)"}},
},
}
PARSER_VERSION = "rbidx/2.1.0"
SENDABLE = ("READY", "DRAFT_WITH_PLACEHOLDERS", "DRAFT_WITH_LAWYER_NOTE")
DIRECTIVES = {
"READY": "필요한 값이 갖추어져 있다. 그대로 작성한다.",
"DRAFT_WITH_PLACEHOLDERS": "비는 값은 [NEEDS_INPUT: 항목] 자리표시자로 두고 questions에 올린다. 감정이 필요한 금액은 일부청구로 쓰고 '감정 후 확장'을 적는다.",
"DRAFT_WITH_LAWYER_NOTE": "lawyer_notes의 각 항목을 questions에 '변호사 판단 사항'으로 올린다. 조건부 제외 권고가 있으면 흡수 문안과 독립 유지 문안을 둘 다 쓴다.",
"HOLD": "hold_mode=draft 잠정 초안이다. questions를 앞에 두고 금액·지분은 비워 둔다.",
}
class Localdocs:
def __init__(self):
self.client = httpx.Client(timeout=60)
self.headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
self.ids = itertools.count(10)
self.url = "http://mcp-localdocs:8012/mcp"
self.rpc("initialize", {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {
"name": "s2-20-prepare", "version": "1.0", "user_id": "{{__user_hash__}}", "workspace_id": "{{__workspace_hash__}}"}})
self.rpc("notifications/initialized", {}, notification=True)
def rpc(self, method, params, notification=False):
body = {"jsonrpc": "2.0", "method": method, "params": params}
if not notification:
body["id"] = next(self.ids)
r = self.client.post(self.url, json=body, headers=self.headers)
r.raise_for_status()
if r.headers.get("mcp-session-id"):
self.headers["mcp-session-id"] = r.headers["mcp-session-id"]
if notification:
return {}
text = r.text.strip()
if r.headers.get("content-type", "").startswith("text/event-stream"):
rows = [json.loads(x[6:]) for x in text.splitlines() if x.startswith("data: ")]
rows = [x for x in rows if x.get("id") == body["id"]]
if not rows:
raise RuntimeError("MCP response missing")
data = rows[-1]
else:
data = json.loads(text)
if "error" in data or "result" not in data:
raise RuntimeError("MCP RPC error: " + str(data.get("error", "missing result")))
return data["result"]
def call(self, name, args):
result = self.rpc("tools/call", {"name": name, "arguments": args})
texts = [x["text"] for x in result.get("content", []) if x.get("type") == "text"]
structured = result.get("structuredContent", {})
if not texts and isinstance(structured, dict) and "result" in structured:
value = structured["result"]
texts = [value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)]
message = "\n".join(texts).strip()
if re.match(r"^(?:Error:\s*)?(?:Document|File|Folder) not found:", message, re.I):
raise FileNotFoundError(message)
if result.get("isError") or re.match(r"^Error(?::|\s)", message):
raise RuntimeError("MCP tool error: " + message)
if not texts:
raise RuntimeError("Empty response for " + name)
return message
def binary(self, path):
raw = self.call("read_binary_doc", {"doc_name": unicodedata.normalize("NFC", path)})
try:
data = json.loads(raw)
except json.JSONDecodeError:
data = json.JSONDecoder().raw_decode(raw.strip())[0]
if not isinstance(data, dict) or "content_base64" not in data:
if re.search(r"not found|does not exist|파일.*없", str(data), re.I):
raise FileNotFoundError(path)
raise RuntimeError("Binary envelope invalid: " + path)
return base64.b64decode(data["content_base64"], validate=True)
def binary_optional(self, path):
try:
return self.binary(path)
except FileNotFoundError:
return None
def write(self, path, text):
self.call("write_file", {"path": unicodedata.normalize("NFC", path), "content": text, "overwrite": True})
def write_binary(self, path, raw):
self.call("write_binary_file", {"path": unicodedata.normalize("NFC", path),
"content_base64": base64.b64encode(raw).decode("ascii"), "overwrite": True})
def reset(self, root):
if root != CFG["output_root"]:
raise RuntimeError("OUTPUT_RESET_PATH_INVALID")
try:
message = self.call("delete_folder", {"path": root, "force": True})
if message != "Successfully deleted folder: " + root:
raise RuntimeError("OUTPUT_RESET_UNCONFIRMED: " + message)
except FileNotFoundError:
pass
def close(self):
self.client.close()
class Blocked(Exception):
def __init__(self, code, detail=""):
super().__init__(code + ": " + str(detail))
self.code, self.detail = code, str(detail)
def require(ok, code, detail=""):
if not ok:
raise Blocked(code, detail)
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def pack(x):
return json.dumps(x, ensure_ascii=False, separators=(",", ":"))
def loads(raw):
"""SKILL §12.3: tolerate trailing garbage after the first JSON value"""
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
try:
return json.loads(text)
except json.JSONDecodeError:
return json.JSONDecoder().raw_decode(text.strip())[0]
def split_target(t):
return [x.strip() for x in str(t).split("|") if x.strip()]
# ---------------- rulebook_index.py rbidx/2.1.0 runtime functions used by T0 (copied; only sha256() is named sha() here) ----------------
def verify(entry, claim_raw, elem_raw):
if entry["parser_version"] != PARSER_VERSION: return "PARSER_VERSION"
if entry["claim"]["sha256"] != sha(claim_raw): return "SHA_CLAIM"
if entry["elements"]["sha256"] != sha(elem_raw): return "SHA_ELEMENTS"
return None
def block2(claim_raw, elem_raw):
"""whole files, verbatim"""
return claim_raw.decode("utf-8"), elem_raw.decode("utf-8")
def restrict_paths(entry, elem_text, keep):
"""packet-overflow rule: drop the per-path sections of the other paths (keep = path id).
An unknown path id changes nothing (the caller then falls back to splitting the CU)."""
sections = entry["elements"]["path_sections"]
if keep not in sections:
return elem_text
spans = sorted(v for k, v in sections.items() if k != keep)
out, cur = [], 0
for s, e in spans:
out.append(elem_text[cur:s]); cur = max(cur, e)
out.append(elem_text[cur:])
return "".join(out)
# ---------------- 0.1 inputs, binding and snapshot ----------------
class Inputs:
"""every byte read is kept for the snapshot (raw sha, never re-serialized)"""
def __init__(self, io):
self.io, self.raw = io, {}
def get(self, path, optional=False):
if path in self.raw:
return self.raw[path]
raw = self.io.binary_optional(path) if optional else self.io.binary(path)
if raw is not None:
self.raw[path] = raw
return raw
def json(self, path, optional=False):
raw = self.get(path, optional)
return None if raw is None else loads(raw)
def load_s2_10(inp, cfg):
root = cfg["s2_10_root"]
status = inp.json(root + "/filter/filter_status.json")
require(str(status.get("status", "")).startswith("FILTER_COMPLETE"), "S2_10_NOT_COMPLETE", status.get("status"))
bound = {a["path"]: a["raw_sha256"] for a in status["artifacts"]}
cir_path = root + "/filter/claim_identity_review.json"
require(sha(inp.get(cir_path)) == bound.get(cir_path), "BIND_MISMATCH", cir_path)
index_path = root + "/claims_index.json"
require(sha(inp.get(index_path)) == status["bound"]["claims_index_sha256"], "BIND_MISMATCH", index_path)
claims = {}
for row in inp.json(index_path)["clusters"]:
require(sha(inp.get(row["path"])) == row["sha256"], "BIND_MISMATCH", row["path"])
claims[row["cluster_id"]] = inp.json(row["path"])
s2_status_path = root + "/s2_10_status.json"
require(sha(inp.get(s2_status_path)) == status["bound"]["s2_10_status_sha256"], "BIND_MISMATCH", s2_status_path)
plan = inp.json(root + "/work/plan.json")
body = json.dumps({k: v for k, v in plan.items() if k != "plan_sha256"}, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
require(sha(body.encode("utf-8")) == plan.get("plan_sha256") == inp.json(s2_status_path).get("plan_sha256"),
"BIND_MISMATCH", root + "/work/plan.json")
sources = {}
for row in plan["clusters"]:
require(sha(inp.get(row["source_path"])) == row["source_sha256"], "BIND_MISMATCH", row["source_path"])
sources[row["cluster_id"]] = inp.json(row["source_path"])["rc"]
for a in plan["artifacts"]:
require(sha(inp.get(a["path"])) == a["raw_sha256"], "BIND_MISMATCH", a["path"])
common = inp.json(plan["common_path"])
return inp.json(cir_path), claims, plan, sources, common
class Stage1:
"""ref = '<logical id or signal path>#<json pointer>' resolved in the Stage 1 original (manifest path + raw sha)"""
def __init__(self, inp, cfg):
self.inp = inp
man = inp.json(cfg["s2_00_root"] + "/ingress/stage1_input_manifest.json")
self.root = man.get("stage1_run_root_ref") or "."
self.rows = [r for r in man["sources"] if r.get("path") and r.get("raw_sha256")]
self.docs = {}
def row(self, prefix):
for r in self.rows:
lid = r["logical_input_id"]
if lid in (prefix, "signal:" + prefix, "signal:" + prefix.split("signals/", 1)[-1]) or r["path"] == prefix:
return r
raise KeyError(prefix)
def doc(self, prefix):
if prefix not in self.docs:
r = self.row(prefix)
path = r["path"] if self.root in (".", "") else self.root.rstrip("/") + "/" + r["path"]
raw = self.inp.get(path)
require(sha(raw) == r["raw_sha256"], "STAGE1_SHA_MISMATCH", path)
self.docs[prefix] = loads(raw)
return self.docs[prefix]
def resolve(self, ref):
prefix, _, pointer = ref.partition("#")
node = self.doc(prefix)
for tok in pointer.split("/")[1:]:
tok = tok.replace("~1", "/").replace("~0", "~")
node = node[int(tok)] if isinstance(node, list) else node[tok]
return node
def evidence_ids(self, ref, body):
"""1-hop closure: E-NNN named in the body, plus the evidence item a pointer sits in"""
ids = set(re.findall(r"\bE-\d{3}\b", pack(body)))
prefix, _, pointer = ref.partition("#")
m = re.match(r"^/items/(\d+)", pointer)
if m and prefix in ("evidence_indexed", "evidence_event_candidates"):
item = self.doc(prefix)["items"][int(m.group(1))]
if isinstance(item, dict) and item.get("evidence_index"):
ids.add(item["evidence_index"])
return sorted(ids)
def evidence_list(stage1):
"""case-level evidence list: short scalar fields of every evidence_indexed item"""
out = []
for i, item in enumerate(stage1.doc("evidence_indexed")["items"]):
row = {"ref": "evidence_indexed#/items/%d" % i}
row.update({k: v for k, v in item.items() if isinstance(v, (str, int, float)) and len(str(v)) <= 200})
out.append(row)
return out
# ---------------- 0.2″ index load, 0.3 coverage ----------------
def load_index(io, inp, cfg, plan, kind_set, review):
b = cfg["build_root"]
man_raw = io.binary(b + "/rulebook_index/manifest.json")
man = loads(man_raw)
require(man["registry_sha256"] == plan["registry_sha256"], "INDEX_REGISTRY_MISMATCH",
"%s vs S2_10 %s" % (man["registry_sha256"], plan["registry_sha256"]))
require(man["parser_version"] == PARSER_VERSION, "INDEX_FORMAT_MISMATCH", man["parser_version"])
tables = {}
for name, want in sorted(man["coverage"]["inputs"]["tables"].items()):
raw = inp.get(b + "/tables/" + name)
require(sha(raw) == want, "TABLES_MISMATCH", name)
tables[name] = loads(raw)
if plan.get("mapping_sha256") != man["coverage"]["inputs"]["mapping_sha256"]:
review.append({"code": "INDEX_COVERAGE_MAPPING_DIFFERS",
"note": "색인 coverage가 다른 S2_10 구제 후보표로 검사됨, 재빌드 권장"})
entries = {e["index"]: e for e in man["entries"]}
kinds, copies = {}, {"manifest.json": man_raw}
for k in sorted(kind_set):
n = "%03d" % k
if k not in entries:
kinds[k] = {"stale": "INDEX_ENTRY_MISSING"}
continue
idx_raw = io.binary_optional(b + "/rulebook_index/" + n + ".json")
claim_raw = io.binary_optional(b + "/rulebooks/claim/" + n + ".md")
elem_raw = io.binary_optional(b + "/rulebooks/elements/" + n + ".md")
if idx_raw is None or claim_raw is None or elem_raw is None:
kinds[k] = {"stale": "INDEX_FILE_MISSING"}
continue
entry = loads(idx_raw)
why = "INDEX_SHA" if sha(idx_raw) != entries[k]["index_sha256"] else verify(entry, claim_raw, elem_raw)
if why:
kinds[k] = {"stale": why}
continue
claim_text, elem_text = block2(claim_raw, elem_raw)
kinds[k] = {"entry": entry, "claim": claim_text, "elements": elem_text}
copies[n + ".json"] = idx_raw
return man, tables, kinds, copies
# ---------------- 0.4 bundles, 0.5 status ----------------
def member_claims(unit, claims):
out = []
for m in unit["members"]:
doc = claims.get(m["cluster_id"]) or {"claims": []}
c = next((c for c in doc["claims"] if c["seq"] == m["seq"]), None)
out.append((m, c))
return out
def relief_rows(cu_id, kind, mclaims, cfg):
rows, seen = [], {}
for m, c in mclaims:
if m["role"] == "ABSORBED":
continue
parts = c.get("relief_components") or [c]
for p in parts:
same = seen.get(pack([p.get("relief_kind"), p.get("relief_detail")]))
if same is not None: # PRIMARY/BRANCH members sharing one component (e.g. the same 취소 row)
same["member"] += ", %s/%s" % (m["cluster_id"], m["seq"])
continue
row = {"relief_row_id": "%s-R%d" % (cu_id, len(rows) + 1), "member": "%s/%s" % (m["cluster_id"], m["seq"]),
"relief_kind": p.get("relief_kind"), "relief_detail": p.get("relief_detail"),
"refs": p.get("key_facts_refs") or []}
checks = cfg["kind_checks"].get(str(kind), {}).get(row["relief_kind"])
if checks:
row["checks"] = checks
rows.append(row)
seen[pack([p.get("relief_kind"), p.get("relief_detail")])] = row
return rows
def object_rows(object_ids, kind, sources, rcs, tables, values):
spans = tables["object_class_spans.json"]["spans"]
span = next((s for s in spans if kind is not None and any(a <= kind <= b for a, b in s["ranges"])), None)
out = []
for oid in object_ids:
src = next((o for rc in rcs for o in sources[rc].get("objects", []) if o["object_id"] == oid), {})
row = {"object_id": oid, "label": src.get("label"), "control": src.get("control"),
"value": (values.get("objects") or {}).get(oid, "NEEDS_INPUT")}
row["object_class"] = None
if span is None or span["rule"] == "NOT_REQUIRED":
pass
elif "FOLLOWS" in span["candidates"]:
row["review"] = "OBJECT_CLASS_FOLLOWS_RELIEF" # the class follows the object of the relief row
elif span["rule"] == "ONE_OF" and len(span["candidates"]) == 1:
row["object_class"] = span["candidates"][0]
elif span["rule"] == "EACH_OF":
row["object_class_candidates"] = span["candidates"]
else:
row["object_class_candidates"], row["review"] = span["candidates"], "OBJECT_CLASS_UNRESOLVED"
out.append(row)
return out
def scoped_threads(rcs, sources, own_refs, object_ids):
"""§10 rule 5: threads sharing an object or a ref with the CU, plus the RC common thread T-00"""
out = []
for rc in rcs:
for t in sources[rc].get("threads", []):
refs = [m["ref"] for m in t.get("materials", [])]
if (t["thread_id"].endswith("/T-00") or t.get("object_id") in object_ids
or set(refs) & own_refs):
out.append({"thread_id": t["thread_id"], "label": t.get("label"), "object_id": t.get("object_id"),
"refs": refs})
return out
def succession_question(unit, registry):
p = next((r for r in registry if r["party_id"] == unit.get("succession_of")), {})
return ("상속 원고 단위 %s(%s)가 잠정(provisional)이다. 망 %s의 상속인 후보 %s, 상속포기 %s에 대해 "
"피상속인과의 관계(배우자·직계비속·직계존속)와 포기 심판 수리 여부를 확인해 상속인 범위와 상속분을 정하라"
"(민법 §1000·§1003·§1043, 2020그42)." % (unit.get("unit_id"), "·".join(unit.get("names", [])),
p.get("name", unit.get("succession_of")),
"·".join(p.get("heirs", [])) or "미상", "·".join(p.get("renounced", [])) or "없음"))
def build_cu(unit, ctx):
claims, sources, cir, stage1, kinds, tables, cfg = (ctx[k] for k in ("claims", "sources", "cir", "stage1", "kinds", "tables", "cfg"))
cu_id = unit["identity_id"]
mclaims = member_claims(unit, claims)
keys = ["%s/%s" % (m["cluster_id"], m["seq"]) for m, _ in mclaims]
hold, lawyer, placeholders, review, blocked = [], [], [], [], []
rcs = sorted({m["cluster_id"] for m, _ in mclaims})
primary = next((c for m, c in mclaims if m["role"] == "PRIMARY"), mclaims[0][1])
kind = primary["case_kind_index"]
if len({c["case_kind_index"] for _, c in mclaims}) > 1:
review.append({"code": "MEMBER_KIND_DIFFERS", "note": "구성원의 사건 종류가 다르다; PRIMARY의 종을 쓴다"})
flags = [f for f in cir["legality_flags"] if set(split_target(f["target"])) & set(keys)]
holds = [h for h in cir["holds"] if set(h["cand_refs"]) & set(keys)]
sg = [g for g in cir["satisfaction_groups"] if set(g["members"]) & set(keys)]
crg = [g for g in cir["cross_rc_groups"] if set(g["members"]) & set(keys)]
ancillary = [a for a in cir["ancillary_claims"] if a["attached_to"] in keys]
# status reasons (v.2 §8.7 as mapped in the S2_20 design §4 T0 0.5)
if unit["decision"] == "HOLD":
hold.append({"code": "CU_DECISION_HOLD", "detail": unit.get("reason")})
for h in holds:
hold.append({"code": "S2_10_HOLD", "detail": h["question"]})
for m, c in mclaims:
if c.get("standing") == "DOUBTFUL":
hold.append({"code": "STANDING_DOUBTFUL", "detail": "%s/%s 당사자 적격 DOUBTFUL: %s" % (m["cluster_id"], m["seq"], c.get("standing_note"))})
units = [sources[rc]["pair"].get("unit") or {} for rc in rcs]
for u in units:
if u.get("succession_of") and u.get("provisional"):
hold.append({"code": "SUCCESSION_UNRESOLVED", "detail": succession_question(u, ctx["common"]["party_registry"])})
if kind is not None and kinds[kind].get("stale"):
hold.append({"code": "INDEX_STALE", "detail": "규칙문서 색인이 정리본과 맞지 않음(%s), 재빌드 뒤 재실행" % kinds[kind]["stale"]})
unconditional = [f for f in flags if f["code"] == "EXCLUDE_RECOMMENDED" and f.get("conditional") is False]
for f in flags:
if f["code"] == "EXCLUDE_RECOMMENDED" and f.get("conditional") is not False:
lawyer.append("조건부 제외 권고(%s): %s" % (f.get("reason"), f.get("condition")))
if f["code"] == "CONFIRMATION_EXCEPTION":
lawyer.append("확인의 이익 예외 주장: %s" % f.get("condition"))
if kind is None:
lawyer.append("사건 종류 미정(REGISTRY_GAP): 규칙문서 없이 급부 클래스 불변식만 적용한다")
if any(m["role"] == "BRANCH" for m, _ in mclaims):
lawyer.append("구제 방법 분기: %s" % " / ".join(unit.get("relief_method_order") or
["%s/%s %s" % (m["cluster_id"], m["seq"], m["role"]) for m, _ in mclaims]))
rows = relief_rows(cu_id, kind, mclaims, cfg)
for r in rows:
d = r["relief_detail"]
if d and (d.get("act") is None or d.get("target") is None):
placeholders.append("%s relief_detail act·target 빈 값" % r["relief_row_id"])
for m, c in mclaims:
codes = [x for x in c.get("relief_review_codes") or [] if x in ("RELIEF_DETAIL_MISSING", "RELIEF_KIND_UNRESOLVED")]
if codes:
placeholders.append("%s/%s %s" % (m["cluster_id"], m["seq"], ",".join(codes)))
for a in ancillary:
if a.get("rate_basis") is None or a.get("from") is None:
placeholders.append("부대청구(%s) 이율·기산일 미정" % a["kind"])
answer = (ctx["request"].get("answers") or {}).get(cu_id)
if answer:
hold = [h for h in hold if h["code"] == "INDEX_STALE"]
lawyer.append("변호사 답변 반영: %s" % answer)
if kind is not None and not kinds[kind].get("stale"):
for flag in kinds[kind]["entry"]["elements"]["flags"]:
if flag in ("REC_CROSS_KIND", "REC_RESTORE_BLOCKED"):
review.append({"code": flag, "note": "요건사실론 정리 기록 플래그; 전송하되 변호사 검토"})
# facts: S2_10 refs of the CU + materials of the scoped threads, bodies from the Stage 1 originals
own = []
for r in rows:
own += r["refs"]
for _, c in mclaims:
own += c.get("key_facts_refs") or []
own = sorted(set(own))
object_ids = sorted({o for _, c in mclaims for o in c.get("object_ids") or []})
threads = scoped_threads(rcs, sources, set(own), set(object_ids))
facts, evidence_ids = [], set()
for ref in sorted(set(own) | {r for t in threads for r in t["refs"]}):
try:
body = stage1.resolve(ref)
except (KeyError, IndexError, ValueError, TypeError) as exc:
blocked.append({"code": "REF_UNRESOLVED", "detail": "%s (%s)" % (ref, type(exc).__name__)})
continue
ev = stage1.evidence_ids(ref, body)
evidence_ids.update(ev)
facts.append({"ref": ref, "own": ref in own, "evidence_index": ev, "body": body})
evidence_rows = [e for e in ctx["evidence"] if e.get("evidence_index") in evidence_ids]
if blocked:
status = "BLOCKED"
elif unconditional:
status = "EXCLUDE_RECOMMENDED"
elif hold:
status = "HOLD"
elif lawyer:
status = "DRAFT_WITH_LAWYER_NOTE"
elif placeholders:
status = "DRAFT_WITH_PLACEHOLDERS"
else:
status = "READY"
entry = kinds[kind]["entry"] if kind is not None and not kinds[kind].get("stale") else None
ics = {ic for rc in rcs for ic in sources[rc].get("declared_ics") or []}
bundle = {
"cu_id": cu_id, "decision": unit["decision"], "confidence": unit.get("confidence"),
"restructure_kind": unit.get("restructure_kind"), "relief_method_order": unit.get("relief_method_order"),
"open_flags": unit.get("open_flags") or [],
"members": [{"key": k, "role": m["role"], "sentence": c["sentence"], "join": c.get("join"), "alt_of": c.get("alt_of"),
"standing": c.get("standing"), "standing_note": c.get("standing_note")} for k, (m, c) in zip(keys, mclaims)],
"parties": {rc: {"plaintiffs": claims[rc]["pair"]["plaintiffs"], "defendant": claims[rc]["pair"]["defendant"],
"unit": sources[rc]["pair"].get("unit")} for rc in rcs},
"case_kind": {"index": kind, "name": primary.get("case_kind"),
"rulebooks": None if entry is None else {"claim": entry["claim"]["file"], "claim_sha256": entry["claim"]["sha256"],
"elements": entry["elements"]["file"], "elements_sha256": entry["elements"]["sha256"]}},
"modules": ([] if kind is None else ["REMEDY/%d" % kind])
+ (["STANDING/SUCCESSION"] if any(u.get("succession_of") for u in units) else [])
+ (["JOINDER"] if len(rows) > 1 or sg or crg or any(c.get("alt_of") for _, c in mclaims) else []),
"relief": rows,
"ancillary": ancillary,
"objects": object_rows(object_ids, kind, sources, rcs, tables, ctx["values"]),
"path_hint": {"relief_kinds": sorted({r["relief_kind"] for r in rows if r["relief_kind"]}),
"candidates": [] if entry is None else [p["id"] for p in entry["elements"]["paths"]],
"lawyer_path": (ctx["request"].get("path_hint") or {}).get(cu_id)},
"elements_rows": [] if entry is None else [{"r_id": r["id"], "class": r["class"], "paths": r["paths"],
"paths_qualified": r["paths_qualified"]} for r in entry["elements"]["r_rows"]],
"stop_ids": [] if entry is None else list(entry["claim"]["ids"]["STOP"]),
"relations": {"relation_labels": unit.get("relation_labels") or [], "satisfaction_groups": sg, "cross_rc_groups": crg},
"legality_flags": flags,
"s2_10_holds": holds,
"defense_hints": [h for rc in rcs for ic in sources[rc].get("issue_clusters", []) if ic.get("cluster_id") in ics
for h in (ic.get("defense_hints") or []) + (ic.get("legal_sustainability_watchpoints") or [])],
"issues": [dict(i, rc=rc) for rc in rcs for i in claims[rc].get("issues") or []],
"threads": threads,
"facts": facts,
"evidence_refs": evidence_rows,
"allowed_refs": sorted({f["ref"] for f in facts} | {e["ref"] for e in evidence_rows}),
"review": review,
}
kana = sorted(set(re.findall(r"[\u3040-\u30fa\u30fc-\u30ff]+", pack(bundle))))
if kana: # S2_10 7.3.3 known contamination; the draft must not copy it (T3 V7)
review.append({"code": "NON_KOREAN_TEXT", "note": "상류 문면에 가나 문자: " + ", ".join(kana[:10])})
reasons = {"hold": hold, "lawyer": lawyer, "placeholders": placeholders, "blocked": blocked}
return bundle, status, reasons
def group_complaints(units, claims, cir, request):
"""CP candidates: connected RCs (same CU, shared object, SG/CRG/relation label); I10 cp_split wins"""
parent = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
x = parent[x]
return x
def union(a, b):
parent[find(a)] = find(b)
rc_of = {}
for u in units:
rcs = [m["cluster_id"] for m in u["members"]]
rc_of[u["identity_id"]] = rcs[0]
for rc in rcs:
union(rc, rcs[0])
for lab in u.get("relation_labels") or []:
union(rcs[0], lab["with"].split("/")[0])
for g in cir["satisfaction_groups"] + cir["cross_rc_groups"]:
rcs = [m.split("/")[0] for m in g["members"]]
for rc in rcs:
union(rc, rcs[0])
by_object = {}
for rc, doc in claims.items():
find(rc)
for c in doc["claims"]:
for o in c.get("object_ids") or []:
by_object.setdefault(o, rc)
union(rc, by_object[o])
groups = {}
for u in units:
groups.setdefault(find(rc_of[u["identity_id"]]), []).append(u["identity_id"])
lists = [sorted(g) for g in groups.values()]
split = request.get("cp_split")
if split:
fixed = [sorted(g) for g in split]
named = [c for g in fixed for c in g]
require(len(named) == len(set(named)) and set(named) <= set(rc_of), "CP_SPLIT_INVALID", named)
taken = {c for g in fixed for c in g}
lists = fixed + [g for g in ([c for c in g if c not in taken] for g in lists) if g]
return {"CP-%02d" % (i + 1): g for i, g in enumerate(sorted(lists))}
def build_cp(cp_id, cus, bundles, statuses, common, values):
rcs = sorted({k.split("/")[0] for c in cus for k in (m["key"] for m in bundles[c]["members"])})
plaintiffs, defendants = {}, {}
for c in cus:
for rc, p in bundles[c]["parties"].items():
for x in p["plaintiffs"]:
plaintiffs.setdefault(x["party_id"], x)
defendants.setdefault(p["defendant"]["party_id"], p["defendant"])
names = [bundles[c]["case_kind"]["name"] for c in cus if bundles[c]["case_kind"]["name"]]
first = names[0]["사건 종류"] if names else None
return {
"cp_id": cp_id, "status": "CANDIDATE", "cus": [{"cu_id": c, "status": statuses[c]} for c in cus], "rcs": rcs,
"plaintiffs": list(plaintiffs.values()), "defendants": list(defendants.values()),
"case_name_candidate": None if first is None else first + (" 등" if len({n["사건 종류"] for n in names}) > 1 else ""),
"joinder_candidates": [{"cu_id": c, "relations": bundles[c]["relations"],
"alt_of": [m for m in bundles[c]["members"] if m["alt_of"] is not None]} for c in cus],
"court_inputs": {"objects": sorted({o["object_id"] for c in cus for o in bundles[c]["objects"]}),
"values": values or "NEEDS_INPUT"},
"primary_goal": common.get("primary_goal"),
"constraints": common.get("constraints"),
}
# ---------------- 0.6 packets and items ----------------
def common_block(tables):
text = ("# S2_20 공통 블록(블록 1)\n정리본의 `<!-- Lnnnn -->` 주석은 제작 좌표이므로 무시한다.\n\n"
+ "".join("## %s\n%s\n\n" % (n, pack(t)) for n, t in sorted(tables.items())))
return text
def kind_block(k, kd, elements_text=None):
e = kd["entry"]
return ("# 블록 2 — 사건 종류 index %d %s\n\n## 청구취지작성규칙 정리본 %s\n\n%s\n\n## 요건사실론 정리본 %s\n\n%s\n"
% (k, e["case_kind"], e["claim"]["file"], kd["claim"], e["elements"]["file"],
kd["elements"] if elements_text is None else elements_text))
def prepare(io, cfg):
out = cfg["output_root"]
io.reset(out)
run = {"run_id": "s2_20-" + datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ"),
"date": datetime.date.today().isoformat()}
inp, review = Inputs(io), []
request = inp.json(cfg["request_path"], optional=True) or {}
values = inp.json(cfg["values_path"], optional=True) or {}
cir, claims, plan, sources, common = load_s2_10(inp, cfg)
stage1 = Stage1(inp, cfg)
units = cir["identity_units"]
missing = [u["identity_id"] for u in units if any(c is None for _, c in member_claims(u, claims))]
require(not missing, "MEMBER_CLAIM_MISSING", missing)
kind_set = {c["case_kind_index"] for u in units for _, c in member_claims(u, claims)
if c["case_kind_index"] is not None}
man, tables, kinds, index_copies = load_index(io, inp, cfg, plan, kind_set, review)
ctx = {"claims": claims, "sources": sources, "cir": cir, "stage1": stage1, "kinds": kinds, "tables": tables,
"cfg": cfg, "common": common, "request": request, "values": values, "evidence": evidence_list(stage1)}
bundles, statuses, reasons = {}, {}, {}
for u in units:
bundles[u["identity_id"]], statuses[u["identity_id"]], reasons[u["identity_id"]] = build_cu(u, ctx)
# predecessor HOLD: the preliminary CU stays sendable with a lawyer note (never pulled down to HOLD)
cu_of = {m["key"]: c for c, b in bundles.items() for m in b.get("members", [])}
for c, b in bundles.items():
for m in b.get("members", []):
if m.get("alt_of") is not None:
main = cu_of.get(m["key"].split("/")[0] + "/" + str(m["alt_of"]))
if main and statuses[main] == "HOLD" and statuses[c] in SENDABLE:
reasons[c]["lawyer"].append("주위적 청구(%s) HOLD: 예비적 청구를 단독 청구로 유지할지" % main)
statuses[c] = "DRAFT_WITH_LAWYER_NOTE"
cps = group_complaints(units, claims, cir, request)
cp_of = {c: cp for cp, cus in cps.items() for c in cus}
hold_mode = request.get("hold_mode", "questions")
# hold_mode=draft sends HOLD CUs as provisional drafts, except a HOLD caused by a stale index (no rulebook to send)
send = [c for c in sorted(bundles) if statuses[c] in SENDABLE or (
hold_mode == "draft" and statuses[c] == "HOLD" and all(h["code"] != "INDEX_STALE" for h in reasons[c]["hold"]))]
# packets: 1_common.md, 2_kind/NNN.md, 3_cu/CU-NNN.json (= the CU bundle); names sort in block order.
# Block 1 is counted at its full budget because G2's T2 static prompt carries the rest of the design's block 1.
common_text = common_block(tables)
require(len(common_text) <= cfg["common_budget"], "COMMON_BLOCK_OVER_BUDGET", len(common_text))
io.write(out + "/packet/1_common.md", common_text)
b1_len = cfg["common_budget"]
kind_text = {None: "# 블록 2 — 규칙문서 없음\n사건 종류 미정(REGISTRY_GAP). 공통 블록의 급부 클래스 불변식만 적용하고 다른 종의 규칙문서를 쓰지 않는다.\n"}
io.write(out + "/packet/2_kind/none.md", kind_text[None])
for k in sorted(kind_set):
if not kinds[k].get("stale") and any(bundles[c]["case_kind"]["index"] == k for c in send):
kind_text[k] = kind_block(k, kinds[k])
io.write(out + "/packet/2_kind/%03d.md" % k, kind_text[k])
items = []
for c in send:
b = bundles[c]
k = b["case_kind"]["index"]
b["cp"] = {"cp_id": cp_of[c], "cus": cps[cp_of[c]],
"defendants": sorted({bundles[x]["parties"][rc]["defendant"]["name"] for x in cps[cp_of[c]] for rc in bundles[x].get("parties", {})})}
b2_path = out + ("/packet/2_kind/none.md" if k is None else "/packet/2_kind/%03d.md" % k)
b2_len = len(kind_text[k])
shared = True
b["drafting_status"] = statuses[c]
b["instructions"] = DIRECTIVES[statuses[c]]
b["lawyer_notes"] = reasons[c]["lawyer"]
b["placeholders"] = reasons[c]["placeholders"]
b["hold_questions"] = [h["detail"] for h in reasons[c]["hold"]] if statuses[c] == "HOLD" else []
b["run"] = run
b3_text = pack(b)
total = b1_len + b2_len + len(b3_text)
if total > cfg["packet_limit"]:
# overflow ①: keep context-thread facts as ref + evidence_index only (the CU's own ref bodies stay)
for f in b["facts"]:
if not f["own"]:
f["body"], f["body_dropped"] = None, True
b3_text = pack(b)
total = b1_len + b2_len + len(b3_text)
if total > cfg["packet_limit"] and k is not None:
# overflow ②: lawyer-given path → drop the other per-path sections (this CU no longer shares the kind prefix)
keep = b["path_hint"]["lawyer_path"]
if keep in kinds[k]["entry"]["elements"]["path_sections"]:
text = kind_block(k, kinds[k], restrict_paths(kinds[k]["entry"], kinds[k]["elements"], keep))
b2_path, b2_len, shared = out + "/packet/2_kind/%03d-%s.md" % (k, c), len(text), False
io.write(b2_path, text)
total = b1_len + b2_len + len(b3_text)
if total > cfg["packet_limit"]:
statuses[c] = b["drafting_status"] = "HOLD"
reasons[c]["hold"].append({"code": "PACKET_OVERFLOW",
"detail": "패킷 %d자가 한도 %d자를 넘는다. 요건사실론 경로를 지정하면(path_hint) 다른 경로 절을 빼고 보낸다" % (total, cfg["packet_limit"])})
b["instructions"] = None
b["hold_questions"] = [h["detail"] for h in reasons[c]["hold"]]
continue
items.append({"run_id": run["run_id"], "cu_id": c, "cp_id": cp_of[c], "case_kind_index": k, "status": statuses[c],
"block2_path": b2_path, "block3_path": out + "/packet/3_cu/%s.json" % c,
"cache_key": "s2_20:draft:%s" % ("none" if k is None else "%03d" % k), "cache_shared": shared,
"packet_chars": {"block1": len(common_text), "block1_budget": b1_len, "block2": b2_len,
"block3": len(b3_text), "total": total}})
sent = {i["cu_id"] for i in items}
for c in sorted(bundles):
b = bundles[c]
if "run" not in b:
b["drafting_status"] = statuses[c]
b["hold_questions"] = [h["detail"] for h in reasons[c]["hold"] + reasons[c]["blocked"]]
b["run"] = run
io.write(out + "/bundle/claims/%s.json" % c, pack(b))
if c in sent:
io.write(out + "/packet/3_cu/%s.json" % c, pack(b))
# lead/rest split (§4 T0 0.6) and prefer=cost|speed by wave count
items.sort(key=lambda x: (x["case_kind_index"] is None, x["case_kind_index"] or 0, x["cp_id"], x["cu_id"]))
seen, lead, rest = set(), [], []
for it in items:
k = it["case_kind_index"]
if k is not None and it["cache_shared"] and k not in seen:
seen.add(k)
lead.append(it)
else:
rest.append(it)
n, l, conc = len(items), len(lead), cfg["concurrency"]
one, two = math.ceil(n / conc), math.ceil(l / conc) + math.ceil((n - l) / conc)
prefer = request.get("prefer") or ("speed" if two > one else "cost")
if prefer == "speed":
lead, rest = items, []
for cp, cus in cps.items():
io.write(out + "/bundle/complaints/%s.json" % cp, pack(build_cp(cp, cus, bundles, statuses, common, values)))
case_bundle = {
"run": run, "parties": common.get("party_registry"), "plaintiff_capacity_matrix": common.get("plaintiff_capacity_matrix"),
"units": common.get("units"), "standing_watchpoints": common.get("standing_watchpoints"),
"objects": common.get("object_registry"), "constraints": common.get("constraints"), "primary_goal": common.get("primary_goal"),
"cu_index": [{"cu_id": u["identity_id"], "members": ["%s/%s" % (m["cluster_id"], m["seq"]) for m in u["members"]],
"status": statuses[u["identity_id"]], "cp_id": cp_of[u["identity_id"]]} for u in units],
"relations": {"satisfaction_groups": cir["satisfaction_groups"], "cross_rc_groups": cir["cross_rc_groups"]},
"ancillary_claims": cir["ancillary_claims"], "evidence": ctx["evidence"],
"complaints": cps,
}
io.write(out + "/bundle/case_bundle.json", pack(case_bundle))
holds = {"run": run, "review": review,
"items": [{"cu_id": c, "status": statuses[c], "reasons": reasons[c]["hold"] + reasons[c]["blocked"],
"exclude_flags": [f for f in bundles[c]["legality_flags"] if f["code"] == "EXCLUDE_RECOMMENDED"]}
for c in sorted(bundles) if c not in sent]}
io.write(out + "/review/holds.json", pack(holds))
io.write(out + "/items/lead.json", pack(lead))
io.write(out + "/items/rest.json", pack(rest))
snapshot = []
for path, raw in sorted(inp.raw.items()):
io.write_binary(out + "/snapshot/" + path, raw)
snapshot.append({"path": path, "raw_sha256": sha(raw), "byte_length": len(raw)})
for name, raw in sorted(index_copies.items()):
io.write_binary(out + "/snapshot/index/" + name, raw)
snapshot.append({"path": out + "/snapshot/index/" + name, "raw_sha256": sha(raw), "byte_length": len(raw)})
io.write(out + "/snapshot/snapshot_manifest.json", pack({"run": run, "files": snapshot}))
counts = {}
for c in statuses.values():
counts[c] = counts.get(c, 0) + 1
result = {"status": "PREPARED", "run": run, "prefer": prefer, "hold_mode": hold_mode,
"counts": counts, "sent": n, "kinds": l,
"waves": {"single_stage": one, "two_stage": two}, "complaints": cps, "review": review,
"lead": [i["cu_id"] for i in lead], "rest": [i["cu_id"] for i in rest]}
io.write(out + "/prepare.json", pack(result))
result["dynamic_fanout"] = lead
return result
def failure(io, cfg, exc):
result = {"status": "BLOCKED", "dynamic_fanout": [],
"error": {"code": getattr(exc, "code", "S2_20_PREPARE_FAILED"), "detail": getattr(exc, "detail", str(exc))[:1000]}}
try:
out = cfg["output_root"]
io.write(out + "/items/lead.json", "[]")
io.write(out + "/items/rest.json", "[]")
io.write(out + "/prepare.json", pack(result))
except Exception as log_exc:
result["diagnostic"] = str(log_exc)[:300]
return result
# ---- main ----
io = None
try:
io = Localdocs()
result = prepare(io, CFG)
except Exception as exc:
result = failure(io, CFG, exc)
finally:
if io is not None:
io.close()
print(json.dumps(result, ensure_ascii=False))
# ---- G2 task 자리(다음 단계에서 작성) ----
# Task_S2_20_draft_lead_* T2a LLM fan-out. preflight_files: [stage2_runs/from-stage1/s2_20/packet/1_common.md, "{{item.block2_path}}", "{{item.block3_path}}"]
# Task_S2_20_verify_lead_* T3a 코드 체인(V1~V9) → s2_20/verify/CU-NNN.json
# Task_S2_20_load_rest T1 코드 정적 로더: items/rest.json → dynamic_fanout
# Task_S2_20_draft_rest_* T2b LLM fan-out(T2a와 같은 프롬프트·같은 preflight)
# Task_S2_20_verify_rest_* T3b 코드 체인
task_procedure:
IN:
nexts:
- Task_S2_20_prepare
wait_until: []
Task_S2_20_prepare:
nexts:
- Task_S2_20_draft_lead_*
- Task_S2_20_verify_lead_*
- Task_S2_20_load_rest
wait_until:
- IN
Task_S2_20_draft_lead_*:
nexts:
- Task_S2_20_verify_lead_{same_ordinal}
wait_until:
- Task_S2_20_prepare
Task_S2_20_verify_lead_*:
nexts:
- Task_S2_20_load_rest
wait_until:
- Task_S2_20_draft_lead_{same_ordinal}
Task_S2_20_load_rest:
nexts:
- Task_S2_20_draft_rest_*
- Task_S2_20_verify_rest_*
- OUT
wait_until:
- all Task_S2_20_verify_lead_*
- Task_S2_20_prepare
Task_S2_20_draft_rest_*:
nexts:
- Task_S2_20_verify_rest_{same_ordinal}
wait_until:
- Task_S2_20_load_rest
Task_S2_20_verify_rest_*:
nexts:
- OUT
wait_until:
- Task_S2_20_draft_rest_{same_ordinal}
OUT:
nexts: []
wait_until:
- all Task_S2_20_verify_rest_*
- Task_S2_20_load_rest

Some files were not shown because too many files have changed in this diff Show More