@chrono-meta/fh-gate 3.11.0 → 3.13.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,389 @@
1
+ #!/usr/bin/env python3
2
+ """numeric_token_diff.py — did a rewrite / shrink pass DROP a number, or INVENT one?
3
+
4
+ WHAT IT CLOSES (measured 2026-09-17, paper-2 DRAFT → SUBMISSION shrink)
5
+ A shrink pass rewrites prose, and a number that lived only in a deleted sentence leaves with it —
6
+ silently, because nothing diffs the NUMBERS of two documents, only their lines. The governor did
7
+ this by hand with ad-hoc python. This tool extracts the MULTISET of numeric tokens on each side and
8
+ names every token that is only-in-before (DROPPED / REDUCED) or only-in-after (INVENTED /
9
+ INCREASED), with its count on both sides and the first line it appears on.
10
+
11
+ WHAT IT DOES NOT DO — read before trusting a 0
12
+ 🟥 It compares TOKENS, not claims. `92.6%` surviving the rewrite does not mean it still says what
13
+ it said; a number that moved from one claim to another is invisible here. Identity of form only.
14
+ 🟥 `0.80` and `0.8` are DIFFERENT tokens (precision is content); `2,880` and `2880` are the SAME
15
+ (thousands separators are stripped). `95 %`, `95%`, `95 %` (NBSP) are one token `95%`.
16
+ 🟥 Section numbers are NOT numbers: `§3.2`, `§3.1–3.2`, `Sec. 9.4`, `Section 3`, `섹션 8.1`, `3.2절`,
17
+ `부록 8`, `Appendix 3`, `K.2`, `A.6.2.7`, a heading's own numbering (`### 4.2 …`) and a list
18
+ marker (`1. `) are blanked BEFORE extraction — those are section_ref_check.py's domain (same
19
+ cross-reference grammar). Version-like strings (`2.7.1`, `12.7.3`) yield nothing by the
20
+ digit-boundary rule below.
21
+ 🟥 A number glued to a Latin letter (`v3`, `F_r2ctrl`, `A26`) is an identifier, not a claim, and is
22
+ skipped. A HYPHENATED CHAIN is judged as a whole (`--hyphen-rule word`, default): a chain that
23
+ carries a Latin letter anywhere is an identifier and sheds NO token (`s43681-022-00171-7`,
24
+ `GHSA-2026-1234`, `A-6`, `PREREG_ADDENDUM_2026-09-10`); a chain of pure digits is a RANGE and
25
+ keeps EVERY segment (`3-5` → 3 and 5, `12-25` → 12 and 25, `40-75` → 40 and 75), so a shrink pass
26
+ that erases the upper bound is a DROPPED, not a silent identical. 🟥 The 2026-09-17 rule blocked
27
+ any `<alnum>-` before a number — measured by cross-family review (codex) as a silent false
28
+ negative: «range 3-5 only» → «range 3 only» was IDENTICAL rc=0. It survives only as the ablation
29
+ arm `--hyphen-rule alnum`. `100-1` (NIST AI 100-1) is now two tokens — the price of the fix.
30
+ A number after a Hangul syllable (`8케이스`, `제3장`) is kept. `.5` (leading-dot decimal) is kept
31
+ as `.5` (v21 — it was `5`; a glued sign binds to it: `−.5` → `-.5`, codex round 19). A SIGN glued to the number is part of it (`−196` · `-196` · `–196` → `-196`) when nothing
32
+ word-like precedes it (start, whitespace, an opening bracket incl. full-width, or an operator
33
+ `= < > ≤ ≥ ≈ : ; , | / + * × ÷`) — so `−196` → `196` is a DROPPED + INVENTED pair, not IDENTICAL
34
+ (v19; codex round 17 fixture, silent in v1–v18 and documented as such — the reader sees the sign).
35
+ The sign survives a statistical prefix too: `p = −0.3` → `p=-0.3` (v20 — the v19 prefixed form
36
+ dropped it, codex round 18). `3-5` is still a range (the `-` follows a digit); `- 196` (a list
37
+ marker) is not a sign. Ablation arm: `--no-sign`. Numbers inside code spans / fences ARE
38
+ tokens (a DOI or a quoted `p<0.001` that disappears is still a drop).
39
+ 🟥 Multiset semantics by default: a common small integer (`3`) that appears 12× before and 9×
40
+ after is reported as REDUCED. That is correct and noisy — `--distinct` compares sets instead
41
+ (a token is DROPPED only when it vanishes entirely), and `--allow` justifies specific tokens.
42
+
43
+ DIGIT BOUNDARY (the discipline of scripts/claim_propagation_scan.py `compile_token`, applied to
44
+ extraction): a token may not be preceded by a digit, `digit.` or `digit,`, and may not be followed
45
+ by a digit, `.digit` or `,ddd`. So `2.7` is never produced from `2.75` or `12.7` (greedy match) and
46
+ nothing is produced from `2.7.1` or `12.7.3` (every start position is either digit-dot-preceded or
47
+ dot-digit-followed). `--no-digit-boundary` removes the lookarounds (ablation / revert probe): then
48
+ `2.7.1` yields `2.7` and `1`, `12.7.3` yields `12.7` and `3`, and `2,880` also sheds `880`.
49
+
50
+ TOKEN FORMS 2880 · 2.7 · 92.6% · 12/12 · p=0.019 · p<0.001 · n=6 · 2026-09-12 (a date is one token)
51
+
52
+ ALLOW FILE one `token<TAB>reason` per line, `#` comments. A line WITHOUT a reason is rejected
53
+ (rc=10) — an allow entry is a decision, and a bare token is a silencer.
54
+
55
+ EXIT CODES
56
+ 0 identical multisets (or every difference allowed)
57
+ 1 a token was DROPPED or REDUCED (before > after) — possibly with INVENTED ones too
58
+ 2 only INVENTED / INCREASED tokens (after > before)
59
+ 4 DEAD CONTROL: BOTH sides yield zero numeric tokens — distinct from 0 on purpose
60
+ 10 input error (file missing · allow file rejected)
61
+
62
+ USAGE
63
+ python3 scripts/numeric_token_diff.py --before <md...> --after <md...> [--allow <tsv>] [--distinct]
64
+ [--limit N] [--hyphen-rule word|alnum|off]
65
+ [--no-digit-boundary] [--json]
66
+ bash scripts/test_paper_integrity_lanes.sh # known pairs + revert probes
67
+ Python ≥ 3.9, stdlib only.
68
+ """
69
+ import argparse
70
+ import json
71
+ import re
72
+ import sys
73
+ from collections import Counter
74
+
75
+ WS = "[\\s   ]*"
76
+ # v21 (codex round 19): a leading-dot decimal is a number of its own (`.5`, `.05`) so a glued sign can bind to it
77
+ NUM = r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+"
78
+ PREFIX = r"(?:(?P<pre>p|n|N|k|CI|df|α|β)" + WS + r"(?P<op>=|<|>|≤|≥|≈)" + WS + r")?"
79
+ # v19 (codex round 17 fixture): a sign glued to the number — ASCII hyphen-minus, U+2212 MINUS, U+2013 EN DASH —
80
+ # is part of the token ONLY when what precedes it is nothing, whitespace, an opening bracket, or an operator —
81
+ # so `3-5` / `3–5` stay ranges, `x-5` stays an identifier, and a truncated DOI `…-00191-3` (the real paper,
82
+ # measured) stays the fragment `00191` it was; `(?=\d)` keeps a list marker `- 196` and a spaced dash `– 5` out.
83
+ # v20 (codex round 18): arithmetic operators (`+ * × ÷`) also license a sign — `x = y +−5` is a signed
84
+ # number — and full-width brackets are mapped to ASCII before extraction (`(−5)`).
85
+ SIGN = r"(?P<sign>(?<![^\s(\[{=<>≤≥≈:;,|/+*×÷])[-−–](?=\d|\.\d))?"
86
+ TAIL = r"(?:" + WS + r"(?P<pct>%)|/(?P<den>\d+(?:\.\d+)?)(?!\d)(?!\.\d))?"
87
+ # Left boundary: not glued to a Latin letter or digit, not `digit.` / `digit,` (a fraction or
88
+ # thousands tail). Right boundary: not followed by a digit, `.digit` or `,ddd`.
89
+ LEFT = r"(?<![A-Za-z\d])(?<!\d\.)(?<!\d,)"
90
+ LEFT_ALNUM_HYPHEN = r"(?<![A-Za-z0-9]-)" # the 2026-09-17 rule — ablation arm only (see header)
91
+ RIGHT = r"(?!\d)(?!\.\d)(?!,\d{3})"
92
+ DATE = r"(?P<date>\d{4}-\d{2}-\d{2})(?!\d)"
93
+ EXP = r"(?P<exp>[eE][+-]?\d+(?![A-Za-z])|[⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺]+|\^[+-]?\d+)?"
94
+ SUPER = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺", "0123456789-+")
95
+ FULLWIDTH = str.maketrans("0123456789%.,+-()[]{}", "0123456789%.,+-()[]{}")
96
+ SCI_CHAIN_RE = re.compile(r"^\d+(?:\.\d+)?[eE][+-]?\d+$")
97
+ HEADING_NUM_RE = re.compile(r"^(#{1,6}\s+)(?:§\s*)?(?:\d+(?:\.\d+)*(?:-?[a-z])?[.)]?|[A-Z](?:\.\d+)+|(?:부록|Appendix)\s*\S+)(?=\s|$)")
98
+ LIST_RE = re.compile(r"^(\s*)\d+[.)]\s")
99
+ # Cross-references are section_ref_check.py's domain — removed BEFORE extraction so `§3.1–3.2`,
100
+ # `Sec. 9.4`, `섹션 8.1`, `3.2절`, `부록 8`, `Appendix K.2`, `A.6.2.7` never shed a numeric token
101
+ # (same grammar as that tool).
102
+ SECTION_PREFIXES = ("§", "Sections", "Section", "sections", "section", "Sec.", "Sec", "섹션") # in step with section_ref_check.py (v6)
103
+ XREF_RE = re.compile(
104
+ r"(?<![A-Za-z])(?:" + "|".join(re.escape(p) for p in SECTION_PREFIXES) + r")"
105
+ r"\s*\d+(?:\.\d+)*(?:-?[a-z])?(?:(?:\s*[~–]\s*§?|\s*[—-]\s*§)\s*\d+(?:\.\d+)*(?:-?[a-z])?)?"
106
+ r"|(?<![\d.A-Za-z])\d+(?:\.\d+)*(?:-?[a-z])?절"
107
+ r"|(?:부록|Appendix|APPENDIX|appendix)\s*(?:\d+|[A-Z])(?:\.\d+(?:\.\d+)*)?(?![A-Za-z0-9])"
108
+ r"|(?<![A-Za-z0-9.§])[A-Z]\.\d+(?:\.\d+)*(?![A-Za-z0-9])")
109
+ # `word` hyphen rule: a hyphenated chain is judged as a whole.
110
+ HYPHEN_CHAIN_RE = re.compile(r"(?<![A-Za-z0-9_])[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)+(?![A-Za-z0-9_])")
111
+ LATIN_RE = re.compile(r"[A-Za-z]")
112
+
113
+
114
+ def build_regex(boundary, hyphen_rule, sign=True):
115
+ left = LEFT if boundary else r"(?<![A-Za-z])"
116
+ if hyphen_rule == "alnum":
117
+ left += LEFT_ALNUM_HYPHEN
118
+ right = RIGHT if boundary else r""
119
+ # v13 (codex round 12): an EXPONENT is part of the number — `2e6`, `2.5E-3`, `10⁶`, `10⁻³`, `10^6` — so a
120
+ # changed magnitude is a changed token (v12 reduced `2e6` and `2e5` both to `2`).
121
+ # v19: a glued sign is part of the number (`--no-sign` = the v1–v18 reading, ablation arm).
122
+ sgn = SIGN if sign else r"(?P<sign>)"
123
+ return re.compile(left + r"(?:" + DATE + r"|" + PREFIX + sgn + r"(?P<num>" + NUM + r")" + EXP + right + TAIL + r")")
124
+
125
+
126
+ def normalise(m):
127
+ if m.group("date"):
128
+ return m.group("date")
129
+ num = m.group("num").replace(",", "")
130
+ if m.group("exp"):
131
+ e = m.group("exp")
132
+ num += ("e" + e[1:].lstrip("+")) if e[0] in "eE" else ("^" + e.translate(SUPER).lstrip("^").lstrip("+"))
133
+ tok = ("-" + num) if m.group("sign") else num
134
+ if m.group("pre"):
135
+ # v20 (codex round 18): the prefixed form rebuilt the token from the unsigned `num` — `p = −0.3` → `p = 0.3` read IDENTICAL.
136
+ tok = m.group("pre") + m.group("op") + tok
137
+ if m.group("pct"):
138
+ tok += "%"
139
+ elif m.group("den"):
140
+ tok += "/" + m.group("den")
141
+ return tok
142
+
143
+
144
+ def blank(m):
145
+ return " " * (m.end() - m.start())
146
+
147
+
148
+ def strip_structure(line, hyphen_rule):
149
+ """Remove a heading's own numbering, a list marker, every cross-reference and (word rule) every
150
+ letter-bearing hyphenated chain — structure and identifiers, not claims. Replacement is by
151
+ equal-length blanks so match offsets still index the original line."""
152
+ m = HEADING_NUM_RE.match(line)
153
+ if m:
154
+ line = line[:len(m.group(1))] + " " * (m.end() - len(m.group(1))) + line[m.end():]
155
+ m = LIST_RE.match(line)
156
+ if m:
157
+ line = " " * m.end() + line[m.end():]
158
+ line = XREF_RE.sub(blank, line)
159
+ if hyphen_rule == "word":
160
+ line = HYPHEN_CHAIN_RE.sub(lambda x: blank(x) if LATIN_RE.search(x.group(0)) and not SCI_CHAIN_RE.match(x.group(0)) else x.group(0), line)
161
+ return line
162
+
163
+
164
+ CODE_SPAN_MASK_RE = re.compile(r"`[^`\n]*`")
165
+
166
+
167
+ FENCE_RE = re.compile(r"^(?:>\s*)*(`{3,}|~{3,})(.*)$")
168
+
169
+
170
+ def _fence_step(line, fence):
171
+ """→ (fence_after, on_fence_line). `fence` = (char, opener length) while inside a fenced block, else
172
+ None. v9 (codex round 8) — CommonMark: a closer uses the same char, is at least as long as the
173
+ opener and carries nothing but spaces after it (a 3-tick line does not close a 4-tick fence); a
174
+ `> ` prefix is allowed (a fence inside a blockquote). Kept byte-identical across the three tools."""
175
+ m = FENCE_RE.match(line.lstrip())
176
+ if fence is None:
177
+ return ((m.group(1)[0], len(m.group(1))), True) if m else (None, False)
178
+ if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= fence[1] and not m.group(2).strip():
179
+ return None, True
180
+ return fence, False
181
+
182
+
183
+ def strip_html_comments(text):
184
+ """v6 (codex round 5): text inside `<!-- … -->` is invisible to the reader, so it is neither a defect
185
+ nor an anchor. 🟥 v7 (codex round 6): the v6 regex strip ERASED PROSE between a `<!--` and a `-->`
186
+ that sat inside code spans or fenced blocks — a delimiter inside code is a literal. 🟥 v8 (codex
187
+ round 7): the same for `~~~` fences and 4-space / tab INDENTED code blocks (a block starts after a
188
+ blank line and runs while lines stay indented). v9: fences go through _fence_step (opener length ·
189
+ blockquote prefix). Fences and indented code are left untouched, code spans are masked before a
190
+ delimiter is looked for. Line numbers are preserved; comment text becomes spaces. Kept
191
+ byte-identical in the three tools (lanes L11l / L11o / L11q pin all three)."""
192
+ out, fence, in_comment, prev_blank, prev_code = [], None, False, True, False
193
+ for line in text.split("\n"):
194
+ if in_comment:
195
+ j = line.find("-->")
196
+ if j < 0:
197
+ out.append(" " * len(line))
198
+ continue
199
+ line, in_comment = " " * (j + 3) + line[j + 3:], False
200
+ s = line.strip()
201
+ fence, on_fence = _fence_step(line, fence)
202
+ if on_fence or fence is not None:
203
+ out.append(line)
204
+ prev_blank, prev_code = False, False
205
+ continue
206
+ indented = (line.startswith(" ") or line.startswith("\t")) and (prev_blank or prev_code)
207
+ if indented:
208
+ out.append(line)
209
+ prev_blank, prev_code = False, True
210
+ continue
211
+ prev_blank, prev_code = (s == ""), False
212
+ masked = CODE_SPAN_MASK_RE.sub(lambda m: " " * len(m.group(0)), line)
213
+ res, pos = [], 0
214
+ while True:
215
+ i = masked.find("<!--", pos)
216
+ if i < 0:
217
+ res.append(line[pos:])
218
+ break
219
+ res.append(line[pos:i])
220
+ j = line.find("-->", i + 4)
221
+ if j < 0:
222
+ res.append(" " * (len(line) - i))
223
+ in_comment = True
224
+ break
225
+ res.append(" " * (j + 3 - i))
226
+ pos = j + 3
227
+ out.append("".join(res))
228
+ return "\n".join(out)
229
+
230
+
231
+ def extract(paths, rx, hyphen_rule):
232
+ """→ (Counter of tokens, {token: (file, line, snippet) first site}, lines read) — rc=10 shape on error."""
233
+ counts, first, n_lines = Counter(), {}, 0
234
+ for p in paths:
235
+ try:
236
+ with open(p, encoding="utf-8", errors="replace") as fh:
237
+ # a number moved INTO a comment has been dropped from the reader's view (loud)
238
+ lines = strip_html_comments(fh.read()).split("\n")
239
+ except OSError as e:
240
+ return None, "cannot read %s: %s" % (p, e), 0
241
+ n_lines += len(lines)
242
+ for i, raw in enumerate(lines, 1):
243
+ # v17 (codex round 16): full-width digits / percent / dot / comma are the reader's ASCII ones
244
+ # (`92.6%` = `92.6%`). A per-character map, NOT NFKC — NFKC would also fold `10⁶` to `106`.
245
+ raw = raw.translate(FULLWIDTH)
246
+ line = strip_structure(raw, hyphen_rule)
247
+ for m in rx.finditer(line):
248
+ tok = normalise(m)
249
+ counts[tok] += 1
250
+ if tok not in first:
251
+ a = max(0, m.start() - 45)
252
+ first[tok] = (p, i, raw[a:m.end() + 45].strip())
253
+ return counts, first, n_lines
254
+
255
+
256
+ def read_allow(path):
257
+ """→ ({token: reason}, error-or-None). A bare token (no TAB / empty reason) is an error."""
258
+ allow = {}
259
+ try:
260
+ with open(path, encoding="utf-8") as fh:
261
+ for n, raw in enumerate(fh, 1):
262
+ line = raw.rstrip("\n")
263
+ if not line.strip() or line.lstrip().startswith("#"):
264
+ continue
265
+ if "\t" not in line:
266
+ return None, "allow file %s:%d — bare token with no reason (expected token<TAB>reason): %r" % (path, n, line)
267
+ tok, reason = line.split("\t", 1)
268
+ tok = tok.strip().replace(",", "").replace(" ", "")
269
+ if not tok or not reason.strip():
270
+ return None, "allow file %s:%d — empty token or empty reason: %r" % (path, n, line)
271
+ allow[tok] = reason.strip()
272
+ except OSError as e:
273
+ return None, "cannot read allow file %s: %s" % (path, e)
274
+ return allow, None
275
+
276
+
277
+ def main():
278
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
279
+ ap.add_argument("--before", nargs="+", required=True, metavar="MD")
280
+ ap.add_argument("--after", nargs="+", required=True, metavar="MD")
281
+ ap.add_argument("--allow", metavar="TSV", help="token<TAB>reason per line — justified differences")
282
+ ap.add_argument("--distinct", action="store_true", help="set semantics: only tokens that vanish / appear entirely")
283
+ ap.add_argument("--limit", type=int, default=0, help="rows printed per class (0 = all)")
284
+ ap.add_argument("--hyphen-rule", choices=["word", "alnum", "off"], default="word",
285
+ help="word (default): a letter-bearing hyphen chain is an identifier, a pure-digit chain is a range · "
286
+ "alnum: the 2026-09-17 rule, any <alnum>- blocks the number (ABLATION — silent on `3-5` → `3`) · "
287
+ "off: no hyphen handling (DOI suffixes shed fragments)")
288
+ ap.add_argument("--no-digit-boundary", action="store_true", help="drop the digit-boundary lookarounds (ablation / revert probe)")
289
+ ap.add_argument("--no-sign", action="store_true", help="the v1–v18 reading: a glued sign is not part of the number (ablation — silent on `−196` → `196`)")
290
+ ap.add_argument("--json", action="store_true")
291
+ args = ap.parse_args()
292
+
293
+ rx = build_regex(not args.no_digit_boundary, args.hyphen_rule, not args.no_sign)
294
+ allow = {}
295
+ if args.allow:
296
+ allow, err = read_allow(args.allow)
297
+ if err:
298
+ print("🟥 " + err, file=sys.stderr)
299
+ return 10
300
+ b_counts, b_first, b_lines = extract(args.before, rx, args.hyphen_rule)
301
+ if b_counts is None:
302
+ print("🟥 " + b_first, file=sys.stderr)
303
+ return 10
304
+ a_counts, a_first, a_lines = extract(args.after, rx, args.hyphen_rule)
305
+ if a_counts is None:
306
+ print("🟥 " + a_first, file=sys.stderr)
307
+ return 10
308
+
309
+ nb, na = sum(b_counts.values()), sum(a_counts.values())
310
+ if nb == 0 and na == 0:
311
+ print("⬜ DEAD CONTROL — 0 numeric tokens on BOTH sides (before: %d line(s), after: %d line(s)); nothing was compared. rc=4 (not identical)."
312
+ % (b_lines, a_lines))
313
+ return 4
314
+
315
+ dropped, reduced, invented, increased, allowed = [], [], [], [], []
316
+ for tok in sorted(set(b_counts) | set(a_counts)):
317
+ b, a = b_counts.get(tok, 0), a_counts.get(tok, 0)
318
+ if b == a:
319
+ continue
320
+ if tok in allow:
321
+ allowed.append((tok, b, a, allow[tok]))
322
+ continue
323
+ if a == 0:
324
+ dropped.append((tok, b, a))
325
+ elif b == 0:
326
+ invented.append((tok, b, a))
327
+ elif not args.distinct:
328
+ (reduced if b > a else increased).append((tok, b, a))
329
+ unused_allow = sorted(t for t in allow if b_counts.get(t, 0) == a_counts.get(t, 0))
330
+ for lst in (dropped, reduced, invented, increased):
331
+ lst.sort(key=lambda t: (-abs(t[1] - t[2]), t[0]))
332
+ rc = 1 if (dropped or reduced) else (2 if (invented or increased) else 0)
333
+
334
+ def site(tok, side):
335
+ f, n, s = (b_first if side == "b" else a_first)[tok]
336
+ return "%s:%d: %s" % (f.split("/")[-1], n, s)
337
+
338
+ if args.json:
339
+ print(json.dumps({
340
+ "before": args.before, "after": args.after, "distinct": args.distinct,
341
+ "digit_boundary": not args.no_digit_boundary, "hyphen_rule": args.hyphen_rule, "sign": not args.no_sign, "allow": args.allow,
342
+ "stats": {"before": {"tokens": nb, "distinct": len(b_counts), "lines": b_lines},
343
+ "after": {"tokens": na, "distinct": len(a_counts), "lines": a_lines}},
344
+ "dropped": [{"token": t, "before": b, "after": a, "first": site(t, "b")} for t, b, a in dropped],
345
+ "reduced": [{"token": t, "before": b, "after": a, "first_before": site(t, "b")} for t, b, a in reduced],
346
+ "invented": [{"token": t, "before": b, "after": a, "first": site(t, "a")} for t, b, a in invented],
347
+ "increased": [{"token": t, "before": b, "after": a, "first_after": site(t, "a")} for t, b, a in increased],
348
+ "allowed": [{"token": t, "before": b, "after": a, "reason": r} for t, b, a, r in allowed],
349
+ "unused_allow": unused_allow,
350
+ "summary": {"dropped": len(dropped), "reduced": len(reduced), "invented": len(invented),
351
+ "increased": len(increased), "allowed": len(allowed), "rc": rc},
352
+ }, ensure_ascii=False, indent=1))
353
+ return rc
354
+
355
+ print("numeric-token diff · before=%d file%s (%d lines · %d tokens · %d distinct) · after=%d file%s (%d lines · %d tokens · %d distinct)"
356
+ % (len(args.before), "" if len(args.before) == 1 else "s", b_lines, nb, len(b_counts),
357
+ len(args.after), "" if len(args.after) == 1 else "s", a_lines, na, len(a_counts)))
358
+ print(" mechanisms: digit-boundary=%s · hyphen-rule=%s · sign=%s · semantics=%s · allow=%s"
359
+ % ("off" if args.no_digit_boundary else "on", args.hyphen_rule, "off" if args.no_sign else "on",
360
+ "distinct" if args.distinct else "multiset",
361
+ ("%s (%d entries)" % (args.allow, len(allow))) if args.allow else "(none)"))
362
+ if nb == 0 or na == 0:
363
+ print(" ⚠️ one side yielded 0 tokens (before=%d, after=%d) — an empty side is a suspicious input, not a clean diff" % (nb, na))
364
+
365
+ def show(label, glyph, rows, side):
366
+ shown = rows if args.limit == 0 else rows[:args.limit]
367
+ for t, b, a in shown:
368
+ print(" %s %-9s %-16s before ×%-3d → after ×%-3d %s" % (glyph, label, t, b, a, site(t, side)))
369
+ if len(shown) < len(rows):
370
+ print(" … %d more %s row(s) (--limit 0 for all)" % (len(rows) - len(shown), label))
371
+
372
+ show("DROPPED", "🟥", dropped, "b")
373
+ show("REDUCED", "🟧", reduced, "b")
374
+ show("INVENTED", "🟦", invented, "a")
375
+ show("INCREASED", "🟦", increased, "a")
376
+ for t, b, a, r in allowed:
377
+ print(" ⬜ ALLOWED %-16s before ×%-3d → after ×%-3d reason: %s" % (t, b, a, r))
378
+ for t in unused_allow:
379
+ print(" ⚠️ UNUSED-ALLOW %-13s no difference on this token — the allow entry is stale" % t)
380
+ if rc == 0:
381
+ print("ⓘ IDENTICAL numeric multisets — %d tokens (%d distinct) on each side%s."
382
+ % (nb, len(b_counts), " after %d allowed difference(s)" % len(allowed) if allowed else ""))
383
+ print("numeric-diff verdict: DROPPED=%d REDUCED=%d INVENTED=%d INCREASED=%d ALLOWED=%d rc=%d"
384
+ % (len(dropped), len(reduced), len(invented), len(increased), len(allowed), rc))
385
+ return rc
386
+
387
+
388
+ if __name__ == "__main__":
389
+ sys.exit(main())