feat(appendix): apply decision-record fixes for 4 rule docs and add C12 record_ids check

- appx_clean.py: accept numbered-heading ID definitions (R_DEF_NUM), add
  record_ids exemption with C12 guard, OLD_WORDING_ROW flag
- Apply revised decisions for 4 docs (old ones kept as dec_outdated), rebuild
  outputs, update _요약.md rows
- _new folder: 137-doc rebuild, item probe, 판단기록_수정.md
- Sync prompt §5-1 ID regex and appx_brief.md b2 with script R_ID
- MEMORY.md entries for 10-27 work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 11:40:15 +09:00
co-authored by Claude Opus 5.5
parent 6cd7dcddb0
commit 4bee20a5eb
744 changed files with 413474 additions and 1 deletions
@@ -0,0 +1,421 @@
"""부록 정리 프롬프트(최적색인방식전_청구취지규칙문서_정리_프롬프트_Opus.md)의 결정적 단계.
python3 appx_clean.py inv ROOT KEY WORK -> WORK/KEY.inv.json (목록·기본 판정·참조·ID)
python3 appx_clean.py build ROOT KEY WORK DEC.json [OUTDIR] -> 출력 파일·기록 json·검사 결과(C1~C12)
OUTDIR(ROOT 아래 폴더 이름)을 주면 출력은 그 폴더에, 기록 json은 그 아래 _기록에 쓴다. 이름이 _로 시작하는 항목은 C1이 보지 않는다.
DEC.json (LLM 판단):
{
"sections": {"<머리글 줄 그대로>": {"action": "KEEP_SECTION|KEEP_ITEMS|KEEP_UNSURE|DISCARD", "why": "...",
"items": ["항목 첫머리의 고유 부분 문자열", ...]}},
"pre_b": "KEEP|DISCARD",
"refs": [{"match": "참조 text+context 안의 부분 문자열", "from": "body|A|B|*",
"kind": "APPLY|RECORD|RAW_DANGLING|NOT_REF", "target": "<머리글 줄>|## 부록 B|null"}],
"patches": [{"old": "조립본에 정확히 한 번 나오는 문구", "new": "바꿀 문구", "why": "근거(해결책 파일·항목)", "count": 기대 횟수(선택, 기본 1)}] (선택)
"record_ids": {"X-2": "정의 행이 옛 지시 문구를 인용하는 이력 행이라 남기지 않음"} (선택)
}
patches는 미결 쟁점 해결책처럼 사람이 확정한 내용 수정과, 프롬프트 §4.7의 기준일 덧붙임(버린 절에만 있던 실행·법률 검토 기준일을 부록 A에 되살림)만 담는다. C2·C7은 교체 전 조립본으로, 나머지 검사는 교체 후 출력으로 본다.
적지 않은 절은 기본 판정을 따른다(①·② 기준 KEEP_SECTION, 나머지 DISCARD). DISCARD 절은 가리켜졌으면 OMIT, 아니면 DROP.
번호 참조(B.n)는 머리글이 '### B.n '으로 시작하는 절이 하나뿐이면 자동으로 그 절에 닿고, 종류는 refs 규칙이 없으면 RECORD로 둔다.
KEEP_ITEMS 절은 items와 별도로, 머리글 칸이 '잔여'로 시작하는 표에서 그 칸이 '없음'·'—'·'-'·빈칸이 아닌 행을 자동으로 모두 남긴다(C11이 확인).
머리글을 남긴 KEEP_ITEMS 절은 OMIT_LINE 대신 ITEMS_LINES 가운데 하나를 쓴다: 잔여 행만 남으면 "res", items로 고른 항목만 남으면 "ref", 둘 다면 "mix".
ID 정의는 줄머리 외에 줄 중간의 정의 표지도 인정한다: "(IMP-04, 원문 217행)", "LC-05:", "효과: RULE-09 (피고)", 머리글 끝 "(`RULE-G-06`)",
절 번호가 앞에 붙은 머리글 "### 4.2 RULE-RES-03 — …".
record_ids의 ID는 C5가 정의를 요구하지 않는다. 대신 C12가 출력에서 그 ID가 나오는 모든 자리 바로 앞(40자 안)에 부록 B 참조가 있는지 본다.
items로 남긴 표 행의 표 머리글에 '원문 … 문구' 칸이 있으면 OLD_WORDING_ROW 플래그로 알린다(옛 지시 문구 인용 가능성; 사람이 확인).
"""
import hashlib, json, os, re, sys, unicodedata
OMIT_LINE = "(제작 관리 기록 — 이 판에서 생략)"
ITEMS_LINES = {"res": "(본문이 연결한 미결 쟁점 행만 남겼다 — 나머지 제작 기록은 이 판에서 생략)",
"ref": "(본문이 가리킨 항목만 남겼다 — 나머지 제작 기록은 이 판에서 생략)",
"mix": "(본문이 가리킨 항목과 미결 쟁점 행만 남겼다 — 나머지 제작 기록은 이 판에서 생략)"}
FIXED_LINES = {OMIT_LINE, *ITEMS_LINES.values()}
NO_RESIDUE = ("", "없음", "—", "-", "–")
R_NUM = re.compile(r"(?:부록\s*|§)?(?<![\w.\-])B\.?(\d+(?:\.\d+)*)")
R_NAME_B = re.compile(r"부록\s*B(?![.\d])[^\n]{0,40}")
R_NAME_A = re.compile(r"부록\s*A(?:\.\d+)*")
R_ID = re.compile(r"(?<![\w-])[A-Z][A-Za-z]*(?:-[A-Za-z0-9]+)+(?![A-Za-z0-9_-])") # 뒤에 붙은 한글 조사("O-21의")는 허용
R_HEAD = re.compile(r"(?m)^(#{3,6}) .*$")
R_DEF = re.compile(r"^(?:#{1,6}\s+|[-*]\s+|\|\s*|\d+\.\s+)?(?:\*\*)?`?([A-Z][A-Za-z]*(?:-[A-Za-z0-9]+)+)")
_I = r"`?([A-Z][A-Za-z]*(?:-[A-Za-z0-9]+)+)`?"
R_DEF_MID = re.compile(r"\(%s,\s*원문|(?:^|[\s(])%s\s*[::]|[::]\**\s*%s\s+\(" % (_I, _I, _I))
R_DEF_HEAD = re.compile(r"^#{1,6} .*\(%s\)\s*$" % _I)
R_DEF_NUM = re.compile(r"^#{1,6}\s+(?:[A-Z]\.?)?\d+(?:\.\d+)*\.?\s+(?:\*\*)?%s" % _I) # "### 4.2 RULE-RES-03 — …"
R_OLD_COL = re.compile(r"^원문.*문구")
def sha(s):
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def find_raw(root, key):
for f in os.listdir(os.path.join(root, "raw")):
n = unicodedata.normalize("NFC", f)
if n in ("청구취지작성규칙_%s_beta_0.8.md" % key, "청구취지작성규칙_%s_beta_0.8_re.md" % key):
return os.path.join(root, "raw", f), n
raise SystemExit("raw not found: " + key)
def clean_line(ln):
new = re.sub(r'<a id="[^"]*"></a> ?', "", ln)
new = re.sub(r"\[([^\]\n]*)\]\(#[^)\n]*\)", r"\1", new)
new = re.sub(r"\[([^\]\n]*)\]\(https?://[^)\n]*\)", r"\1", new)
new = re.sub(r"(?:<br>|[ \t])*https?://[^\s|<)]+", "", new)
if new.startswith("|") and "http" in ln:
oc, nc = ln.split("|"), new.split("|")
if len(oc) == len(nc):
new = "|".join(" URL 삭제 " if (not c.strip() and "http" in oc[k]) else c for k, c in enumerate(nc))
return new
def clean(seg):
res = []
for ln in seg.split("\n"):
new = clean_line(ln)
if ln.strip() and not new.strip():
continue
res.append(new)
return re.sub(r"\n{3,}", "\n\n", "\n".join(res)).strip("\n")
def defs(s):
d = set()
for line in s.split("\n"):
line = re.sub(r'<a id="[^"]*"></a>\s*', "", line).strip()
m = R_DEF.match(line)
if m:
d.add(m.group(1))
d.update(g for m in R_DEF_MID.finditer(line) for g in m.groups() if g)
for R in (R_DEF_HEAD, R_DEF_NUM):
m = R.match(line)
if m:
d.add(m.group(1))
return d
def ids(s):
return {m.group() for m in R_ID.finditer(s) if re.search(r"\d", m.group())}
def load(root, key):
rp, rn = find_raw(root, key)
t = open(rp, encoding="utf-8").read()
ref = open(os.path.join(root, "청구취지규칙문서_사건종류별", "청구취지작성규칙_%s.md" % key), encoding="utf-8").read()
ia, ib = t.find("\n## 부록 A") + 1, t.find("\n## 부록 B") + 1
assert 0 < ia < ib, "appendix boundary"
assert re.sub(r'<a id="[^"]*"></a>', "", t[:ia]) == ref, "body != designated set"
B = t[ib:]
hs = [(m.start(), len(m.group(1)), m.group()) for m in R_HEAD.finditer(B)]
chunks = [] # 머리글부터 다음 머리글(단계 무관) 앞까지
for k, (s, lv, h) in enumerate(hs):
e = hs[k + 1][0] if k + 1 < len(hs) else len(B)
end_sub = next((s2 for s2, lv2, _ in hs[k + 1:] if lv2 <= lv), len(B))
parent = next((hs[q][2] for q in range(k - 1, -1, -1) if hs[q][1] < lv), None)
chunks.append({"heading": h, "level": lv, "start": ib + s, "end": ib + e, "sub_end": ib + end_sub, "parent": parent})
for c in chunks:
txt = t[c["start"]:c["sub_end"]]
ls = txt.split("\n")
hdrs = [re.sub(r'<a id="[^"]*"></a>', "", ls[i]) for i in range(len(ls) - 1)
if ls[i].lstrip().startswith("|") and re.match(r"\s*\|[\s:|-]+\|\s*$", ls[i + 1]) and "-" in ls[i + 1]]
has_tbl = any(any(re.search(r"LEAF|Leaf|말단", x) for x in h.split("|")) and any(re.search(r"FORM|Form|문형", x) for x in h.split("|")) for h in hdrs)
c["default"] = "KEEP_SECTION" if (re.search(r"경로.{0,10}문형", c["heading"]) or has_tbl) else "DISCARD"
pre_b = t[ib:ib + hs[0][0]] if hs else B
return t, rn, ref, ia, ib, chunks, pre_b
def find_refs(t, spans):
out = []
for name, s0, e0 in spans:
seg = t[s0:e0] if isinstance(t, str) else t[name][s0:e0]
for R, kind in ((R_NUM, "num"), (R_NAME_B, "nameB"), (R_NAME_A, "nameA")):
for m in R.finditer(seg):
if kind != "num" and re.match(r"부록\s*[AB]\. ", seg[m.start():m.start() + 6]) and seg[max(0, m.start() - 3):m.start()].endswith("## "):
continue # 부록 머리글 자체
ctx = seg[max(0, m.start() - 80):m.end() + 40].replace("\n", " ")
out.append({"text": m.group(), "from": name, "at": s0 + m.start(), "context": ctx, "kind_re": kind,
"num": m.group(1) if kind == "num" else None})
return out
def heading_for_num(chunks, num):
hits = [c["heading"] for c in chunks if re.match(r"#{3,6} (?:부록\s*)?B\.?%s(?![\d.]*\d)(?:[ .]|$)" % re.escape(num), c["heading"])]
return hits[0] if len(hits) == 1 else None
def resolve(refs, chunks, rules):
res = []
for r in refs:
rule = next((x for x in rules if x["match"] in (r["text"] + " " + r["context"]) and x.get("from", "*") in ("*", r["from"])), None)
if r["kind_re"] == "nameA":
res.append(dict(r, kind="APPLY", target="## 부록 A")); continue
if rule:
res.append(dict(r, kind=rule["kind"], target=rule.get("target"))); continue
if r["kind_re"] == "num":
h = heading_for_num(chunks, r["num"])
res.append(dict(r, kind="RECORD" if h else "UNRESOLVED", target=h)); continue
res.append(dict(r, kind="UNRESOLVED", target=None))
return res
def cmd_inv(root, key, work):
t, rn, ref, ia, ib, chunks, pre_b = load(root, key)
keep = [c for c in chunks if c["default"] == "KEEP_SECTION"]
spans = [("body", 0, ia), ("A", ia, ib)] + [("B", c["start"], c["sub_end"]) for c in keep]
refs = resolve(find_refs(t, spans), chunks, [])
kept_txt = t[:ib] + "".join(t[c["start"]:c["sub_end"]] for c in keep)
kd = defs(kept_txt)
disc = [c for c in chunks if not any(k["start"] <= c["start"] < k["sub_end"] for k in keep)]
only = []
for x in sorted(ids(kept_txt) - kd):
for c in disc:
seg = t[c["start"]:c["end"]]
for line in seg.split("\n"):
m = R_DEF.match(re.sub(r'<a id="[^"]*"></a>\s*', "", line).strip())
if m and m.group(1) == x:
only.append({"id": x, "section": c["heading"], "line": line[:400]}); break
else:
continue
break
body = t[:ia]
sel = "\n".join(l for l in body.split("\n") if "선택 기준" in l)
kb = "".join(t[c["start"]:c["sub_end"]] for c in keep)
lwf = sorted({m.group() for m in re.finditer(r"LEAF-[A-Za-z0-9-]*\d[A-Za-z0-9-]*", body)} - set(re.findall(r"LEAF-[A-Za-z0-9-]+", kb + sel)))
inv = {"key": key, "raw": rn, "chars": len(t), "body_end": ia, "appendix_a": [ia, ib],
"pre_b": {"chars": len(pre_b), "text": pre_b[:600]},
"b_sections": [dict({k: c[k] for k in ("heading", "level", "parent", "start", "end", "sub_end", "default")},
chars=c["end"] - c["start"], head300=t[c["start"]:c["start"] + 300]) for c in chunks],
"refs": [{k: r[k] for k in ("text", "from", "at", "context", "kind", "target")} for r in refs],
"ids_only_in_discarded": only, "leaf_without_form_default": lwf}
json.dump(inv, open(os.path.join(work, key + ".inv.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(json.dumps({"key": key, "sections": len(chunks), "default_keep": [c["heading"] for c in keep],
"refs": len(refs), "unresolved": sum(r["kind"] == "UNRESOLVED" for r in refs),
"ids_only_in_discarded": [o["id"] for o in only], "lwf": lwf}, ensure_ascii=False))
def item_block(seg, start_sub):
lines = seg.split("\n")
p = seg.index(start_sub)
li = seg[:p].count("\n")
ln = lines[li]
if ln.lstrip().startswith("|"):
a = li
while a > 0 and lines[a - 1].lstrip().startswith("|"):
a -= 1
return ("row", (a, a + 1), li)
if re.match(r"\s*(?:[-*]|\d+\.)\s", ln):
b = li + 1
while b < len(lines) and lines[b].startswith((" ", "\t")) and lines[b].strip():
b += 1
return ("list", li, b)
a = li
while a > 0 and lines[a - 1].strip():
a -= 1
b = li
while b < len(lines) and lines[b].strip():
b += 1
return ("para", a, b)
def residue_rows(seg):
"""'잔여' 칸이 있는 표에서 잔여가 남은 행의 줄 번호와 그 표의 머리글·구분 줄 번호."""
lines, picks, rows = seg.split("\n"), [], []
for i in range(len(lines) - 1):
if not (lines[i].lstrip().startswith("|") and re.match(r"\s*\|[\s:|-]+\|\s*$", lines[i + 1])):
continue
cells = [x.strip() for x in lines[i].strip().strip("|").split("|")]
col = next((n for n, x in enumerate(cells) if x.startswith("잔여")), None)
if col is None:
continue
j = i + 2
while j < len(lines) and lines[j].lstrip().startswith("|"):
cs = [x.strip() for x in lines[j].strip().strip("|").split("|")]
if col < len(cs) and cs[col] not in NO_RESIDUE:
rows.append(j)
j += 1
if any(i + 2 <= r < j for r in rows):
picks += [i, i + 1]
return picks, rows
def assemble(t, ref, ia, ib, chunks, pre_b, dec, referenced):
secs = dec.get("sections", {})
act = {}
for c in chunks:
d = secs.get(c["heading"], {})
act[c["heading"]] = d.get("action", c["default"])
# KEEP_SECTION/KEEP_UNSURE은 하위 절까지 포함
inside = set()
for c in chunks:
if act[c["heading"]] in ("KEEP_SECTION", "KEEP_UNSURE"):
for c2 in chunks:
if c["start"] < c2["start"] < c["sub_end"]:
inside.add(c2["heading"])
kept_any = {c["heading"] for c in chunks if act[c["heading"]] in ("KEEP_SECTION", "KEEP_UNSURE", "KEEP_ITEMS") or c["heading"] in inside}
need_head = set(referenced)
for c in chunks: # 남긴 하위 절의 상위 머리글은 남긴다
if c["heading"] in kept_any or c["heading"] in referenced:
p = c["parent"]
while p:
need_head.add(p)
p = next(x["parent"] for x in chunks if x["heading"] == p)
parts = [ref, clean(t[ia:ib]) + "\n\n"]
bh = t[ib:t.find("\n", ib)]
pre_body = t[t.find("\n", ib) + 1:ib + len(pre_b)]
parts.append(bh + "\n\n" + ((clean(pre_body) + "\n\n") if dec.get("pre_b") == "KEEP" and pre_body.strip() else ""))
decisions = []
for c in chunks:
h, a = c["heading"], act[c["heading"]]
d = secs.get(h, {})
if h in inside:
decisions.append({"heading": h, "action": "IN_KEPT_PARENT"})
parts.append(clean(t[c["start"]:c["end"]]) + "\n\n"); continue
if a in ("KEEP_SECTION", "KEEP_UNSURE"):
decisions.append({"heading": h, "action": a, "why": d.get("why", "기본 판정 ①·②")})
parts.append(clean(t[c["start"]:c["end"]]) + "\n\n"); continue
if a == "KEEP_ITEMS":
seg = t[c["start"]:c["end"]]
lines = seg.split("\n")
picks, rows = residue_rows(seg)
picks, items, n_res = picks + rows, [], len(set(rows))
for st in d.get("items", []):
kind, x, y = item_block(seg, st)
it = {"match": st[:60], "kind": kind}
if kind == "row":
a0, a1 = x
picks += [a0, a1, y]
it["quotes_raw"] = any(R_OLD_COL.match(c.strip()) for c in lines[a0].split("|"))
else:
picks += list(range(x, y))
items.append(it)
sel = sorted(set(picks))
txt, prev = [], None
for i in sel:
if prev is not None and i != prev + 1 and not (lines[i].startswith("|") and lines[prev].startswith("|")):
txt.append("")
txt.append(lines[i]); prev = i
body_txt = clean("\n".join(txt))
hk = h in need_head
ref_rows = {y if k == "row" else -1 for k, _, y in (item_block(seg, st) for st in d.get("items", []))} - set(rows)
kind = "mix" if n_res and ref_rows else ("res" if n_res else "ref")
decisions.append({"heading": h, "action": "KEEP_ITEMS", "heading_kept": hk, "items": items, "residue_rows": n_res, "line": kind, "why": d.get("why", "")})
parts.append(("%s\n\n%s\n\n%s\n\n" % (h, ITEMS_LINES[kind], body_txt)) if hk else body_txt + "\n\n"); continue
if h in need_head:
decisions.append({"heading": h, "action": "OMIT", "why": d.get("why", "가리켜진 제작 관리 기록 절")})
parts.append("%s\n\n%s\n\n" % (h, OMIT_LINE))
else:
decisions.append({"heading": h, "action": "DROP", "why": d.get("why", "제작 관리 기록; 가리키는 참조 없음")})
out = "".join(parts).rstrip("\n") + "\n"
return out, decisions, need_head, act, inside
def apply_patches(out, patches, regions=None):
for p in patches:
n, want = out.count(p["old"]), p.get("count", 1)
assert n == want, "patch old found %d times (want %d): %s" % (n, want, p["old"][:80])
if regions is not None:
regions.append("body" if out.find(p["old"]) < out.find("\n## 부록 A") else "appendix")
out = out.replace(p["old"], p["new"])
return out
def cmd_build(root, key, work, decp, outdir=None):
t, rn, ref, ia, ib, chunks, pre_b = load(root, key)
dec = json.load(open(decp, encoding="utf-8"))
rules = dec.get("refs", [])
referenced, seen = set(), None
for _ in range(10): # 닫힘
out, decisions, need_head, act, inside = assemble(t, ref, ia, ib, chunks, pre_b, dec, referenced)
# 본문·부록 A는 raw 위치로, 부록 B는 조립된 출력 안에서 찾는다(남긴 글만 대상, 고정 문구·머리글 줄 제외)
ob = out.find("\n## 부록 B") + 1
btxt = "\n".join("" if (l in FIXED_LINES or R_HEAD.match(l) or l.startswith("## 부록 B")) else l for l in out[ob:].split("\n"))
res = resolve(find_refs(t, [("body", 0, ia), ("A", ia, ib)]) + find_refs({"B": btxt}, [("B", 0, len(btxt))]), chunks, rules)
new_ref = {r["target"] for r in res if r["target"] and r["target"].startswith("###")}
if new_ref == seen:
break
seen, referenced = new_ref, new_ref
patches = dec.get("patches", [])
regions = []
out0, out = out, apply_patches(out, patches, regions)
# ---- 검사 ----
C, fail = {}, {}
if outdir:
od = os.path.join(root, outdir); ld = os.path.join(od, "_기록")
else:
od, ld = os.path.join(root, "청구취지규칙문서_사건종류별_부록정리"), os.path.join(root, "청구취지규칙문서_사건종류별_부록정리_기록")
os.makedirs(od, exist_ok=True); os.makedirs(ld, exist_ok=True)
op = os.path.join(od, "청구취지작성규칙_%s.md" % key)
open(op, "w", encoding="utf-8").write(out)
names = [unicodedata.normalize("NFC", n) for n in os.listdir(od)]
stray = [n for n in names if not re.match(r"청구취지작성규칙_.+\.md$", n) and not n.startswith("_")]
C["C1"] = os.path.exists(op) and not stray; fail["C1"] = stray
C["C2"] = out0[:out0.find("\n## 부록 A") + 1] == ref
want = [d["heading"] for d in decisions if d["action"] in ("KEEP_SECTION", "KEEP_UNSURE", "OMIT", "IN_KEPT_PARENT") or d.get("heading_kept")]
got = [m.group() for m in R_HEAD.finditer(out[out.find("\n## 부록 B"):])]
C["C3"] = want == got and "\n## 부록 B" in out and all(h in got for h in referenced); fail["C3"] = [want, got] if not C["C3"] else []
heads_out = set(m.group().strip() for m in re.finditer(r"(?m)^#{2,6} .*$", out))
bad = [r for r in res if r["kind"] == "UNRESOLVED" or (r["kind"] in ("APPLY", "RECORD") and r["target"] not in ("## 부록 A", "## 부록 B") and r["target"] not in heads_out)]
C["C4"] = not bad; fail["C4"] = [{k: r[k] for k in ("text", "from", "at", "context", "kind", "target")} for r in bad][:40]
rec = dec.get("record_ids", {})
lost0 = (ids(out) & defs(t)) - defs(out)
lost = sorted(lost0 - set(rec))
C["C5"] = not lost; fail["C5"] = lost
bad12 = ["unneeded:" + x for x in rec if x not in lost0]
for x in sorted(set(rec) & lost0): # 부록 B 기록 위치 표지로만 쓰였는지
for m in re.finditer(r"(?<![\w-])%s(?![A-Za-z0-9_-])" % re.escape(x), out):
pre = out[max(0, out.rfind("\n", 0, m.start()) + 1, m.start() - 40):m.start()]
if not (R_NUM.search(pre) or "부록 B" in pre or "부록B" in pre):
bad12.append("%s@%d:%s" % (x, m.start(), out[m.start() - 40:m.end() + 20].replace("\n", " ")))
C["C12"] = not bad12; fail["C12"] = bad12[:20]
actd = {d["heading"]: d["action"] for d in decisions}
bad6 = [r for r in res if r["kind"] == "APPLY" and r["target"] and r["target"].startswith("###") and actd.get(r["target"]) not in ("KEEP_SECTION", "KEEP_UNSURE", "KEEP_ITEMS", "IN_KEPT_PARENT")]
C["C6"] = not bad6; fail["C6"] = [{k: r[k] for k in ("text", "at", "context", "target")} for r in bad6][:20]
raw_lines, k, miss = clean(t[ia:]).split("\n"), 0, None
for ln in out0[out0.find("\n## 부록 A") + 1:].split("\n"):
if ln in FIXED_LINES or ln == "":
continue
while k < len(raw_lines) and raw_lines[k] != ln:
k += 1
if k == len(raw_lines):
miss = ln[:160]; break
k += 1
C["C7"] = miss is None; fail["C7"] = miss
C["C8"] = not any(x in out for x in ("http", "<a id=", "](#", "]()")); fail["C8"] = [x for x in ("http", "<a id=", "](#", "]()") if x in out]
body = t[:ia]
kb = out[out.find("\n## 부록 B"):]
sel = "\n".join(l for l in body.split("\n") if "선택 기준" in l)
lwf = sorted({m.group() for m in re.finditer(r"LEAF-[A-Za-z0-9-]*\d[A-Za-z0-9-]*", body)} - set(re.findall(r"LEAF-[A-Za-z0-9-]+", kb + sel)))
C["C9"] = True # LEAF_WITHOUT_FORM은 기록만(새로 만들지 않는다)
out2 = apply_patches(assemble(t, ref, ia, ib, chunks, pre_b, dec, referenced)[0], patches)
C["C10"] = sha(out2) == sha(out)
out_lines, lost11 = set(out.split("\n")), []
for c in chunks:
if actd.get(c["heading"]) == "KEEP_ITEMS":
seg = t[c["start"]:c["end"]]
lost11 += [ln[:120] for ln in (clean_line(seg.split("\n")[r]) for r in residue_rows(seg)[1]) if ln not in out_lines]
C["C11"] = not lost11; fail["C11"] = lost11
flags = (["LEAF_WITHOUT_FORM:" + x for x in lwf]) + ["RAW_DANGLING:%s@%d" % (r["text"], r["at"]) for r in res if r["kind"] == "RAW_DANGLING"]
flags += ["OLD_WORDING_ROW:" + it["match"].strip("| ") for d in decisions for it in d.get("items", []) if it.get("quotes_raw")]
log = {"source": "raw/" + rn, "source_sha256": sha(t), "output_sha256": sha(out),
"inventory": {"body_end": ia, "appendix_a": [ia, ib],
"b_sections": [{k2: c[k2] for k2 in ("heading", "level", "start", "end", "default")} for c in chunks],
"leaf_without_form": lwf},
"decisions": decisions,
"ref_resolution": [{k2: r[k2] for k2 in ("text", "from", "at", "kind", "target")} for r in res],
"flags": flags, "checks": C, "record_ids": rec,
"patches": [{"why": p.get("why", ""), "region": rg, "count": p.get("count", 1),
"old_chars": len(p["old"]), "new_chars": len(p["new"])} for p, rg in zip(patches, regions)],
"chars": {"body": len(ref), "appendix_a": len(clean(t[ia:ib])), "appendix_b": len(out) - len(ref) - len(clean(t[ia:ib])) - 2,
"total": len(out), "raw_total": len(t)}}
json.dump(log, open(os.path.join(ld, key + ".json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
from collections import Counter
print(json.dumps({"key": key, "checks": C, "fail": {k: v for k, v in fail.items() if v and not C[k]},
"actions": Counter(d["action"] for d in decisions), "chars": log["chars"], "flags": flags,
"ref_kinds": Counter(r["kind"] for r in res)}, ensure_ascii=False))
if __name__ == "__main__":
if sys.argv[1] == "inv":
cmd_inv(*sys.argv[2:5])
else:
cmd_build(*sys.argv[2:7])