feat(stage2): S2_20 2.7.4-g3 and S2_30 1.3.3-g5 complaint grouping minimal plan

Apply items 1-11 of the CU-to-complaint grouping criteria (11-18 doc, section 4.1).

S2_20 T0 group_complaints:
- a shared object alone no longer joins RCs; it raises JOINDER_LATTER_CANDIDATE
  (§65 latter-sentence candidate), except when the S2_10 cross call did not run
  (OBJECT_LINK_CROSS_NOT_REVIEWED keeps the old join)
- NONE labels skipped; SAME_PAIR joins RCs with an overlapping plaintiff and the
  same defendant; CROSS_HOLD_SEPARATED and LABEL_JOIN_REVIEW reviews
- reviews judged on final candidates after cp_split; link_reasons on CP candidates
S2_20 T5 plan_cp: LC_PERIOD_FLAG for merged CUs with LC-PERIOD ISSUE/UNKNOWN.
S2_30 calculate court_review: JUR_PANEL, JUR_SMALL_CLAIM, JUR_APPEAL_HIGH_COURT
(sealed appeal_court), JUR_SPLIT_HINT via sealed evaluate_complaint per RC;
schema kind CHECK, numbers unchanged. Sealed assets and S2_10 unchanged.

Also adds the HITL complaint-regrouping options design note (11-19).
Two independent verification rounds; offline tests and golden 516/516 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 12:09:22 +09:00
co-authored by Claude Opus 5.5
parent 027a531e88
commit 0c580c65a7
10 changed files with 11949 additions and 24 deletions
@@ -6,7 +6,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "src")
OUT = sys.argv[1]
WITH_G5 = "--g5" in sys.argv[2:]
VERSION = "1.3.2-g5" if WITH_G5 else "1.2.1-g4"
VERSION = "1.3.3-g5" if WITH_G5 else "1.2.1-g4"
def rd(name):
@@ -1,3 +1,6 @@
# 2026-11-19 1.3.3-g5 소장 묶음 최소안(소장작성_개별청구권묶음기준_11_18.md §4.1 9~11번)을 calculate 단계에 넣었다. 개정 전 YAML 사본은 Stage_2_S2_30_G4_G5_11_19_pre_group.yml, 생성기 원본은 커밋 027a531e.
# court_review(t_calculate.py): 이미 계산한 관할로 review를 단다(스키마 kind CHECK, name이 코드). 합의부 JUR_PANEL, 소액 JUR_SMALL_CLAIM, 단독인데 소가 2억 원 초과면 JUR_APPEAL_HIGH_COURT(봉인 soga_calc.appeal_court를 호출만 한다; 관할이 정해진 소장의 result/CP-NN.json에 appeal_court).
# 청구마다 정확히 한 RC에만 속하고 RC가 둘 이상인 소장은 RC마다 봉인 evaluate_complaint로 따로 계산해, 나누면 관할이 낮아질 때 JUR_SPLIT_HINT를 단다. 숫자(소가·인지·관할)는 바꾸지 않는다. 봉인 자산은 그대로다.
# 2026-11-18 1.3.2-g5 제소 기준일 안내 문구를 S2_20 2.7.3-g3(작업실 소제기일 우선)에 맞췄다. 문구만 바뀌었다(로직·자산 불변). 개정 전 원본은 커밋 2554da9b.
# review_notes.md 기본값 줄: '작업실 소제기일에 입력하거나 s2_20_request.json에 넣고 S2_20부터 다시 실행한다'(S2_30은 S2_20이 쓴 request 파일만 읽는다). §4 양식 줄에는 FILING_DATE 항목이 있을 때만 'FILING_DATE는 위 제소 기준일 줄을 따른다'를 붙인다.
# 남은 불일치: 봉인 자산 soga_adapter.py의 FILING_DATE 항목 문구는 request 파일만 든다(재봉인 필요, 이번 범위 밖). Stage_2_S2_30_G4.yml은 다시 만들지 않았다.
@@ -49,6 +49,56 @@ def cp_packet(io, cfg, binding, ad, out, cp_id, plan):
return packet, chars, trimmed
def court_review(ad, out, calc):
"""1.3.3 (grouping criteria 11-18 §4.1 items 9-11): court review items from numbers the calculation already made.
Panel and small-claim results become review items; appeal_court() (사물관할규칙 §4①) is wired in and a sole-judge complaint over the
high-court line gets an item; when every claim belongs to one RC, each RC is run through the sealed evaluate_complaint alone to show
when splitting the complaint would lower the court. Items use the schema kind CHECK (name = review code). Numbers are never changed here."""
tier = lambda s: 0 if s == "소액사건" else 1 if str(s).startswith("단독") else 2 if s == "합의부" else None
won = lambda v: "%s원" % format(v, ",") if isinstance(v, int) else "소가 없음"
for cp in ad["complaints"]:
res = out["results"].get(cp["cp_id"])
if not res or not (res["jurisdiction"].get("steps") or []) or res["jurisdiction"]["status"] == "NEEDS_INPUT":
continue
first, soga, date, exc = res["jurisdiction"]["steps"][0], res.get("soga"), res.get("filing_date"), cp.get("exception_kind")
def add(code, text, **kw):
out["review_items"].append(dict({"item_id": "SG-%03d" % (len(out["review_items"]) + 1), "kind": "CHECK", "cp_id": cp["cp_id"],
"cu_id": None, "claim_id": None, "name": code, "value": soga, "status": "NEEDS_REVIEW", "text": text,
"basis": {"rule": "REVIEW", "text": None, "refs": []}, "alternatives": [], "answer_key": None}, **kw))
rcs_of = {ci["claim_id"]: sorted({str(m).split("/")[0] for m in ci.get("members") or []}) for ci in cp["claims"]}
all_rcs = sorted({rc for v in rcs_of.values() for rc in v})
why = "; ".join(res["jurisdiction"].get("notes") or [])
np = any(i.get("name") == "인지법 §2④ 사건" and i.get("value") is True for i in res["jurisdiction"].get("inputs") or [])
if first == "합의부" and np and "§2④" not in why:
why = "; ".join(x for x in (why, "비재산권·산출불능 청구 포함(인지법 §2④)") if x)
shown = ("소가 %s" % won(soga) if isinstance(soga, int) else "소가 없음") + (", %s" % why if why else "")
if first == "합의부":
add("JUR_PANEL", "합의부 사건(%s; 사물관할규칙 §2)%s" % (shown, ". RC %d개를 한 소장으로 묶었다 — 아래 분리 가정 항목이 있으면 함께 본다" % len(all_rcs) if len(all_rcs) > 1 else ""))
elif first == "소액사건":
add("JUR_SMALL_CLAIM", "소액사건(소가 %s; 소액사건심판규칙 §1의2). 소액사건심판법 §5의2 일부청구 금지와 다른 청구를 병합하면 소액이 아니게 되는지 확인" % won(soga))
appeal = calc.appeal_court(soga, "합의부" if first == "합의부" else "단독", exc, date)
res["appeal_court"] = appeal.table()
if tier(first) is not None and tier(first) < 2 and appeal.steps and appeal.steps[0] == "고등법원":
add("JUR_APPEAL_HIGH_COURT", "단독 사건이지만 소가 %s이 2억 원을 넘어 항소심은 고등법원이다(사물관할규칙 §4①)" % won(soga))
if len(all_rcs) < 2 or any(len(v) != 1 for v in rcs_of.values()) or tier(first) is None:
continue
hints, unknown = [], []
for rc in all_rcs:
part = dict(cp, claims=[{k: v for k, v in ci.items() if not k.startswith("_")} for ci in cp["claims"] if rcs_of[ci["claim_id"]] == [rc]])
r = calc.evaluate_complaint(part)
step = (r["jurisdiction"].get("steps") or [None])[0]
if r.get("soga") is None and tier(step) != 2:
unknown.append(rc)
elif tier(step) is not None:
hints.append((rc, r.get("soga"), step))
if hints and min(tier(s) for _, _, s in hints) < tier(first):
add("JUR_SPLIT_HINT", "소장을 RC별로 나누면 %s%s — 지금 묶음은 %s. 나누면 인지·송달료를 따로 내고 관련재판적(민사소송법 §25)을 잃을 수 있다. "
"나누려면 cp_split에 CU 번호로 적고 S2_20부터 다시 실행한다"
% (", ".join("%s %s %s" % (rc, won(v), s) for rc, v, s in hints), "(소가를 정하지 못한 RC: %s)" % ", ".join(unknown) if unknown else "", first),
alternatives=[{"rc": rc, "soga": v, "jurisdiction": s} for rc, v, s in hints])
out["summary"]["review_item_count"] = len(out["review_items"])
def calculate_step(io, cfg, prev_raw):
"""G4 step 5 calculate: classify + decisions + external values + review answers -> soga per CP, prayer amounts, T6 packets"""
binding = binding_for(io, cfg, prev_raw, "Task_S2_30_load_decide", ("FANOUT_READY",))
@@ -83,6 +133,7 @@ def calculate_step(io, cfg, prev_raw):
bad = dropped + bad
adapter.apply_decisions(ad, ok, bad, src)
out = adapter.calculate(ad, assets["calc"])
court_review(ad, out, assets["calc"])
cu_of = {c["claim_id"]: c["cu_id"] for cp in ad["complaints"] for c in cp["claims"]}
owner = lambda d: d.get("_resp_cu") or cu_of.get(d.get("claim_id"))
for e in entries:
@@ -1,3 +1,9 @@
# 2026-11-19 개정(2.7.4-g3; 개정 전 사본 Stage_2_S2_20_G1_G2_G3_11_19_pre_group.yml): 소장 묶음 최소안(소장작성_개별청구권묶음기준_11_18.md §4.1 1~8번)을 적용했다. 고친 곳은 T0 group_complaints·build_cp와 T4z 등급표, T5 plan_cp다.
# T0: 같은 목적물(object_ids)만으로는 RC를 잇지 않고 JOINDER_LATTER_CANDIDATE(§65 후문 후보) review를 낸다. 단 S2_10 RC 간 판정이 돌지 않았으면(filter_review cross_status SKIPPED_OVERSIZE·FAILED 또는 CROSS_NOT_REVIEWED) 종전처럼 잇고 OBJECT_LINK_CROSS_NOT_REVIEWED review를 낸다.
# T0: relation NONE 라벨은 잇지 않는다. 원고 party_id가 겹치고 피고 party_id가 같은 RC를 잇는다(SAME_PAIR). S2_10 holds 중 여러 RC에 걸친 것이 다른 후보로 나뉘면 CROSS_HOLD_SEPARATED review를 낸다(판정이 돈 경우만).
# T0: 피고가 다른 RC를 CONCURRENT·ALTERNATIVE 라벨로 이었으면 잇되 LABEL_JOIN_REVIEW를 낸다(§2 표). review는 cp_split을 적용한 최종 후보로 판정하고, 같은 RC 묶음의 목적물은 한 건으로 모으며, 장부 행은 관련 RC마다 낸다.
# T0: CP 후보(bundle/complaints/CP-NN.json)에 link_reasons(그 후보의 RC끼리 자동 묶음이 이은 간선 [{rcs, reason}]; cp_split으로만 묶인 RC 사이에는 간선이 없다)를 더한다. 새 review 네 코드는 RUN_ITEM_CODES와 T4z GRADE3에 넣었다. COPARTY_BASIS(T5)는 그대로다.
# T5: 병합 CU 초안의 legal_checks LC-PERIOD가 ISSUE·UNKNOWN이면 plan review에 LC_PERIOD_FLAG를 더한다(S2_30 verify_cp W8이 그대로 옮긴다). 프롬프트·LLM 호출·다른 task는 그대로다.
# 2026-11-18 개정(2.7.3-g3; 개정 전 사본 Stage_2_S2_20_G1_G2_G3_11_18_pre_env.yml): 제소 기준일을 작업실(workspace) 소제기일에서 먼저 읽는다(SKILL.md §4.1 env.filing_date). 고친 곳은 T0 prepare뿐이다.
# T0 코드 CFG 옆 상수 ENV_FILING_DATE가 실행 시작 때 작업실 소제기일(YYYY-MM-DD, 미입력이면 빈 문자열)의 Python 리터럴(§4.1 py 필터)로 치환된다. 값이 코드 문자열을 깨지 못하게 하려고 py 필터를 쓴다.
# 날짜 형식이 아닌 값은 날짜 검사(valid_date)에서 떨어져 미입력으로 처리된다(새 review 코드 없음). py 필터를 치환하지 않는 백엔드에서는 T0가 시작하지 못한다(배포 전 확인).
@@ -316,7 +322,7 @@
Agent:
name: Stage_2_S2_20_v2
description: "S2_20 v.2(사전 색인 rbidx/2.1.0) — G1 준비(T0 prepare), 캐시 예열(T2p·T1a), G2 CU 초안 작성·검사(T2a·T3a·T1·T2b·T3b), G3 CU 보수(T4p·T4·T3c; LLM gpt-6.1-sol), 검토 장부(T4z), 소장 계획(T5 plan_cp). CU별 청구취지·청구원인 초안과 검사·보수 결과(draft/·verify/), 검토 장부(review/review_ledger.*), CP별 소장 계획(plan/CP-NN.json)까지 낸다. 소장 문안은 만들지 않는다."
version: 2.7.3-g3
version: 2.7.4-g3
Stages:
- name: S2_20_draft_pleadings
description: S2_10 7.6.0 CU별 청구취지·청구원인 초안과 소장 묶음(CP) 병합. 이 파일은 G1(T0), 캐시 예열(T2p·T1a), G2(CU 초안·검사), G3(CU 보수), 검토 장부(T4z)와 소장 계획(T5 plan_cp)을 구현한다.
@@ -371,7 +377,8 @@ Agent:
REVIEW_ARRAY_KEYS = ("blocked_review_items", "hard_gate_findings", "review_findings", "review_items", "review_queue", "unresolved_review_items") # S2_00 REVIEW_ARRAY_KEYS
REQUIRED_REVIEW_DOCS = ("stage1_part1_soft_gate_handoff", "stage1_part2_review_handoff", "stage1_part3_review_handoff", "stage1_part4_review_handoff",
"b1_evidence_indexed_gate", "b2_event_candidates_gate", "client_goal")
RUN_ITEM_CODES = ("RC_BLOCKED_SKIPPED", "RC_REVIEW_REQUESTS", "RELIEF_LEGAL_REVIEW", "AMOUNT_REVIEW_NO_CLAIM", "AMOUNT_REVIEW_MALFORMED", "AMOUNT_REVIEW_UNREACHED", "SLICE_SOURCE_MISMATCH")
RUN_ITEM_CODES = ("RC_BLOCKED_SKIPPED", "RC_REVIEW_REQUESTS", "RELIEF_LEGAL_REVIEW", "AMOUNT_REVIEW_NO_CLAIM", "AMOUNT_REVIEW_MALFORMED", "AMOUNT_REVIEW_UNREACHED", "SLICE_SOURCE_MISMATCH",
"JOINDER_LATTER_CANDIDATE", "OBJECT_LINK_CROSS_NOT_REVIEWED", "CROSS_HOLD_SEPARATED", "LABEL_JOIN_REVIEW")
OPERATOR = ("VERIFY_MISSING", "VERIFY_ERROR", "REPAIR_CALL_FAILED", "REPAIR_NOT_RUN", "REPAIR_PACKET_OVERFLOW", "REPAIR_LOAD_ERROR", "DRAFT_UNPARSED", "OUTPUT_PARSE_FAILED",
"OUTPUT_CU_MISMATCH", "SCHEMA_INVALID", "LLM_STATUS", "INDEX_STALE", "STATUS_SET_MISSING", "REVIEW_ITEMS_FAILED", "DRAFT_MISSING",
"EXTENSION_PAYLOAD_KEY_UNDECLARED", "seed_admission_repair", "WORKER_SLICE_GUARD_MISMATCH", "SCHEMA_PATTERN", "SLICE_SPLIT", "CORRECTIONS", "LEDGER_CU_ERROR",
@@ -1390,35 +1397,70 @@ Agent:
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 group_complaints(units, claims, cir, request, review, run_items):
"""CP candidates: connected RCs (same CU, relation label other than NONE, SG/CRG group, same plaintiff and defendant); I10 cp_split wins.
2.7.4 (grouping criteria 11-18 §4.1): a shared object alone no longer joins RCs; RCs it would have joined become a §65 latter-sentence
candidate review. When the S2_10 cross call did not run (CROSS_NOT_REVIEWED) the object join stays, with a review. Reviews are judged
on the final candidates (after cp_split). Returns (cps, links)."""
parent, links = {}, {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
x = parent[x]
return x
def union(a, b):
def union(a, b, why):
if a != b:
links.setdefault((min(a, b), max(a, b), why), None)
parent[find(a)] = find(b)
rc_of = {}
pair = {}
for rc, doc in sorted(claims.items()):
find(rc)
p = doc.get("pair") or {}
plaintiffs = {x.get("party_id") for x in p.get("plaintiffs") or [] if isinstance(x, dict)} - {None}
pair[rc] = (plaintiffs, (p.get("defendant") or {}).get("party_id"))
rc_of, label_pairs = {}, []
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])
union(rc, rcs[0], "SAME_CU:" + u["identity_id"])
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"]:
if lab.get("relation") != "NONE": # 2.7.4: NONE is "no relation" (the S2_10 validator lets it through)
other = lab["with"].split("/")[0]
union(rcs[0], other, "LABEL:%s" % lab.get("relation"))
if lab.get("relation") in ("CONCURRENT", "ALTERNATIVE") and rcs[0] != other:
label_pairs.append((sorted([rcs[0], other]), lab["relation"]))
for tag, gs in (("SG", cir["satisfaction_groups"]), ("CRG", cir["cross_rc_groups"])):
for g in gs:
rcs = [m.split("/")[0] for m in g["members"]]
for rc in rcs:
union(rc, rcs[0])
union(rc, rcs[0], "%s:%s" % (tag, g.get("group_id")))
# 2.7.4: same pair = an overlapping plaintiff party_id and the same defendant party_id (needed once the object join is gone)
in_units = {m["cluster_id"] for u in units for m in u["members"]}
known = sorted(rc for rc, (pl, d) in pair.items() if pl and d is not None and rc in in_units)
for a, b in itertools.combinations(known, 2):
if pair[a][1] == pair[b][1] and pair[a][0] & pair[b][0]:
union(a, b, "SAME_PAIR")
# 2.7.4: shared object. The S2_10 cross call reviews every such pair, so no label means no relation it could find; what is left is §65 latter sentence.
fr = cir.get("filter_review") or {}
cross_skipped = fr.get("cross_status") in ("SKIPPED_OVERSIZE", "FAILED") or any(
isinstance(x, dict) and x.get("code") == "CROSS_NOT_REVIEWED" for x in (fr.get("validation") or {}).get("reviews") or [])
by_object = {}
for rc, doc in claims.items():
find(rc)
for rc, doc in sorted(claims.items()):
for c in doc["claims"]:
for o in c.get("object_ids") or []:
by_object.setdefault(o, rc)
union(rc, by_object[o])
if rc not in by_object.setdefault(o, []):
by_object[o].append(rc)
object_sets = {} # RC set -> shared objects, kept only where the other links left those RCs apart
for o, rcs in sorted(by_object.items()):
if len({find(rc) for rc in rcs}) < 2:
continue
object_sets.setdefault(tuple(rcs), []).append(o)
if cross_skipped: # second pass, so every object of an RC set is listed and linked
for rcs, objs in object_sets.items():
for o in objs:
for rc in rcs[1:]:
union(rc, rcs[0], "OBJECT_CROSS_NOT_REVIEWED:%s" % o)
groups = {}
for u in units:
groups.setdefault(find(rc_of[u["identity_id"]]), []).append(u["identity_id"])
@@ -1430,10 +1472,49 @@ Agent:
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))}
cps = {"CP-%02d" % (i + 1): g for i, g in enumerate(sorted(lists))}
# reviews on the final candidates: RCs are together when one candidate holds all of them
cps_of = {}
for u in units:
for m in u["members"]:
cps_of.setdefault(m["cluster_id"], set()).update(cp for cp, g in cps.items() if u["identity_id"] in g)
together = lambda rcs: bool(set.intersection(*[cps_of.get(rc, set()) for rc in rcs]))
by_lawyer = "; cp_split으로 정한 묶음이면 그대로 둔다" if split else ""
def rr(code, rcs, note): # the review row once, a ledger row on every RC so each candidate's section shows it
run_review(review, run_items, code, rcs[0], note)
run_items.extend({"code": code, "rc": rc, "text": note} for rc in rcs[1:])
for rcs, objs in sorted(object_sets.items()):
if cross_skipped and together(rcs):
rr("OBJECT_LINK_CROSS_NOT_REVIEWED", list(rcs),
"%s: 목적물 %s를 함께 가진 RC를 한 소장 후보로 묶었다. S2_10의 RC 간 관계 판정이 돌지 않아(CROSS_NOT_REVIEWED) 같은 목적물만 근거다. "
"공동소송 요건(민사소송법 §65)과 관할을 확인하고, 나누려면 cp_split에 CU 번호로 적고 S2_20부터 다시 실행한다" % (", ".join(rcs), ", ".join(objs)))
elif not cross_skipped and not together(rcs):
same_defendant = len({pair.get(rc, (None, None))[1] for rc in rcs}) == 1 and pair.get(rcs[0], (None, None))[1] is not None
court = ("피고가 같으므로 피고의 보통재판적(§2·§3) 법원에 함께 낼 수 있다. 원고가 다르므로 §65 요건을 확인한다" if same_defendant else
"피고가 여럿인 후문 공동소송에는 관련재판적(§25②)이 적용되지 않으므로 각 피고에 대해 같은 법원에 관할이 있는지(예: 부동산 소재지 §20) 확인한다")
rr("JOINDER_LATTER_CANDIDATE", list(rcs),
"%s: 목적물 %s를 함께 가졌지만 다른 소장 후보로 나뉘었다. 민사소송법 §65 후문(같은 종류의 권리·의무, 같은 종류의 사실상·법률상 원인) 공동소송 후보다. "
"%s. 묶으려면 cp_split에 CU 번호로 적고 S2_20부터 다시 실행한다%s" % (", ".join(rcs), ", ".join(objs), court, by_lawyer))
# 2.7.4: cross holds (relation unclear, S2_10 delta holds) whose RCs ended in different candidates
if not cross_skipped:
for h in cir.get("holds") or []:
rcs = sorted({str(r).split("/")[0] for r in h.get("cand_refs") or []})
if len(rcs) > 1 and not together(rcs):
rr("CROSS_HOLD_SEPARATED", rcs,
"%s: S2_10이 RC 간 관계를 보류했다(%s). 이 RC들은 다른 소장 후보로 나뉘었다. 관계를 확인한 뒤 묶으려면 cp_split에 CU 번호로 적고 S2_20부터 다시 실행한다%s"
% (", ".join(rcs), h.get("question"), by_lawyer))
# 2.7.4 (§2 table via §4.1 item 7): a CONCURRENT or ALTERNATIVE label joining RCs with different defendants stays a join, with a review
for rcs, rel in sorted({(tuple(r), rel) for r, rel in label_pairs}):
ds = {pair.get(rc, (None, None))[1] for rc in rcs}
if len(ds) > 1 and together(list(rcs)):
rr("LABEL_JOIN_REVIEW", list(rcs),
"%s: S2_10 %s 라벨(%s)로 피고가 다른 RC를 한 소장 후보로 묶었다. 공동소송 요건(민사소송법 §65)은 법적 판단이므로 확인하고, "
"나누려면 cp_split에 CU 번호로 적고 S2_20부터 다시 실행한다"
% (", ".join(rcs), rel, "함께 성립" if rel == "CONCURRENT" else "대체 구제수단, §70과 다른 개념"))
return cps, [{"rcs": [a, b], "reason": why} for a, b, why in sorted(links)]
def build_cp(cp_id, cus, bundles, statuses, common, values):
def build_cp(cp_id, cus, bundles, statuses, common, values, links):
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:
@@ -1451,6 +1532,7 @@ Agent:
"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"},
"link_reasons": [x for x in links if set(x["rcs"]) <= set(rcs)], # 2.7.4: why these RCs are one candidate (union edges)
"primary_goal": common.get("primary_goal"),
"constraints": common.get("constraints"),
}
@@ -1586,7 +1668,7 @@ Agent:
reasons[c]["coded"].append({"code": "PRIMARY_HELD", "text": text})
statuses[c] = "DRAFT_WITH_LAWYER_NOTE"
cps = group_complaints(units, claims, cir, request)
cps, links = group_complaints(units, claims, cir, request, review, run_items)
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)
@@ -1679,7 +1761,7 @@ Agent:
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)))
io.write(out + "/bundle/complaints/%s.json" % cp, pack(build_cp(cp, cus, bundles, statuses, common, values, links)))
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"),
@@ -4622,7 +4704,8 @@ Agent:
NOT_A_CLAIM_PARTIAL UNSPECIFIED_RELIEF PLAINTIFF_SHARE_UNKNOWN CLIENT_DEFERRED
RELIEF_DETAIL_MISSING ANCILLARY_RATE_UNSPECIFIED PLAINTIFF_SHARE_PENDING""".split())
GRADE3 = frozenset("""MISSING_FACT CROSS_RC ELEMENT_MISSING_REVIEW RC_REVIEW_REQUESTS RELIEF_LEGAL_REVIEW REGISTRY_GAP QUESTION SELF_REPORT_CONFLICT RESIDUAL_OBJECT_WITHOUT_PAIR
EXPECTED_DEFENSE UNROUTED_ISSUE_REVIEW LOW_CONFIDENCE_DECISION HOLD_UNIT_PRESENT REC_RESTORE_BLOCKED TRACK_B_EXCLUSION_FLAGGED NON_KOREAN_TEXT""".split())
EXPECTED_DEFENSE UNROUTED_ISSUE_REVIEW LOW_CONFIDENCE_DECISION HOLD_UNIT_PRESENT REC_RESTORE_BLOCKED TRACK_B_EXCLUSION_FLAGGED NON_KOREAN_TEXT
JOINDER_LATTER_CANDIDATE OBJECT_LINK_CROSS_NOT_REVIEWED CROSS_HOLD_SEPARATED LABEL_JOIN_REVIEW""".split())
GRADE4 = frozenset("""JOIN_NOTE ALTERNATIVE DEFERRED COPARTY_ORDINARY PRECONDITION_CHAIN COMPATIBILITY_REVIEW SUBJECT_TO_MERITS NOT_A_CLAIM LAWYER_ANSWER REPAIR_HISTORY STAGE1_DRAFTING_BLOCK_REVIEW
DUP_SUSPECT DUP_SUSPECT_CORRECTION ORDER_TEXT_ALTERNATIVE COMPATIBILITY_REVIEW_FLAGGED OUTPUT_LENGTH_REVIEW""".split())
GATE_UNRUN = ("GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW", "GATE_CONDITION_KEY_UNSUPPORTED_REVIEW")
@@ -5357,6 +5440,11 @@ Agent:
continue
shared.setdefault(n, []).append({"ref": f["ref"], "fact_id": f["body"].get("fact_id"), "shared_from": f["shared_from"]})
draft = read_json(io, out + "/draft/%s.json" % c)
if isinstance(draft, dict) and isinstance(draft.get("legal_checks"), list): # 2.7.4: period check not CLEAR (limitation, exclusion, filing period)
for x in draft["legal_checks"]:
if isinstance(x, dict) and x.get("check_id") == "LC-PERIOD" and x.get("value") in ("ISSUE", "UNKNOWN"):
review.append(item("LC_PERIOD_FLAG", "기간 검사 %s(시효·제척·출소기간): %s — 소 제기 시기와 이 청구를 이 소장에 둘지 확인"
% (x["value"], str(x.get("reason") or "")[:120]), [c]))
rows = (draft.get("prayer") or {}).get("relief") if isinstance(draft, dict) and "unparsed" not in draft else None
rows = [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else []
if not rows:
@@ -1,3 +1,6 @@
# 2026-11-19 1.3.3-g5 소장 묶음 최소안(소장작성_개별청구권묶음기준_11_18.md §4.1 9~11번)을 calculate 단계에 넣었다. 개정 전 YAML 사본은 Stage_2_S2_30_G4_G5_11_19_pre_group.yml, 생성기 원본은 커밋 027a531e.
# court_review(t_calculate.py): 이미 계산한 관할로 review를 단다(스키마 kind CHECK, name이 코드). 합의부 JUR_PANEL, 소액 JUR_SMALL_CLAIM, 단독인데 소가 2억 원 초과면 JUR_APPEAL_HIGH_COURT(봉인 soga_calc.appeal_court를 호출만 한다; 관할이 정해진 소장의 result/CP-NN.json에 appeal_court).
# 청구마다 정확히 한 RC에만 속하고 RC가 둘 이상인 소장은 RC마다 봉인 evaluate_complaint로 따로 계산해, 나누면 관할이 낮아질 때 JUR_SPLIT_HINT를 단다. 숫자(소가·인지·관할)는 바꾸지 않는다. 봉인 자산은 그대로다.
# 2026-11-18 1.3.2-g5 제소 기준일 안내 문구를 S2_20 2.7.3-g3(작업실 소제기일 우선)에 맞췄다. 문구만 바뀌었다(로직·자산 불변). 개정 전 원본은 커밋 2554da9b.
# review_notes.md 기본값 줄: '작업실 소제기일에 입력하거나 s2_20_request.json에 넣고 S2_20부터 다시 실행한다'(S2_30은 S2_20이 쓴 request 파일만 읽는다). §4 양식 줄에는 FILING_DATE 항목이 있을 때만 'FILING_DATE는 위 제소 기준일 줄을 따른다'를 붙인다.
# 남은 불일치: 봉인 자산 soga_adapter.py의 FILING_DATE 항목 문구는 request 파일만 든다(재봉인 필요, 이번 범위 밖). Stage_2_S2_30_G4.yml은 다시 만들지 않았다.
@@ -200,7 +203,7 @@
Agent:
name: Stage_2_S2_30_G4_G5
description: "S2_30 G4 — 소가·인지 계산과 소장 병합 초안. 1 prepare_g4, 2 adapt, 3 classify(LLM)+검사, 4 decide(LLM)+검사, 5 calculate, 6 draft_cp(T6, LLM), 7 verify_cp(T7), 8 publish_soga. 자산 Default_Agent/soga/v1, 출력 stage2_runs/s2_20/soga·draft/CP-NN·verify/CP-NN. G5 — 9 G5_load, 10 G5_draft(LLM)+검사·조립, 11 G5_publish: 법원에 낼 소장 완성본 후보 final/CP-NN/소장.md."
version: 1.3.2-g5
version: 1.3.3-g5
Stages:
- name: S2_30_G4_soga_and_complaint
description: "S2_20 T5 plan_cp 뒤를 잇는다. S2_20 실행(prepare.json run_id)의 plan·bundle·draft와 Stage 1 value_facts, 제어 입력 C-1~C-3으로 소가를 계산하고 소장별 청구취지·청구원인을 병합한다. S2_20을 다시 실행하지 않고 공시지가나 검토 응답이 들어올 때마다 이 YAML만 다시 돌린다."
@@ -2898,6 +2901,56 @@ Agent:
return packet, chars, trimmed
def court_review(ad, out, calc):
"""1.3.3 (grouping criteria 11-18 §4.1 items 9-11): court review items from numbers the calculation already made.
Panel and small-claim results become review items; appeal_court() (사물관할규칙 §4①) is wired in and a sole-judge complaint over the
high-court line gets an item; when every claim belongs to one RC, each RC is run through the sealed evaluate_complaint alone to show
when splitting the complaint would lower the court. Items use the schema kind CHECK (name = review code). Numbers are never changed here."""
tier = lambda s: 0 if s == "소액사건" else 1 if str(s).startswith("단독") else 2 if s == "합의부" else None
won = lambda v: "%s원" % format(v, ",") if isinstance(v, int) else "소가 없음"
for cp in ad["complaints"]:
res = out["results"].get(cp["cp_id"])
if not res or not (res["jurisdiction"].get("steps") or []) or res["jurisdiction"]["status"] == "NEEDS_INPUT":
continue
first, soga, date, exc = res["jurisdiction"]["steps"][0], res.get("soga"), res.get("filing_date"), cp.get("exception_kind")
def add(code, text, **kw):
out["review_items"].append(dict({"item_id": "SG-%03d" % (len(out["review_items"]) + 1), "kind": "CHECK", "cp_id": cp["cp_id"],
"cu_id": None, "claim_id": None, "name": code, "value": soga, "status": "NEEDS_REVIEW", "text": text,
"basis": {"rule": "REVIEW", "text": None, "refs": []}, "alternatives": [], "answer_key": None}, **kw))
rcs_of = {ci["claim_id"]: sorted({str(m).split("/")[0] for m in ci.get("members") or []}) for ci in cp["claims"]}
all_rcs = sorted({rc for v in rcs_of.values() for rc in v})
why = "; ".join(res["jurisdiction"].get("notes") or [])
np = any(i.get("name") == "인지법 §2④ 사건" and i.get("value") is True for i in res["jurisdiction"].get("inputs") or [])
if first == "합의부" and np and "§2④" not in why:
why = "; ".join(x for x in (why, "비재산권·산출불능 청구 포함(인지법 §2④)") if x)
shown = ("소가 %s" % won(soga) if isinstance(soga, int) else "소가 없음") + (", %s" % why if why else "")
if first == "합의부":
add("JUR_PANEL", "합의부 사건(%s; 사물관할규칙 §2)%s" % (shown, ". RC %d개를 한 소장으로 묶었다 — 아래 분리 가정 항목이 있으면 함께 본다" % len(all_rcs) if len(all_rcs) > 1 else ""))
elif first == "소액사건":
add("JUR_SMALL_CLAIM", "소액사건(소가 %s; 소액사건심판규칙 §1의2). 소액사건심판법 §5의2 일부청구 금지와 다른 청구를 병합하면 소액이 아니게 되는지 확인" % won(soga))
appeal = calc.appeal_court(soga, "합의부" if first == "합의부" else "단독", exc, date)
res["appeal_court"] = appeal.table()
if tier(first) is not None and tier(first) < 2 and appeal.steps and appeal.steps[0] == "고등법원":
add("JUR_APPEAL_HIGH_COURT", "단독 사건이지만 소가 %s이 2억 원을 넘어 항소심은 고등법원이다(사물관할규칙 §4①)" % won(soga))
if len(all_rcs) < 2 or any(len(v) != 1 for v in rcs_of.values()) or tier(first) is None:
continue
hints, unknown = [], []
for rc in all_rcs:
part = dict(cp, claims=[{k: v for k, v in ci.items() if not k.startswith("_")} for ci in cp["claims"] if rcs_of[ci["claim_id"]] == [rc]])
r = calc.evaluate_complaint(part)
step = (r["jurisdiction"].get("steps") or [None])[0]
if r.get("soga") is None and tier(step) != 2:
unknown.append(rc)
elif tier(step) is not None:
hints.append((rc, r.get("soga"), step))
if hints and min(tier(s) for _, _, s in hints) < tier(first):
add("JUR_SPLIT_HINT", "소장을 RC별로 나누면 %s%s — 지금 묶음은 %s. 나누면 인지·송달료를 따로 내고 관련재판적(민사소송법 §25)을 잃을 수 있다. "
"나누려면 cp_split에 CU 번호로 적고 S2_20부터 다시 실행한다"
% (", ".join("%s %s %s" % (rc, won(v), s) for rc, v, s in hints), "(소가를 정하지 못한 RC: %s)" % ", ".join(unknown) if unknown else "", first),
alternatives=[{"rc": rc, "soga": v, "jurisdiction": s} for rc, v, s in hints])
out["summary"]["review_item_count"] = len(out["review_items"])
def calculate_step(io, cfg, prev_raw):
"""G4 step 5 calculate: classify + decisions + external values + review answers -> soga per CP, prayer amounts, T6 packets"""
binding = binding_for(io, cfg, prev_raw, "Task_S2_30_load_decide", ("FANOUT_READY",))
@@ -2932,6 +2985,7 @@ Agent:
bad = dropped + bad
adapter.apply_decisions(ad, ok, bad, src)
out = adapter.calculate(ad, assets["calc"])
court_review(ad, out, assets["calc"])
cu_of = {c["claim_id"]: c["cu_id"] for cp in ad["complaints"] for c in cp["claims"]}
owner = lambda d: d.get("_resp_cu") or cu_of.get(d.get("claim_id"))
for e in entries:
@@ -0,0 +1,153 @@
# 소장 구성 HITL 선택 옵션 구상 (2026-11-19)
- 상태: 설계안. YAML과 코드는 바꾸지 않았다.
- 선행 문서: [소장작성_개별청구권묶음기준_11_18.md](소장작성_개별청구권묶음기준_11_18.md) §4.1(변호사가 `cp_split`으로 묶으면 S2_20부터 재실행).
- 검증: §1은 Fable 5.2 medium 독립 검증 1회를 반영했다. §2는 Fable 5.2 medium 독립 설계자 2명의 안을 main agent가 비교해 정했다.
- 줄 번호: `S20` = `Stage_2_S2_20_G1_G2_G3.yml`(2.7.3-g3), `S30` = `Stage_2_S2_30_G4_G5.yml`(1.3.2-g5).
## 0. 질문
1. 변호사가 Liti-agent와 다르게 소장 구성을 묶거나 나눌 때, S2_20을 다시 실행하지 않고 소장 작성만 달리할 수 있는가?
2. S2_30 결과를 화면에 보여 준 뒤, 변호사에게 어떤 선택 옵션을 주어야 가장 깔끔하고 최소한의 작업으로 진행되는가?
## 1. S2_20 재실행 없이 소장 구성만 바꾸는 경로
### 1.1 지금 상태
- `cp_split`은 S2_20 T0 `group_complaints`의 한 곳(S20:1426-1432)에서만 읽는다. S2_30에는 읽는 곳이 없다.
- T0 `prepare`는 출력 폴더 전체를 지우고(`io.reset(out)`, S20:1476) 새 run_id를 만든다(S20:1477). 이때 CU 초안의 LLM 작성·검사·보수가 모두 다시 돈다. `soga/`와 `final/`도 같은 폴더 아래에 있어 함께 지워진다.
- CU 초안 프롬프트는 "이 CU 하나만 쓴다. 다른 CU와의 병합 문구 … 는 쓰지 않는다"(S20:1809)라고 정한다. block 3의 `cp` 정보(S20:1613)는 키로 들어 있을 뿐, 이를 쓰라는 지시는 없다. 그러므로 소장 묶음은 CU 작성과 따로 떼어 낼 수 있다.
### 1.2 방법: S2_30 `prepare_g4` 덮어쓰기(overlay)
- `prepare_g4`는 이미 `s2_20_request.json`을 읽고 그 해시를 남긴다(S30:583-587).
- `cp_split`이 있으면 T0과 같은 규칙으로 `case_bundle.complaints`를 다시 묶는다.
- 아래 세 가지를 서로 맞게 새로 만든다. S2_30은 세 곳을 모두 읽는다(S30:541, 550, 573, 2878).
- 소장 목록(`complaints` 지도)
- `plan/CP-NN.json`
- `bundle/complaints/CP-NN.json`(`joinder_candidates`는 T6 프롬프트와 verify_cp가 쓴다. 없으면 `INPUT_MISSING`이 된다. S30:3344, 3774, 4318)
- 새 파일은 G4 실행마다 비우는 `soga/work/`에 쓴다. S2_20 산출물과 run_id는 건드리지 않는다. S2_30은 run_id가 다른 plan을 읽지 않는다(S30:550).
- 이 방법을 쓰면 S2_20 LLM 단계는 다시 돌지 않는다. 소가·관할·인지와 소장별 병합 문안은 S2_30만 다시 계산한다.
- Liti-agent가 묶은 원래 구성이 남으므로, 변호사가 무엇을 바꿨는지 비교해 검토 노트에 적을 수 있다.
- `cp_split`을 지우면 원래 상태로 돌아간다.
- `cp_split`이 없으면 덮어쓰기도 없고, 동작은 지금과 같다.
- "S2_20 T5만 다시 돌린다"는 안은 버렸다. S2_20을 실행하면 첫 task인 T0이 폴더를 지우기 때문이다.
### 1.3 필요한 장치
1. **멈춤:** 고유필수적 공동소송(민사소송법 §67)을 쪼개는 묶음만 멈춘다. 지금 데이터에는 고유필수와 유사필수를 가르는 표지가 없다(`NECESSARY_COPARTY`, `coparty_form`뿐이다, S20:1146).
2. **검토 노트:**
- 예비적·선택적 공동소송(§70)이나 `alt_of` 짝을 다른 소장으로 나누면 노트를 남긴다. §70은 병합한 뒤의 분리를 막을 뿐, 처음부터 따로 내는 것을 막지 않는다. 어댑터에는 이미 `K-ALT-BROKEN` REVIEW가 있다(soga_adapter.py:760-763).
- 소장을 합치면 §65 요건과 같은 소송절차인지를 묻는 노트를 남긴다(지금 `COPARTY_BASIS`, S20:5374).
3. **소장 번호:** CP 번호는 정렬 순서로 정해진다(S20:1433). 그래서 묶음이 바뀌면 cp_id에 매인 변호사 입력(C-2 `exception_kind`, C-3 답변)이 엉뚱한 소장에 붙을 수 있다. §2.4의 번호 규칙으로 막는다.
4. **HOLD CU:** PASS CU만 옮기면 안 된다. HOLD CU도 자리표시자와 함께 옮긴다(S20:5285-5316; S30:564-567).
5. **결과 노트:**
- §27에 따라 소가는 소장마다 합산한다. 그래서 합의부·단독·소액 구분과 인지액이 바뀐다.
- 소장을 나누면 §25 관련재판적을 잃을 수 있다.
- 만족 묶음이 갈라지면 중첩 책임 문구를 손봐야 한다(S30:3794-3805).
이 밖에 검증에서 확인한 사항은 다음과 같다.
- "CU가 두 소장에 들어간다"는 경우는 이미 `CP_SPLIT_INVALID`로 검사한다(S20:1429).
- "어느 소장에도 없는 CU"는 생기지 않는다. `cp_split`에 이름이 없는 CU는 자동 묶음에 남는다(S20:1431).
- "문제 CU만 다시 쓴다"는 약속은 뺐다. 대신 새 묶음 밖의 피고를 언급하는 초안을 표시만 한다.
- S2_30의 LLM 단계는 다시 돈다. cp_id가 바뀐 소장은 지난 결정을 다시 쓰지 못한다. cp_id가 `input_sha` 안에 있기 때문이다(S30:2121-2123).
## 2. HITL 선택 옵션 구상
### 2.1 결론
변호사에게는 소장 표 위에서 세 동작만 준다.
- 청구(CU) 옮기기: 다른 소장이나 새 소장으로 옮긴다.
- 소장 합치기
- 에이전트안으로 되돌리기
결과는 지금 있는 `cp_split` 키에 소장 구성 전체로 저장한다. 다시 돌리는 것은 S2_30뿐이다. 독립 설계자 두 명은 서로의 안을 보지 않았는데도 중심 결론이 같았다.
### 2.2 화면에 보여 줄 것
S2_30이 끝나면 코드가 `grouping_view.json`을 만든다. 화면은 이 파일로 표를 그리고, 즉시 검사에도 이 파일을 쓴다.
```json
{"s2_20_run_id": "…",
"complaints": {"CP-01": {"cus": ["CU-01", "CU-03"], "plaintiffs": ["…"], "defendants": ["…"],
"soga": 152000000, "court": "…합의부", "stamp": 663000, "review_codes": ["…"]}},
"cus": {"CU-01": {"title": "…", "defendants": ["…"], "status": "MERGED|HOLD"}},
"links": [{"a": "CU-01", "b": "CU-03", "reason": "SATISFACTION_GROUP", "lock": "WARN", "note": "§70 …"},
{"a": "CU-03", "b": "CU-05", "reason": "SHARED_OBJECT", "lock": "FREE"}]}
```
| 등급 | 대상 | 화면 동작 |
|---|---|---|
| `HARD` | 고유필수적 공동소송(§67). 표지가 생기기 전까지는 비어 있다. | 그 연결을 끊는 옮기기를 막는다. |
| `WARN` | §70 공동소송, `alt_of` 짝, 만족 묶음, RC 사이 묶음, `DECLARATORY_OF` | 노트를 보여 주고 한 번 확인받는다. |
| `FREE` | 같은 목적물을 공유한다는 이유만으로 묶인 경우 | 막지 않는다. |
- 합치기를 하면 언제나 §65 노트를 보여 준다.
- 무엇을 바꾸든 "소가·관할·인지를 다시 계산한다"는 안내를 보여 준다.
- CU별 소가를 더해 미리 합계를 보여 주지 않는다. §27의 합산·흡수 규칙 때문에 단순 합과 다를 수 있다.
### 2.3 저장 형식
화면은 동작들을 완성된 소장 구성 하나로 바꿔 `stage2_control/s2_20_request.json`에 쓴다.
```json
{"cp_split": [["CU-01", "CU-03"], ["CU-05"], ["CU-02", "CU-04"]],
"cp_split_note": "피고 丙 분리 (선택)"}
```
이 형식을 택한 이유는 다음과 같다.
- **CU 번호만 적는다.** CP 번호는 결과에서 나온다.
- **모든 CU를 빠짐없이 적는다.** 그래서 같은 파일은 언제나 같은 결과를 내고, 처음 묶음과 상관없이 결과가 같다.
- **되돌리기는 키를 지우면 된다.** 소장 구성이 에이전트안과 같아지면 화면이 키를 지운다.
- **형식이 바뀌지 않는다.** T0(S20:1426-1432)이 이미 받는 형식이다. 나중에 S2_20을 다시 돌려도 같은 묶음이 나온다.
- **다른 키를 지우지 않는다.** T0은 이 파일을 `dict(request, …)`로 다시 쓰므로 다른 키를 보존한다(S20:1484). 화면도 파일 전체를 덮어쓰지 말고 키만 합쳐 써야 한다.
- **백엔드 변경이 없다.** 실행 요청의 `env`로는 지금 `filing_date`만 넘긴다(SKILL.md §4.1). 그래서 제어 파일이 통로다.
### 2.4 검사와 번호
검사는 두 겹이다.
1. **화면(안내용, 즉시):** 모든 CU가 정확히 한 번 나오는지 본다. `HARD` 연결이 끊기지 않았는지 본다.
2. **`prepare_g4`(최종 판정, LLM 호출 전 첫 코드 task):**
- 모르는 CU 번호, 중복 번호, 빈 목록이 있으면 `CP_SPLIT_INVALID`로 멈추고 binding에 기록한다.
- `HARD` 연결을 끊으면 멈춘다.
- `WARN` 연결을 끊거나 소장을 합치면 검토 노트를 남긴다. §27 소가·관할·인지 변화와 §25 관련재판적 상실도 노트로 적는다.
번호는 다음 규칙으로 정한다.
- **번호 유지:** CU 구성이 그대로인 소장만 S2_20의 CP 번호를 유지한다.
- **새 번호:** 바뀌거나 새로 생긴 소장은 가장 큰 번호 다음부터 받는다.
- **변호사 입력 보호:** 사라진 소장에 매인 C-2·C-3 입력은 적용하지 않고 `CP_CONTROL_STALE` 노트로 남긴다.
- **비용:** 번호를 유지한 소장은 S2_30의 지난 결정(`decision/previous.json`)을 다시 쓴다. 그래서 LLM 비용은 바뀐 소장에서만 생긴다.
### 2.5 비교에서 고르거나 버린 것
| 항목 | 처리 | 이유 |
|---|---|---|
| 설계자 1의 번호 규칙(구성이 그대로인 소장만 번호 유지) | 채택 | C-2·C-3 입력을 가장 안전하게 지킨다. |
| 설계자 2의 `CP_CONTROL_STALE` 노트 | 채택 | 사라진 소장의 입력이 다른 소장에 붙지 않는다. |
| 설계자 2의 `complaints_auto`(T0이 에이전트 원안을 따로 저장) | 보류 | 소장 구성을 빠짐없이 적으므로 처음 묶음은 결과에 영향이 없다. S2_20을 `cp_split`과 함께 돌린 뒤 "에이전트 원안 보기"가 필요할 때 더한다. |
| 설계자 1의 `cp_split_meta`(`based_on_run_id`, `acknowledged`) | 선택 사항 | 없어도 동작한다. 확인 기록이 필요할 때 더한다. |
| 설계자 2의 "새 소장은 T5의 LLM 계획을 건너뛴다"는 위험 | 사실 오류 | T5 `plan_cp`는 LLM을 쓰지 않는 코드 task다. |
| 연결 하나씩 끊기 | 버림 | union-find에서는 다른 경로로 이어져 있으면 아무것도 바뀌지 않는다. 연결이 없는 CU끼리 합치는 동작도 표현할 수 없다. |
| 에이전트가 대안을 미리 계산 | 버림 | 대안마다 S2_30 LLM 실행이 필요하고, 대부분은 선택되지 않는다. |
| 자유 입력 CU 목록을 주 화면으로 | 버림 | 오타가 실행할 때에야 드러나고, 잠금을 보여 줄 수 없다. 화면이 없을 때 쓰는 대체 수단으로만 둔다. |
| 새 제어 파일이나 새 키 | 버림 | S2_20과 S2_30이 서로 다른 기준을 갖게 된다. |
| 동작 기록 저장 | 버림 | 순서에 따라 결과가 달라지고, 다시 재생하는 장치가 필요하다. |
| `env`로 묶음 전달 | 버림 | 백엔드를 바꿔야 하고, 값이 남지 않는다. |
## 3. 남은 과제와 위험
- T0의 번호 규칙(`sorted(lists)`)이 §2.4의 안정 번호 규칙과 다르다. T0에도 같은 규칙을 옮기거나, 차이를 받아들여야 한다.
- §67 잠금은 고유필수 표지가 생기기 전까지 실제로 아무것도 막지 않는다.
- 지금의 `cp_split` 경로는 합친 소장이 법적으로 병합될 수 있는지 검사하지 않는다. 덮어쓰기 단계의 노트가 유일한 장치다.
- 위쪽 단계에서 CU 번호가 바뀌면 옛 `cp_split`은 멈춘다. 이것은 맞는 동작이지만, 무엇이 문제인지 알려 주는 메시지가 필요하다.
- 백엔드가 `grouping_view.json`을 변호사에게 보여 주고 제어 파일을 쓰는 화면 기능은 확인하지 않았다.
- 구현 범위:
- `prepare_g4` 덮어쓰기(약 15행과 번호 규칙)
- C-2·C-3 stale 처리
- `grouping_view.json` 발행
- S2_30 YAML은 `gen_yaml.py --g5`로만 다시 생성한다.
@@ -2,6 +2,8 @@
작성: main agent (Opus 5.5). 검증: 독립 검증자 Fable 5.2 medium 2회. 1회차 지적을 반영해 v1을 쓰고, 2회차 지적을 반영해 이 문서를 썼다. 프로젝트 코드는 고치지 않았다.
**적용 상태(2026-11-19):** §4.1 1~11번을 S2_20 2.7.4-g3(T0·T4z·T5)과 S2_30 1.3.3-g5(calculate의 court_review)에 적용했다(Fable 5.2 medium 독립 검증 2회). 12번(변호사 `cp_split` 경로)은 코드 변경이 없다. 아래 줄 번호와 "코드는 고치지 않았다"는 서술은 2.7.3-g3 기준이다.
약칭과 범위:
- S00 = `Stage_2_S2_00.yml`, S10 = `Stage_2_S2_10.yml`, S20 = `Stage_2_S2_20_G1_G2_G3.yml`(2.7.3-g3)
- calc = `assets_for_stage_2/soga/v1/tools/soga_calc.py`
@@ -4,6 +4,27 @@
## How to Write MEMORY.md
### 2026-11-19 — 소장 묶음 최소안(§4.1 1~11번) 적용: S2_20 2.7.4-g3 + S2_30 1.3.3-g5(Fable 5.2 medium 독립 검증 2회 → 재개정 2회; 미커밋·미배포·온라인 미실행)
<!-- cp_grouping_minimal_apply_20261119 -->
기준 문서 [소장작성_개별청구권묶음기준_11_18.md](Default_Agent/Stage_2_Clean/agent_scripts/소장작성_개별청구권묶음기준_11_18.md) §4.1. 보존본 `Stage_2_S2_20_G1_G2_G3_11_19_pre_group.yml`·`Stage_2_S2_30_G4_G5_11_19_pre_group.yml`, 생성기 원본은 커밋 027a531e. S2_10·봉인 자산 무변경.
- **S2_20 T0 `group_complaints`**: 같은 목적물만으로는 잇지 않음 → `JOINDER_LATTER_CANDIDATE`(§65 후문 후보; 피고 같으면 보통재판적 §2·§3, 다르면 §25② 미적용·§20 예시). cross 미판정(`cross_status` SKIPPED_OVERSIZE·FAILED 또는 `CROSS_NOT_REVIEWED`)이면 종전처럼 잇고 `OBJECT_LINK_CROSS_NOT_REVIEWED`. NONE 라벨 무시. `SAME_PAIR`(원고 party_id 겹침 + 같은 피고, CU 있는 RC만). 여러 RC holds가 갈리면 `CROSS_HOLD_SEPARATED`. 피고 다른 CONCURRENT·ALTERNATIVE 라벨은 잇고 `LABEL_JOIN_REVIEW`(§2 표). review는 cp_split 뒤 최종 후보로 판정, RC 묶음별 1건, 장부 행은 RC마다. CP 후보에 `link_reasons`. 새 네 코드는 `RUN_ITEM_CODES`·T4z GRADE3.
- **S2_20 T5**: 병합 CU 초안 LC-PERIOD ISSUE·UNKNOWN → plan review `LC_PERIOD_FLAG`(verify_cp W8이 옮김). HOLD CU는 대상 아님.
- **S2_30 `court_review`(t_calculate.py, gen_yaml로만 생성)**: 스키마 kind `CHECK`·name=코드. `JUR_PANEL`(인지법 §2④ 사유 표시), `JUR_SMALL_CLAIM`, 봉인 `appeal_court` 호출 → `JUR_APPEAL_HIGH_COURT`(단독 + 2억 초과) + result의 `appeal_court`, 청구마다 한 RC인 다중 RC 소장은 RC별 봉인 `evaluate_complaint`로 `JUR_SPLIT_HINT`. 숫자 불변.
- **검증에서 바로잡은 것**: RC 소계 근사(MEANS·econ_partial 무시로 관할 오판) → 봉인 계산기 호출; review를 cp_split 전에 판정; 봉인 스키마 위반(kind enum·additionalProperties); §65 후문 문구("같은 원인"은 전문); 같은 피고에 §25① 오인용; 목적물마다 중복 review; 0청구 RC의 SAME_PAIR 다리; cross 미판정 경로 둘째 목적물 누락.
- **시험**: 실측 사본(11-11, CU 18) 새 묶음 = 종전 CP 4개, 합성 17건, T5 1건, replay A·B·C 숫자 불변·스키마 적합, 골든 516/516, 두 YAML code task ast 통과(9·13).
- **함정**: gen_yaml은 agent_scripts에서 실행(생성기 폴더에서 돌리면 그 폴더에 새 파일이 생김).
### 2026-11-19 — 소장 구성 HITL 선택 옵션 구상: S2_20 재실행 없이 S2_30만 다시 돌림(Fable 5.2 medium 검증 1회 + 독립 설계자 2명 비교; 코드 무변경)
<!-- cp_hitl_regroup_options_20261119 -->
[소장구성_HITL선택옵션_구상_11_19.md](Default_Agent/Stage_2_Clean/agent_scripts/소장구성_HITL선택옵션_구상_11_19.md). 11-18 문서 §4.1의 "변호사 `cp_split` → S2_20부터 재실행"을 대체하는 안.
- **경로**: S2_30 `prepare_g4`(S30:583이 이미 request를 읽음)에 덮어쓰기. `cp_split`으로 `case_bundle.complaints`를 다시 묶고 소장 목록·`plan/CP-NN.json`·`bundle/complaints/CP-NN.json` 셋을 `soga/work/`에 함께 쓴다(S30:541·550·573·2878이 셋 다 읽음). S2_20 run_id·산출물은 그대로. 버린 안: "T5만 재실행"(S2_20 첫 task가 `io.reset`, S20:1476).
- **HITL 옵션**: 소장 표 위 세 동작(CU 옮기기·소장 합치기·에이전트안 되돌리기). 화면은 `grouping_view.json`(소장별 법원·소가·인지·노트, 연결 등급 HARD=§67 / WARN=§70·alt_of·SG·cross·DECLARATORY_OF / FREE=공유 목적물). 저장은 기존 `cp_split`에 CU 번호로 전체 구성. 되돌리기 = 키 삭제. 백엔드 변경 없음(env는 `filing_date`뿐).
- **검사·번호**: 화면 검사는 안내용이고, 최종 판정은 `prepare_g4`가 LLM 전에 한다(`CP_SPLIT_INVALID`·HARD 끊기 → 멈춤, WARN·합치기·§27·§25 → 노트). 구성이 그대로인 소장만 CP 번호 유지, 나머지는 max+1. 사라진 소장의 C-2·C-3 입력 → `CP_CONTROL_STALE`. HOLD CU도 함께 옮김.
- **검증에서 바로잡은 것**: "두 소장 중복"은 이미 검사(S20:1429), "어느 소장에도 없음"은 불가(S20:1431). §70은 병합 뒤 분리만 막으므로 멈춤이 아니라 노트. "문제 CU만 재작성"은 빼고 표시만(프롬프트가 `cp` 사용을 지시하지 않음, S20:1809). 설계자 2의 "T5 LLM 계획 건너뜀"은 오류(T5는 LLM 없음).
- **남은 과제**: T0 번호 규칙(`sorted`)과 맞추기, 고유/유사필수 표지(없으면 §67 잠금은 아무것도 막지 않음), 화면 기능 미확인. 구현·커밋하지 않았다.
### 2026-11-18 — 소장 묶음 기준(CU→CP)을 코드만으로 수행할 수 있는가: 설계 판단 문서 작성(Fable 5.2 medium 독립 검증 2회; 코드 무변경)
<!-- cp_grouping_code_feasibility_20261118 -->