@chrono-meta/fh-gate 3.11.0 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,591 @@
1
+ #!/usr/bin/env python3
2
+ """section_ref_check.py — every §N / Sec. N / 섹션 N / N절 / 부록 N / Appendix X / K.n cross-reference resolves to a heading.
3
+
4
+ WHAT IT CLOSES (measured 2026-09-17, paper-2 draft)
5
+ A paper renumbers its sections during a rewrite and the cross-references keep the old numbers; a
6
+ section is deleted and `§3.7` still points at it; a pointer says «부록 3 §10» and no such thing
7
+ exists (the draft itself records one of these: «초판이 「부록 3 §10」이라고 적었고 그 번호는
8
+ 없다»). The governor checked this by hand. This tool parses every heading (`#`…`######`) into an
9
+ anchor and every cross-reference in the body into a key, and names each ref that does not resolve,
10
+ with its line — DANGLING (parent exists) is kept apart from DANGLING (no such top-level), because
11
+ the first is usually a missing sub-heading and the second a wrong number.
12
+
13
+ WHAT IT DOES NOT DO — read before trusting a 0
14
+ 🟥 Heading-defined anchors ONLY. A paper that defines «부록 1…7» in a pointer TABLE, or a
15
+ numbered paragraph without a heading, is reported DANGLING for those refs. That is a finding
16
+ about the paper's shape, not a false positive — but `--define '부록 1'` declares such an anchor
17
+ explicitly (printed in the header, never implicit).
18
+ 🟥 A ref into ANOTHER document («RESULT §12», «Workbook 부록 B») is DANGLING here by construction:
19
+ this tool sees one corpus. `--external REGEX` classifies a ref whose same-line ±80-char window
20
+ matches REGEX as EXTERNAL — listed, not counted — and the regex is printed. Off by default:
21
+ the loud direction is the safe one, and the snippet beside each DANGLING row shows the context.
22
+ 🟥 Exact key match. `§3.2` does not resolve to `### 3.2b`, `K.2` does not resolve to `## Appendix K`
23
+ — both are DANGLING (parent exists). `--parent-resolves` makes any ref with an existing ancestor
24
+ resolve: ABLATION ONLY (revert probe); it turns the instrument into «the chapter exists».
25
+ 🟥 Only the spellings listed under GRAMMAR are refs — that list is GENERATED from the regex source,
26
+ so it cannot drift from what is scanned. A spelling outside it (`Sect. 3`, `chapter 3`, `제3장`)
27
+ is not scanned and does not dangle; cross-family review (codex, 2026-09-17) found `Sec. 9.4` /
28
+ `Section 3.2` / `섹션 8.1` outside the first version's grammar, so a body written that way was
29
+ rc=0 without a single ref read. `--no-alt-spellings` reproduces that arm (ABLATION ONLY).
30
+ `N절` with a bare integer is ambiguous with a count: `0절` is never a ref (sections are 1-based;
31
+ «관련연구 0절로» measured as a count), `3절로 나눴다` still reads as §3 — loud direction.
32
+ 🟥 Refs are read from body lines that are not headings, code fences included (a fenced quote that
33
+ cites a section is still a pointer a reader will follow). `§F_r2ctrl`-style tokens (no digit
34
+ after §) are not refs. `§4-1` reads as `§4` and `§3.2 — 0.017` as `§3.2` (a range needs `~` or
35
+ an EN dash, or a second `§` after a hyphen / EM dash: `§12~§21` · `§3.1–3.2` · `§3 — §4`).
36
+
37
+ GRAMMAR
38
+ heading `## 3. Method` · `### 4.2 …` · `#### 9.4.1 …` · `### 2.3b …` · `### §3.3-b …` · `## 부록 8 —`
39
+ · `## Appendix K` · `### K.2 …` · `## A.6 …` (an unnumbered heading defines nothing)
40
+ ref {SPELLINGS}
41
+ · `부록 8` `부록 B` `Appendix K` `Appendix 3` · `K.2` `A.6.2.7` (a capital letter, a dot,
42
+ digits — not preceded by a letter)
43
+ map `--map 3=4,3.3=1.5,부록 3=부록 A` — a ref still under an OLD number is STALE-OLD (rc=1),
44
+ whether or not the old number happens to resolve today.
45
+
46
+ EXIT CODES
47
+ 0 every ref resolves (EXTERNAL refs listed, not counted)
48
+ 1 DANGLING or STALE-OLD refs present
49
+ 4 DEAD CONTROL: zero cross-references found — distinct from 0 on purpose (headings are printed)
50
+ 10 input error (file missing · zero numbered headings, so every ref would dangle — not a verdict)
51
+
52
+ USAGE
53
+ python3 scripts/section_ref_check.py --body <md...> [--define REF ...] [--external REGEX]
54
+ [--map old=new,...] [--show-resolved] [--list-headings] [--json]
55
+ bash scripts/test_paper_integrity_lanes.sh # known pairs + revert probes
56
+ Python ≥ 3.9, stdlib only.
57
+ """
58
+ import argparse
59
+ import json
60
+ import re
61
+ import sys
62
+ import unicodedata
63
+
64
+ APP = r"(?:부록|Appendix|APPENDIX|appendix)"
65
+ NUMKEY = r"\d+(?:\.\d+)*(?:-?[a-z])?"
66
+ # ── Section spellings: ONE source. The prefix tuple builds the regexes AND the printed list. ────
67
+ # Longest first inside the alternation (`Section` before `Sec.` before `Sec`).
68
+ # v6 (codex round 5): plural / lowercase English forms were outside the grammar, so `sections 3.1 - 3.3`
69
+ # was not even scanned. Longest first inside the alternation (`Sections` before `Section`).
70
+ SECTION_PREFIXES = ("§", "Sections", "Section", "sections", "section", "Sec.", "Sec", "섹션")
71
+ SECTION_SUFFIXES = ("절",) # `3.2절` — digits glued to the suffix, no space
72
+ RANGE_EXAMPLES = ("§12~§21", "§3.1–3.2", "§3 — §4", "Section 1.1-1.3")
73
+ RANGE_INTERIOR_CAP = 50 # `§1~§999` is not expanded — a cap, printed when hit
74
+
75
+
76
+ def section_prefix_regex(prefixes):
77
+ return r"(?<![A-Za-z])(?:" + "|".join(re.escape(p) for p in prefixes) + r")"
78
+
79
+
80
+ def build_ref_regexes(alt_spellings, compact_range=True):
81
+ """→ (section_re, suffix_re_or_None). `alt_spellings=False` keeps only `§` (ablation arm);
82
+ `compact_range=False` drops the `1.1-1.3` ASCII-hyphen form (ablation arm)."""
83
+ prefixes = SECTION_PREFIXES if alt_spellings else ("§",)
84
+ # A range is `§12~§21` / `§3.1–3.2` (tilde or EN dash, optional second §) or `§3 - §4` /
85
+ # `§3 — §4` (hyphen / EM dash ONLY when a second § follows). `§3.2 — 0.017` is a section
86
+ # followed by a number, not a range — measured on the 2026-09-17 draft («§0.017»).
87
+ # 🟥 v3 (codex round 2, 2026-09-18): `Section 1.1-1.3` — a COMPACT ASCII hyphen straight into a
88
+ # digit — was read as `§1.1` alone, so a missing upper endpoint was silent. It is a range only when
89
+ # both sides share the same parent and ascend (`1.1-1.3` yes · `2026-09-10` no — refs_in() enforces that).
90
+ # 🟥 v6 (codex round 5): the SPACED ASCII hyphen `Section 3.1 - 3.3` was outside that form and read
91
+ # as `§3.1` alone. Spaces around the hyphen are now allowed; the same-parent + ascending guard is what
92
+ # keeps `§3.2 - 0.017` (parent 3 vs 0) a section followed by a number. EM/EN dashes are unchanged.
93
+ # v14 (codex round 13): prose ranges `Sections 6.1 through 6.3` · `§3.1 to 3.3` go through the same expansion
94
+ range_forms = r"\s*[~–]\s*§?|\s*[—-]\s*§|\s+(?:through|thru|to)\s+§?" + (r"|\s*-\s*(?=\d)" if compact_range else "")
95
+ # v16 (codex round 15): ONE range tail — numeric second end, or a suffix-only second end (`3.2a-c`) — shared by
96
+ # the primary ref, the slash continuation and the plural-list continuation, so a shorthand that the primary
97
+ # ref reads is read in every position.
98
+ range_tail = (r"(?:(?:(?:" + range_forms + r")\s*(?P<num2>\d+(?:\.\d+)*)(?P<suf2>-?[a-z])?|\s*[-–]\s*(?P<suf2o>[a-z]))"
99
+ r"(?![A-Za-z0-9])(?!\.\d))?")
100
+ section_re = re.compile(
101
+ section_prefix_regex(prefixes)
102
+ + r"\s*(?P<num>\d+(?:\.\d+)*)(?P<suf>-?[a-z])?(?![A-Za-z0-9])(?!\.\d)" + range_tail)
103
+ # (v15, codex round 14: `§3.2a-c` — a suffix-only second endpoint means «same number, that suffix»)
104
+ # v9 (codex round 8): a slash continuation may itself carry a range — `§3.1/3.2-3.4` names §3.3 too;
105
+ # v10 (round 9): spaces around the slash (`§3.1 / 3.2`) are allowed
106
+ slash_re = re.compile(r"\s*/\s*(?P<num>\d+(?:\.\d+)*)(?P<suf>-?[a-z])?(?![A-Za-z0-9])(?!\.\d)" + range_tail)
107
+ # v11 (codex round 10): after a PLURAL prefix (`Sections 3.1 and 3.2` · `sections 3.1, 3.2 and 3.4-3.6`)
108
+ # the list continues — comma / semicolon / and / or / & / 및, Oxford `, and` too (v13·v14) — each item through the same range grammar. Singular
109
+ # prefixes do not continue (`§3.1, 12 cases` names no §12).
110
+ cont_re = re.compile(
111
+ r"(?:\s*[,;]\s*(?:and\s+|or\s+|&\s*|및\s*)?|\s+(?:and|or)\s+|\s*&\s*|\s*및\s*)(?P<num>\d+(?:\.\d+)*)(?P<suf>-?[a-z])?(?![A-Za-z0-9])(?!\.\d)"
112
+ + range_tail)
113
+ suffix_re = None
114
+ if alt_spellings:
115
+ # `N절` with a bare integer is ambiguous with a COUNT («관련연구 0절로 내는 것» = zero sections,
116
+ # measured on the 2026-09-17 prior-art section). Sections are 1-based, so a leading 0 is never
117
+ # a ref; a count with N ≥ 1 («3절로 나눴다») still reads as a ref — loud direction, the snippet
118
+ # beside the row settles it.
119
+ suffix_re = re.compile(r"(?<![\d.A-Za-z])(?P<num>(?!0)\d+(?:\.\d+)*)(?P<suf>-?[a-z])?(?:"
120
+ + "|".join(re.escape(s) for s in SECTION_SUFFIXES) + r")")
121
+ return section_re, suffix_re, slash_re, cont_re
122
+
123
+
124
+ def spellings_text(alt_spellings):
125
+ prefixes = SECTION_PREFIXES if alt_spellings else ("§",)
126
+ forms = [p + ("" if p == "§" else " ") + "N" for p in prefixes]
127
+ if alt_spellings:
128
+ forms += ["N" + s for s in SECTION_SUFFIXES]
129
+ return " · ".join("`%s`" % f for f in forms) + " (N = 3 · 3.2 · 9.4.1 · 2.3b · 3.3-b; N절 needs N ≥ 1 — `0절` is a count; ranges " \
130
+ + " · ".join("`%s`" % r for r in RANGE_EXAMPLES) + ")" + ("" if alt_spellings else " [ABLATION: alt spellings off]")
131
+
132
+
133
+ HEADING_RE = re.compile(r"^(#{1,6})\s+(.*?)\s*$")
134
+ H_SECTION_RE = re.compile(r"^(?:" + section_prefix_regex(SECTION_PREFIXES) + r"\s*)?(?P<num>\d+(?:\.\d+)*)(?P<suf>-?[a-z])?(?=[.)]?(?:\s|$))")
135
+ H_APPENDIX_RE = re.compile(r"^" + APP + r"\s*(?P<app>\d+|[A-Z])(?:\.(?P<sub>\d+(?:\.\d+)*))?(?![A-Za-z0-9])")
136
+ H_LETTER_RE = re.compile(r"^(?P<let>[A-Z])\.(?P<sub>\d+(?:\.\d+)*)(?=[.)]?(?:\s|$))")
137
+ R_APPENDIX_RE = re.compile(APP + r"\s*(?P<app>\d+|[A-Za-z])(?:\.(?P<sub>\d+(?:\.\d+)*))?(?![A-Za-z0-9])(?!\.\d)") # v17: `appendix k.2` too
138
+ R_LETTER_RE = re.compile(r"(?<![A-Za-z0-9.§])(?P<let>[A-Z])\.(?P<sub>\d+(?:\.\d+)*)(?![A-Za-z0-9])(?!\.\d)")
139
+ TOKEN_PREFIX_RE = r"(?:(?:" + "|".join(re.escape(p) for p in SECTION_PREFIXES) + r")\s*)?"
140
+
141
+
142
+ def _nfkc(s):
143
+ return unicodedata.normalize("NFKC", s)
144
+
145
+
146
+ # v18 (codex round 17, fixtures run by the author after the sidecar hit its quota): full-width ASCII (U+FF01–FF5E)
147
+ # and the ideographic space are the reader's ASCII — mapped per character (length-preserving) before a line
148
+ # is scanned for headings or refs, so `Appendix K` keys as K and `## Appendix K` defines it.
149
+ FULLWIDTH = {c: c - 0xFEE0 for c in range(0xFF01, 0xFF5F)}
150
+ FULLWIDTH[0x3000] = 0x20
151
+
152
+
153
+ def _fw(line):
154
+ return line.translate(FULLWIDTH)
155
+
156
+
157
+ CODE_SPAN_MASK_RE = re.compile(r"`[^`\n]*`")
158
+
159
+
160
+ FENCE_RE = re.compile(r"^(?:>\s*)*(`{3,}|~{3,})(.*)$")
161
+
162
+
163
+ def _fence_step(line, fence):
164
+ """→ (fence_after, on_fence_line). `fence` = (char, opener length) while inside a fenced block, else
165
+ None. v9 (codex round 8) — CommonMark: a closer uses the same char, is at least as long as the
166
+ opener and carries nothing but spaces after it (a 3-tick line does not close a 4-tick fence); a
167
+ `> ` prefix is allowed (a fence inside a blockquote). Kept byte-identical across the three tools."""
168
+ m = FENCE_RE.match(line.lstrip())
169
+ if fence is None:
170
+ return ((m.group(1)[0], len(m.group(1))), True) if m else (None, False)
171
+ if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= fence[1] and not m.group(2).strip():
172
+ return None, True
173
+ return fence, False
174
+
175
+
176
+ def strip_html_comments(text):
177
+ """v6 (codex round 5): text inside `<!-- … -->` is invisible to the reader, so it is neither a defect
178
+ nor an anchor. 🟥 v7 (codex round 6): the v6 regex strip ERASED PROSE between a `<!--` and a `-->`
179
+ that sat inside code spans or fenced blocks — a delimiter inside code is a literal. 🟥 v8 (codex
180
+ round 7): the same for `~~~` fences and 4-space / tab INDENTED code blocks (a block starts after a
181
+ blank line and runs while lines stay indented). v9: fences go through _fence_step (opener length ·
182
+ blockquote prefix). Fences and indented code are left untouched, code spans are masked before a
183
+ delimiter is looked for. Line numbers are preserved; comment text becomes spaces. Kept
184
+ byte-identical in the three tools (lanes L11l / L11o / L11q pin all three)."""
185
+ out, fence, in_comment, prev_blank, prev_code = [], None, False, True, False
186
+ for line in text.split("\n"):
187
+ if in_comment:
188
+ j = line.find("-->")
189
+ if j < 0:
190
+ out.append(" " * len(line))
191
+ continue
192
+ line, in_comment = " " * (j + 3) + line[j + 3:], False
193
+ s = line.strip()
194
+ fence, on_fence = _fence_step(line, fence)
195
+ if on_fence or fence is not None:
196
+ out.append(line)
197
+ prev_blank, prev_code = False, False
198
+ continue
199
+ indented = (line.startswith(" ") or line.startswith("\t")) and (prev_blank or prev_code)
200
+ if indented:
201
+ out.append(line)
202
+ prev_blank, prev_code = False, True
203
+ continue
204
+ prev_blank, prev_code = (s == ""), False
205
+ masked = CODE_SPAN_MASK_RE.sub(lambda m: " " * len(m.group(0)), line)
206
+ res, pos = [], 0
207
+ while True:
208
+ i = masked.find("<!--", pos)
209
+ if i < 0:
210
+ res.append(line[pos:])
211
+ break
212
+ res.append(line[pos:i])
213
+ j = line.find("-->", i + 4)
214
+ if j < 0:
215
+ res.append(" " * (len(line) - i))
216
+ in_comment = True
217
+ break
218
+ res.append(" " * (j + 3 - i))
219
+ pos = j + 3
220
+ out.append("".join(res))
221
+ return "\n".join(out)
222
+
223
+
224
+
225
+
226
+ def skey(num, suf):
227
+ # NFKC: `§1.2` (full-width digits, codex round 3) keys the same as `## 1.2`; display keeps the raw text
228
+ return "S:" + _nfkc(num) + (suf or "")
229
+
230
+
231
+ def akey(app, sub):
232
+ return "A:" + _nfkc(app).upper() + (("." + _nfkc(sub)) if sub else "") # v17: prose `appendix k.2` keys as K.2
233
+
234
+
235
+ def show(key):
236
+ ns, rest = key.split(":", 1)
237
+ if ns == "S":
238
+ return "§" + rest
239
+ if rest.isdigit():
240
+ return "부록 " + rest
241
+ if "." in rest:
242
+ return rest # K.2
243
+ return "Appendix " + rest # K
244
+
245
+
246
+ def parse_heading_key(text):
247
+ t = text.strip().lstrip("*_ ").strip()
248
+ # v7 (codex round 6): `## **3.2** Middle` renders as a numbered heading — drop emphasis glued to the number
249
+ t = re.sub(r"^(\S+?)[*_]{1,3}(?=\s|$)", r"\1", t)
250
+ m = H_APPENDIX_RE.match(t)
251
+ if m:
252
+ return akey(m.group("app"), m.group("sub"))
253
+ m = H_SECTION_RE.match(t)
254
+ if m:
255
+ return skey(m.group("num"), m.group("suf"))
256
+ m = H_LETTER_RE.match(t)
257
+ if m:
258
+ return akey(m.group("let"), m.group("sub"))
259
+ return None
260
+
261
+
262
+ def parse_ref_token(text):
263
+ """One ref-shaped string (`3.2`, `§3.2`, `Sec. 3.2`, `3.2절`, `부록 3`, `K`, `K.2`, `Appendix K`) → key or None."""
264
+ t = text.strip()
265
+ m = re.fullmatch(TOKEN_PREFIX_RE + r"(?P<num>\d+(?:\.\d+)*)(?P<suf>-?[a-z])?(?:" + "|".join(SECTION_SUFFIXES) + r")?", t)
266
+ if m:
267
+ return skey(m.group("num"), m.group("suf"))
268
+ m = re.fullmatch(APP + r"\s*(?P<app>\d+|[A-Za-z])(?:\.(?P<sub>\d+(?:\.\d+)*))?", t)
269
+ if m:
270
+ return akey(m.group("app"), m.group("sub"))
271
+ m = re.fullmatch(r"(?P<let>[A-Z])(?:\.(?P<sub>\d+(?:\.\d+)*))?", t)
272
+ if m:
273
+ return akey(m.group("let"), m.group("sub"))
274
+ return None
275
+
276
+
277
+ def _parent_last(num):
278
+ """`3.2.4` → (`3.2`, `4`) · `12` → (``, `12`)."""
279
+ return (num.rsplit(".", 1)[0], num.rsplit(".", 1)[1]) if "." in num else ("", num)
280
+
281
+
282
+ def _range_refs(n1, s1, n2, s2, sep, rng, start, expand_interior, cap, cap_verdict):
283
+ """The second endpoint of a range plus its interiors (or one UNCHECKED row) → [(key, display, start)];
284
+ [] when the compact-hyphen guard rejects the second number (`Sec. 2026-09-10` is a date)."""
285
+ if "." in n1 and "." not in n2 and "§" not in sep and not s1 and not s2:
286
+ n2 = n1.rsplit(".", 1)[0] + "." + n2 # v15 (codex round 14): `Sections 3.1-3` is the sibling shorthand 3.1–3.3
287
+ (p1, a), (p2, b) = _parent_last(n1), _parent_last(n2)
288
+ if sep == "-" and not (s1 or s2) and (p1 != p2 or not (a.isdigit() and b.isdigit() and int(a) < int(b))):
289
+ return [] # compact form = same parent AND ascending (numeric ends only; `§3.2a-c` is a suffix range)
290
+ out = [(skey(n2, s2 or None), "§" + n2 + s2, start)]
291
+ if not expand_interior:
292
+ return out
293
+ # Which interiors a range names is decided by its FORM, and only four forms are enumerable:
294
+ # same parent, integer ends `§1.1–1.3` → §1.2 (v3, codex round 2)
295
+ # same number, letter suffixes `§3.2a–3.2c` → §3.2b (v4, codex round 3)
296
+ # parent to its own child `§3~§3.2` → §3.1 (v5, codex round 4)
297
+ # number to its own suffix `§3.2–3.2b` → §3.2a (v5 — a suffix is a child of its number)
298
+ # 🟥 v5: every OTHER form with a range separator (`§3.2a-3.3` · `§3.2a–3.3c` · `§3~§4.2`) used to
299
+ # check its endpoints and say clean — the interior was not unchecked by accident but by having no
300
+ # definition, and rc=0 hid that. It is now an UNCHECKED row (DANGLING-class, the key can never
301
+ # resolve) unless --no-unchecked-verdict; the cap hit (v4) is the same row with a different reason.
302
+ inner_keys, why = None, None
303
+ if p1 == p2 and not s1 and not s2 and a.isdigit() and b.isdigit() and int(a) < int(b):
304
+ inner_keys = [((p1 + "." if p1 else "") + str(k), None) for k in range(int(a) + 1, int(b))]
305
+ elif n1 == n2 and s1 and s2 and s1[-1] < s2[-1]:
306
+ style = "-" if s1.startswith("-") else ""
307
+ inner_keys = [(n1, style + chr(c)) for c in range(ord(s1[-1]) + 1, ord(s2[-1]))]
308
+ elif n1 == n2 and not s1 and s2:
309
+ style = "-" if s2.startswith("-") else ""
310
+ inner_keys = [(n1, style + chr(c)) for c in range(ord("a"), ord(s2[-1]))]
311
+ elif not s1 and not s2 and p2 == n1 and b.isdigit() and int(b) >= 1:
312
+ inner_keys = [(n1 + "." + str(k), None) for k in range(1, int(b))]
313
+ else:
314
+ why = "mixed form — no defined interior"
315
+ # span = sections from the first end to the last (`§1–5` spans 4), the number --help promises
316
+ if inner_keys is not None and len(inner_keys) + 1 > cap:
317
+ why = "span > %d — --range-cap N to expand" % cap
318
+ if why is not None:
319
+ if cap_verdict:
320
+ out.append((skey(n1 + "~" + n2, None), "%s (interior UNCHECKED: %s)" % (rng, why), start))
321
+ else:
322
+ print("⚠️ range %s — %s — interior NOT expanded (ABLATION: --no-unchecked-verdict)" % (rng, why), file=sys.stderr)
323
+ return out
324
+ for inner, suf in inner_keys:
325
+ out.append((skey(inner, suf), "§%s%s (interior of %s)" % (inner, suf or "", rng), start))
326
+ return out
327
+
328
+
329
+ def refs_in(line, rxs):
330
+ """→ [(key, display, start)] for every cross-reference on a non-heading line. `display` keeps the
331
+ spelling as written (`Sec. 9.4`, `3.2절`) so the reader sees what the reader will see."""
332
+ section_re, suffix_re, slash_re, cont_re, expand_interior, cap, cap_verdict = rxs
333
+ out = []
334
+ for m in section_re.finditer(line):
335
+ end1 = m.end("suf") if m.group("suf") else m.end("num")
336
+ n1, s1 = _nfkc(m.group("num")), m.group("suf") or ""
337
+ out.append((skey(m.group("num"), m.group("suf")), line[m.start():end1], m.start()))
338
+ pos = end1
339
+ if m.group("num2") or m.group("suf2o"):
340
+ if m.group("suf2o"): # v15: `§3.2a-c` → second endpoint = same number, suffix c (style of the first)
341
+ n2, s2 = n1, ("-" if s1.startswith("-") else "") + m.group("suf2o")
342
+ sep = line[end1:m.start("suf2o")].strip()
343
+ else:
344
+ n2, s2 = _nfkc(m.group("num2")), m.group("suf2") or ""
345
+ sep = line[end1:m.start("num2")].strip()
346
+ out += _range_refs(n1, s1, n2, s2, sep, line[m.start():m.end()].strip(), m.start(), expand_interior, cap, cap_verdict)
347
+ pos = m.end() # v12 (codex round 11): a plural list may continue AFTER a range item
348
+ # v7 (codex round 6): `§3.1/3.2` names two sections; a bare integer after the slash is a sibling
349
+ # when the first is dotted (`§3.1/2` → §3.2). v9 (round 8): the slash side may carry a range.
350
+ plural = line[m.start():m.start("num")].strip().lower().startswith("sections")
351
+ while True:
352
+ sm = slash_re.match(line, pos) or (cont_re.match(line, pos) if plural else None)
353
+ if not sm:
354
+ break
355
+ n = _nfkc(sm.group("num"))
356
+ if "." not in n and "." in n1:
357
+ n = n1.rsplit(".", 1)[0] + "." + n
358
+ s = sm.group("suf") or ""
359
+ endn = sm.end("suf") if sm.group("suf") else sm.end("num")
360
+ out.append((skey(n, s or None), "§%s%s (in %s)" % (n, s, line[m.start():endn]), m.start()))
361
+ if sm.group("num2") or sm.group("suf2o"):
362
+ if sm.group("suf2o"):
363
+ n2, s2, sep = n, ("-" if s.startswith("-") else "") + sm.group("suf2o"), line[endn:sm.start("suf2o")].strip()
364
+ else:
365
+ n2, s2, sep = _nfkc(sm.group("num2")), sm.group("suf2") or "", line[endn:sm.start("num2")].strip()
366
+ out += _range_refs(n, s, n2, s2, sep, line[m.start():sm.end()].strip(), m.start(), expand_interior, cap, cap_verdict)
367
+ pos = sm.end()
368
+ if suffix_re is not None:
369
+ for m in suffix_re.finditer(line):
370
+ out.append((skey(m.group("num"), m.group("suf")), m.group(0), m.start()))
371
+ spans = []
372
+ for m in R_APPENDIX_RE.finditer(line):
373
+ out.append((akey(m.group("app"), m.group("sub")), m.group(0), m.start()))
374
+ out += _letter_range(line, m, m.group("app"), m.group("sub")) if expand_interior else []
375
+ spans.append((m.start(), m.end()))
376
+ for m in R_LETTER_RE.finditer(line):
377
+ if any(a <= m.start() < b for a, b in spans):
378
+ continue # v18: `Appendix K.1` is one ref, not `Appendix K.1` + `K.1`
379
+ out.append((akey(m.group("let"), m.group("sub")), m.group(0), m.start()))
380
+ out += _letter_range(line, m, m.group("let"), m.group("sub")) if expand_interior else []
381
+ return out
382
+
383
+
384
+ LETTER_RANGE_RE = re.compile(r"\s*[-–~]\s*(?:(?:부록|Appendix|APPENDIX|appendix)\s*)?(?:(?P<let>[A-Za-z])\.)?(?P<sub>\d+)(?![A-Za-z0-9.])")
385
+
386
+
387
+ def _letter_range(line, m, let, sub):
388
+ """v18: `Appendix K.1-K.3` · `K.1–3` name the interior K.2 (same letter, integer ends). Other forms are endpoints only."""
389
+ if not sub or "." in sub or not sub.isdigit():
390
+ return []
391
+ r = LETTER_RANGE_RE.match(line, m.end())
392
+ if not r or (r.group("let") and r.group("let").upper() != let.upper()):
393
+ return []
394
+ a, b = int(sub), int(r.group("sub"))
395
+ rng = line[m.start():r.end()].strip()
396
+ out = [(akey(let, r.group("sub")), "%s.%s (in %s)" % (let.upper(), r.group("sub"), rng), m.start())]
397
+ if a < b:
398
+ out += [(akey(let, str(k)), "%s.%d (interior of %s)" % (let.upper(), k, rng), m.start()) for k in range(a + 1, b)]
399
+ return out
400
+
401
+
402
+ def ancestors(key):
403
+ ns, rest = key.split(":", 1)
404
+ out = []
405
+ base = re.sub(r"-?[a-z]$", "", rest)
406
+ if base != rest:
407
+ out.append(ns + ":" + base)
408
+ parts = base.split(".")
409
+ while len(parts) > 1:
410
+ parts = parts[:-1]
411
+ out.append(ns + ":" + ".".join(parts))
412
+ return out
413
+
414
+
415
+ def is_under(key, old):
416
+ if key == old:
417
+ return True
418
+ if not key.startswith(old):
419
+ return False
420
+ rest = key[len(old):]
421
+ return rest.startswith(".") or rest.startswith("-") or re.fullmatch(r"[a-z]", rest) is not None
422
+
423
+
424
+ def main():
425
+ ap = argparse.ArgumentParser(description=__doc__.replace("{SPELLINGS}", spellings_text(True)),
426
+ formatter_class=argparse.RawDescriptionHelpFormatter)
427
+ ap.add_argument("--body", nargs="+", required=True, metavar="MD", help="body file(s); headings and refs are pooled across them")
428
+ ap.add_argument("--define", action="append", default=[], metavar="REF",
429
+ help="declare an anchor that is not a heading (e.g. '부록 1'); repeatable, printed")
430
+ ap.add_argument("--external", metavar="REGEX", help="a ref whose same-line ±80-char window matches is EXTERNAL (listed, not counted)")
431
+ ap.add_argument("--map", metavar="OLD=NEW,...", help="renumbering map; refs still under an OLD number are STALE-OLD")
432
+ ap.add_argument("--parent-resolves", action="store_true", help="ABLATION ONLY: a ref resolves if any ancestor heading exists")
433
+ ap.add_argument("--no-alt-spellings", action="store_true",
434
+ help="ABLATION ONLY: scan `§N` alone — Sec./Section/섹션/N절 refs are not read (the 2026-09-17 v1 arm)")
435
+ ap.add_argument("--no-range-interior", action="store_true",
436
+ help="ABLATION ONLY: check only a range's two endpoints — `§1.1–1.3` with no §1.2 reads clean (the v2 arm)")
437
+ ap.add_argument("--no-compact-range", action="store_true",
438
+ help="ABLATION ONLY: `Section 1.1-1.3` (compact ASCII hyphen) is read as §1.1 alone (the v2 arm)")
439
+ ap.add_argument("--range-cap", type=int, default=RANGE_INTERIOR_CAP, metavar="N",
440
+ help="a range spanning more than N sections is not expanded and becomes a DANGLING-class UNCHECKED row (default %d)" % RANGE_INTERIOR_CAP)
441
+ ap.add_argument("--no-unchecked-verdict", "--no-cap-verdict", dest="no_cap_verdict", action="store_true",
442
+ help="ABLATION ONLY: a range whose interior cannot be enumerated (cap hit · mixed form) is a stderr "
443
+ "warning and stays clean (the v3/v4 arm); `--no-cap-verdict` is the older spelling")
444
+ ap.add_argument("--show-resolved", action="store_true", help="also list resolved refs")
445
+ ap.add_argument("--list-headings", action="store_true", help="print every parsed heading anchor")
446
+ ap.add_argument("--json", action="store_true")
447
+ args = ap.parse_args()
448
+ rxs = build_ref_regexes(not args.no_alt_spellings, not args.no_compact_range) \
449
+ + (not args.no_range_interior, args.range_cap, not args.no_cap_verdict)
450
+
451
+ defined, unnumbered, files = {}, 0, {}
452
+ for p in args.body:
453
+ try:
454
+ with open(p, encoding="utf-8", errors="replace") as fh:
455
+ files[p] = strip_html_comments(fh.read()).split("\n")
456
+ except OSError as e:
457
+ print("🟥 cannot read %s: %s" % (p, e), file=sys.stderr)
458
+ return 10
459
+ for p, lines in files.items():
460
+ fence = None # v8/v9: ``` and ~~~ fences via _fence_step (opener length · `> ` prefix)
461
+ for i, line in enumerate(lines, 1):
462
+ fence, on_fence = _fence_step(line, fence)
463
+ if on_fence or fence is not None:
464
+ continue
465
+ m = HEADING_RE.match(_fw(line))
466
+ if not m:
467
+ continue
468
+ k = parse_heading_key(m.group(2))
469
+ if k is None:
470
+ unnumbered += 1
471
+ else:
472
+ defined.setdefault(k, []).append((p, i, m.group(2)[:70]))
473
+ flag_defined = []
474
+ for d in args.define:
475
+ k = parse_ref_token(d)
476
+ if k is None:
477
+ print("🟥 --define %r is not a ref-shaped token" % d, file=sys.stderr)
478
+ return 10
479
+ flag_defined.append(k)
480
+ defined.setdefault(k, []).append(("--define", 0, d))
481
+ n_headings = sum(len(v) for v in defined.values()) - len(flag_defined) + unnumbered
482
+ if not defined:
483
+ n_refs_seen = sum(len(refs_in(l, rxs)) for lines in files.values() for l in lines
484
+ if not HEADING_RE.match(l) and not FENCE_RE.match(l.lstrip()))
485
+ print("🟥 0 numbered headings parsed from %d file(s) (%d unnumbered heading(s)); %d ref(s) seen and NOT reported as "
486
+ "dangling — wrong file or wrong heading shape. rc=10" % (len(files), unnumbered, n_refs_seen))
487
+ return 10
488
+
489
+ mapping = []
490
+ if args.map:
491
+ for pair in args.map.split(","):
492
+ if "=" not in pair:
493
+ print("🟥 --map entry %r is not OLD=NEW" % pair, file=sys.stderr)
494
+ return 10
495
+ o, n = pair.split("=", 1)
496
+ ko, kn = parse_ref_token(o), parse_ref_token(n)
497
+ if ko is None or kn is None:
498
+ print("🟥 --map entry %r: not ref-shaped" % pair, file=sys.stderr)
499
+ return 10
500
+ mapping.append((ko, kn))
501
+ ext_re = re.compile(args.external) if args.external else None
502
+
503
+ resolved, dangling, stale, external = [], [], [], []
504
+ for p, lines in files.items():
505
+ fence = None
506
+ for i, line in enumerate(lines, 1):
507
+ fence, on_fence = _fence_step(line, fence)
508
+ if on_fence:
509
+ continue
510
+ if fence is None and HEADING_RE.match(line):
511
+ continue # the heading's own number is a definition, not a reference
512
+ # (a `#` line INSIDE a fence is neither — its refs are scanned)
513
+ for key, disp, pos in refs_in(_fw(line), rxs):
514
+ snippet = line[max(0, pos - 45):pos + 60].strip()
515
+ rec = {"key": key, "ref": disp, "file": p, "line": i, "snippet": snippet}
516
+ old = next((o for o, n in mapping if is_under(key, o)), None)
517
+ if old is not None:
518
+ rec["old"], rec["new"] = old, dict(mapping)[old]
519
+ stale.append(rec)
520
+ continue
521
+ if key in defined:
522
+ resolved.append(rec)
523
+ continue
524
+ anc = [a for a in ancestors(key) if a in defined]
525
+ if args.parent_resolves and anc:
526
+ rec["via_parent"] = anc[0]
527
+ resolved.append(rec)
528
+ continue
529
+ if ext_re is not None and ext_re.search(line[max(0, pos - 80):pos + 80]):
530
+ rec["matched"] = ext_re.search(line[max(0, pos - 80):pos + 80]).group(0)
531
+ external.append(rec)
532
+ continue
533
+ rec["parent"] = anc[0] if anc else None
534
+ dangling.append(rec)
535
+ n_refs = len(resolved) + len(dangling) + len(stale) + len(external)
536
+ if n_refs == 0:
537
+ print("⬜ DEAD CONTROL — 0 cross-references found in %d file(s) (%d numbered heading(s) parsed; spellings scanned: %s); nothing was checked. rc=4 (not a clean check)."
538
+ % (len(files), len(defined) - len(flag_defined), spellings_text(not args.no_alt_spellings)))
539
+ return 4
540
+ rc = 1 if (dangling or stale) else 0
541
+
542
+ if args.json:
543
+ print(json.dumps({
544
+ "body": args.body, "defined": {k: [{"file": f, "line": n, "text": t} for f, n, t in v] for k, v in sorted(defined.items())},
545
+ "defined_by_flag": flag_defined, "external_regex": args.external, "map": mapping,
546
+ "parent_resolves": args.parent_resolves, "alt_spellings": not args.no_alt_spellings,
547
+ "spellings": spellings_text(not args.no_alt_spellings),
548
+ "dangling": dangling, "stale_old": stale, "external": external, "resolved": resolved,
549
+ "summary": {"headings": n_headings, "numbered": len(defined) - len(flag_defined), "refs": n_refs,
550
+ "distinct_refs": len({r["key"] for r in resolved + dangling + stale + external}),
551
+ "dangling": len(dangling), "stale_old": len(stale), "external": len(external),
552
+ "resolved": len(resolved), "rc": rc},
553
+ }, ensure_ascii=False, indent=1))
554
+ return rc
555
+
556
+ print("section-ref check · body=%d file%s · headings=%d (%d numbered anchors · %d unnumbered) · refs=%d (%d distinct)"
557
+ % (len(files), "" if len(files) == 1 else "s", n_headings, len(defined) - len(flag_defined), unnumbered,
558
+ n_refs, len({r["key"] for r in resolved + dangling + stale + external})))
559
+ print(" spellings: %s" % spellings_text(not args.no_alt_spellings))
560
+ print(" mechanisms: exact-match=%s · defined-by-flag=%s · external=%s · map=%s · range-interior=%s · compact-range=%s · range-cap=%d · unchecked-verdict=%s"
561
+ % ("off (ABLATION: parent resolves)" if args.parent_resolves else "on",
562
+ ", ".join(show(k) for k in flag_defined) if flag_defined else "(none)",
563
+ repr(args.external) if args.external else "(none)",
564
+ ", ".join("%s→%s" % (show(o), show(n)) for o, n in mapping) if mapping else "(none)",
565
+ "off (ABLATION)" if args.no_range_interior else "on",
566
+ "off (ABLATION)" if args.no_compact_range else "on",
567
+ args.range_cap, "off (ABLATION)" if args.no_cap_verdict else "on"))
568
+ if args.list_headings:
569
+ for k in sorted(defined, key=lambda x: [(0, int(t)) if t.isdigit() else (1, t) for t in re.split(r"[.:\-]", x)]):
570
+ for f, n, t in defined[k]:
571
+ print(" ▸ %-10s %s:%d %s" % (show(k), f.split("/")[-1], n, t))
572
+ for r in dangling:
573
+ why = ("parent %s exists" % show(r["parent"])) if r["parent"] else "no such top-level"
574
+ print(" 🟥 DANGLING %-10s %s:%d (%s) …%s…" % (r["ref"], r["file"].split("/")[-1], r["line"], why, r["snippet"]))
575
+ for r in stale:
576
+ print(" 🟥 STALE-OLD %-10s %s:%d (old %s → now %s) …%s…" % (r["ref"], r["file"].split("/")[-1], r["line"], show(r["old"]), show(r["new"]), r["snippet"]))
577
+ for r in external:
578
+ print(" ⬜ EXTERNAL %-10s %s:%d (matched %r) …%s…" % (r["ref"], r["file"].split("/")[-1], r["line"], r["matched"], r["snippet"]))
579
+ if args.show_resolved:
580
+ for r in resolved:
581
+ print(" ✅ resolved %-10s %s:%d%s" % (r["ref"], r["file"].split("/")[-1], r["line"],
582
+ (" (via parent %s — ABLATION)" % show(r["via_parent"])) if r.get("via_parent") else ""))
583
+ if dangling:
584
+ print("ⓘ a DANGLING ref is a pointer the reader cannot follow; «parent exists» usually means a sub-heading was removed or never written.")
585
+ print("section-ref verdict: DANGLING=%d STALE-OLD=%d EXTERNAL=%d RESOLVED=%d rc=%d"
586
+ % (len(dangling), len(stale), len(external), len(resolved), rc))
587
+ return rc
588
+
589
+
590
+ if __name__ == "__main__":
591
+ sys.exit(main())