@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,499 @@
1
+ #!/usr/bin/env python3
2
+ """claim_propagation_scan.py — a RETRACTED number that some other file still asserts as live.
3
+
4
+ WHAT IT CLOSES (measured 2026-09-17, the five-arm retraction, PR #743)
5
+ A numeric claim («2.7 %–13.6 %», «five review arms») was retracted in its canon file and had
6
+ already been copied into two more — the resident CLAUDE.md carried it at two sites. Neither
7
+ existing instrument could see it: scripts/halffix_propagation_scan.sh anchors on identifiers of
8
+ 10+ chars or path literals and reads the STAGED DIFF, not a retraction list;
9
+ scripts/novelty_claim_check.sh matches absence/novelty phrases — a different claim class.
10
+ This scanner takes a list of retracted TOKENS and names every file:line that still asserts one
11
+ of them OUTSIDE a retraction context.
12
+ Calibration (prototype, same day): the pre-retraction tree fired 13/13 known sites — both
13
+ CLAUDE.md sites among them; the post-retraction tree fired 0 on CLAUDE.md, every site classified
14
+ as retraction context. The lane suite (scripts/test_claim_propagation_lanes.sh) reconstructs both
15
+ arms as fixture files, so it does not depend on git history at lane time.
16
+
17
+ WHAT IT DOES NOT DO — read before trusting a 0
18
+ 🟥 PROSE-claim retractions are OUT OF SCOPE. Measured 0/8 precision on a prose claim («0 lines
19
+ of validation code»): word tokens that are not a specific figure flood on their own — a flood
20
+ generator, not an instrument. Feed it numbers and short literal phrases only.
21
+ 🟥 The ⓑ retraction vocabulary (DEFAULT_MARKERS) is a FROZEN JUDGMENT — the words this repo has
22
+ used to retract things, euphemisms included (`초판`, `replaced`, `the earlier`, `인용하지
23
+ 마라`). Ablation: dropping three English euphemisms turned 3 excluded sites LIVE. A retraction
24
+ phrased in wording not on the list is reported LIVE (loud direction); a genuinely live sentence
25
+ that sits within ±200 chars of any marker is excluded (silent direction). Both are properties
26
+ of the vocabulary, not of the corpus. `--markers` overrides it, `--strict-markers` narrows it.
27
+ 🟥 EXCLUDED CLASSES are a CLASSIFICATION, not a corpus cut. Two file classes hold the retracted
28
+ figure legitimately: RECORD class — a dated dispatch-log / ledger line is «what was done that
29
+ day», not a claim (`knowledge/shared/learnings/*_log.yaml`); FIXTURE class — a lane suite
30
+ carries the retracted figure as its known-positive by construction (`scripts/test_*_lanes.sh`,
31
+ measured: this scanner's own suite = 44 would-be-LIVE sites). Both are excluded by DEFAULT,
32
+ and exclusion means: the file IS scanned, its would-be-LIVE hits are counted as
33
+ EXCLUDED-FILE — printed in every verdict line, listed by `--show-excluded`, never LIVE and
34
+ never in rc. A first version skipped those files entirely, which HID a live claim sitting in
35
+ an excluded file (cross-family review, 2026-09-17); visible-not-silent is the fix. `--exclude`
36
+ adds patterns; `--no-default-exclude` drops the defaults so those hits count as LIVE.
37
+ 🟥 It judges FORM, not truth. A LIVE hit means «this token is asserted here with no retraction
38
+ marker nearby»; the reader decides whether the sentence is the retracted claim. Advisory by
39
+ decision (governor, 2026-09-17): MARK, never BLOCK — not wired into pre-commit.
40
+
41
+ MECHANISMS (each independently switchable so a known pair can ablate it)
42
+ nfkc corpus lines, tokens, anchor and marker regexes are NFKC-normalized before matching —
43
+ full-width `2.7%` and `B-1` become their ASCII forms. Without it a full-width copy
44
+ of a retracted figure is SILENT (cross-family review found exactly that:
45
+ `2.7 % claim-error` → bare=0). Measured scope: the delta is DIGITS and `%`; an
46
+ ideographic / no-break space between token parts is already matched by the FORM's `\\s`
47
+ without NFKC (lane L11r). Side effect, named: snippets print the normalized text
48
+ (`ⓐ`→`a`, `①`→`1`); a regex containing `…` becomes `...`. `--no-nfkc` disables.
49
+ form token FORM + digit boundary — `2.7 %` matches `2.7%` / `2.7 %`, never `12.7 %` or
50
+ `2.75 %`; a word token needs letter boundaries; parts are joined by optional
51
+ whitespace INCLUDING a line break inside a block. The largest reducer measured
52
+ (naive `2\\.7` = 131 lines → 8). Not switchable: it IS the token.
53
+ ⓐ anchor a token counts as a CLAIM SITE only if the claims file's anchor regex occurs within ±N
54
+ chars in the same block. Decorative for `%`-bearing tokens, LOAD-BEARING for bare
55
+ numbers — and only with CLAIM-SPECIFIC anchors (오류율|error rate|claim-error|B-1|
56
+ 최저|최고 …); generic ones (팔|arm|five) flood on `3/3`.
57
+ ⓑ retract a hit whose ±N-char window, or whose block's caption line, carries a retraction marker
58
+ is RETRACTION-CONTEXT, not live. Removed 15/16 post-retraction sites in calibration.
59
+ The revert probe (lane L7) shows this one is load-bearing, not decorative.
60
+ ⓒ′ form-rule (ON) a BARE token — no anchor — that is purely numeric is REFUSED: reported with
61
+ its bare counts, never scanned. Rarity today is not specificity (`12/12` was 8 lines
62
+ here and every one unrelated). Loud: rc=3 PARTIAL.
63
+ ⓒ ubiquity (secondary) a BARE token above the frequency thresholds is REFUSED the same way.
64
+ ⓓ quote (OFF) a token inside «…» 「…」 “…” "…" `…` is a MENTION. Measured as silent-direction
65
+ (it swallows the known-positive), so it is opt-in only.
66
+
67
+ COUNTING UNIT — one unit for every column. `bare` = occurrences of the token in block text (the
68
+ same text pass 2 classifies), `files` = files with ≥1. For every scanned (non-refused) token:
69
+ bare == LIVE + EXCLUDED-FILE + RETRACTION-CONTEXT + NO-ANCHOR + MENTION (lane L14)
70
+ A first version counted `bare` per LINE and LIVE per BLOCK, so a token wrapped across a line break
71
+ or repeated on one line made the two columns disagree (bare=1, LIVE=2).
72
+ Unit of context = a BLOCK: a blank-line-delimited paragraph, or one fenced ``` block. Windows are
73
+ measured in chars over the flattened block, so a marker one wrapped line above still counts and a
74
+ marker at the far end of a 1,500-char table row does not.
75
+
76
+ CLAIMS FILE `token<TAB>anchor-regex<TAB>source` per line; `#` comments; empty anchor = bare token.
77
+ EXCLUDES fnmatch against the root-relative path (`/` separators; `*` crosses `/`).
78
+
79
+ EXIT CODES
80
+ 0 scanned, no live propagation 2 LIVE propagation found (ADVISORY — mark, not block)
81
+ 3 a token was REFUSED (ⓒ′/ⓒ) and nothing live — PARTIAL scan, NOT a clean-corpus verdict
82
+ 4 DEAD CONTROL: zero tokens parsed — distinct from 0 on purpose (not found ≠ 0)
83
+ 10 input error (claims file missing · empty corpus)
84
+ EXCLUDED-FILE never changes rc; it is always in the verdict line so it cannot hide.
85
+
86
+ USAGE
87
+ python3 scripts/claim_propagation_scan.py --claims <tsv> --root <dir> [--paths P ...] [options]
88
+ bash scripts/test_claim_propagation_lanes.sh # known pairs + revert probes
89
+ Corpus = `git ls-files` under --root when it is a checkout (untracked files are NOT scanned),
90
+ else a filesystem walk; `--untracked` forces the walk. `--quiet` keeps the exclusion lines and the
91
+ verdict line — those two are never silenced. Python ≥ 3.9, stdlib only.
92
+ """
93
+ import argparse
94
+ import fnmatch
95
+ import glob
96
+ import json
97
+ import os
98
+ import re
99
+ import subprocess
100
+ import sys
101
+ import unicodedata
102
+
103
+ WS = r"[\s ]*" # whitespace incl. NBSP / thin / narrow-NBSP — `2.7 %`, `2.7%`, `2.7 %` are one token
104
+
105
+ DEFAULT_MARKERS = (
106
+ r"철회|RETRACT|retract|withdraw|supersed|replaced|초판|종전|옛|the earlier|no longer|~~|"
107
+ r"defective|obsolete|폐기|인용하지 마라|do not cite|used to (read|say|cite)"
108
+ )
109
+ STRICT_MARKERS = r"철회|RETRACT|retract|withdrawn|superseded|~~"
110
+
111
+ # Excluded CLASSES (pattern, label). Files matching these are scanned; their would-be-LIVE hits are
112
+ # counted as EXCLUDED-FILE. See the header: record class (a ledger line is a record, not a claim) and
113
+ # fixture class (a lane suite carries the retracted figure as its known-positive by construction).
114
+ DEFAULT_EXCLUDES = [
115
+ ("knowledge/shared/learnings/*_log.yaml", "record class"),
116
+ ("scripts/test_*_lanes.sh", "fixture class"),
117
+ ]
118
+
119
+ NFKC_ON = True # ablation switch — `--no-nfkc` turns it off; lane L11's revert probe flips this line in a copy
120
+
121
+ QUOTE_RE = re.compile(r"«[^»\n]{0,300}»|「[^」\n]{0,300}」|“[^”\n]{0,300}”|\"[^\"\n]{0,300}\"|`[^`\n]{0,300}`")
122
+ NUMERIC_FORM_RE = re.compile(r"[\d.,/%\s–—-]+")
123
+
124
+
125
+ def norm(s):
126
+ """NFKC-normalize when enabled — applied to corpus lines, tokens, anchor and marker regexes alike."""
127
+ return unicodedata.normalize("NFKC", s) if NFKC_ON else s
128
+
129
+
130
+ def compile_token(tok):
131
+ """Token FORM: literal parts joined by optional whitespace, with digit / letter / hangul boundaries."""
132
+ t = norm(tok.strip())
133
+ parts = re.split(r"\s+", t)
134
+ pat = WS.join(re.escape(p) for p in parts)
135
+ first, last = t[0], t[-1]
136
+ pre = post = ""
137
+ if first.isdigit():
138
+ pre = r"(?<![\d.])"
139
+ elif re.match(r"[A-Za-z]", first):
140
+ pre = r"(?<![A-Za-z])"
141
+ elif re.match(r"[가-힣]", first):
142
+ pre = r"(?<![가-힣])"
143
+ if last.isdigit():
144
+ post = r"(?!\d)(?!\.\d)"
145
+ elif re.match(r"[A-Za-z]", last):
146
+ post = r"(?![A-Za-z])"
147
+ return re.compile(pre + pat + post)
148
+
149
+
150
+ def read_claims(path):
151
+ claims = []
152
+ with open(path, encoding="utf-8") as fh:
153
+ for raw in fh:
154
+ line = raw.rstrip("\n")
155
+ if not line.strip() or line.lstrip().startswith("#"):
156
+ continue
157
+ cols = line.split("\t")
158
+ tok = cols[0].strip()
159
+ anchor = norm(cols[1].strip()) if len(cols) > 1 else ""
160
+ src = cols[2].strip() if len(cols) > 2 else ""
161
+ if not tok:
162
+ continue
163
+ claims.append({"token": tok, "anchor": anchor, "source": src, "re": compile_token(tok),
164
+ "anchor_re": re.compile(anchor) if anchor else None})
165
+ return claims
166
+
167
+
168
+ def list_corpus(root, paths, tracked):
169
+ files = []
170
+ if tracked and os.path.isdir(os.path.join(root, ".git")):
171
+ cmd = ["git", "-C", root, "ls-files", "--"] + (paths or ["."])
172
+ out = subprocess.run(cmd, capture_output=True, text=True, check=False).stdout
173
+ files = [os.path.join(root, f) for f in out.splitlines() if f]
174
+ else:
175
+ for b in (paths or ["."]):
176
+ p = os.path.join(root, b)
177
+ if os.path.isfile(p):
178
+ files.append(p)
179
+ elif os.path.isdir(p):
180
+ for d, dirs, fs in os.walk(p):
181
+ dirs[:] = [x for x in dirs if x != ".git"] # prune only .git itself, never .github
182
+ for f in fs:
183
+ files.append(os.path.join(d, f))
184
+ else:
185
+ files.extend(glob.glob(os.path.join(root, b))) # README* etc.
186
+ out = []
187
+ for f in sorted(set(files)):
188
+ try:
189
+ with open(f, "rb") as fh:
190
+ head = fh.read(8192)
191
+ except OSError:
192
+ continue
193
+ if b"\0" in head:
194
+ continue
195
+ out.append(f)
196
+ return out
197
+
198
+
199
+ def rel_of(f, root):
200
+ return os.path.relpath(f, root).replace(os.sep, "/")
201
+
202
+
203
+ def classify_excludes(files, root, patterns):
204
+ """→ (labels: rel → class label, per_pattern: [(pattern, label, [rels])]). No file is dropped."""
205
+ labels = {}
206
+ per_pattern = []
207
+ for pat, label in patterns:
208
+ matched = []
209
+ for f in files:
210
+ rel = rel_of(f, root)
211
+ if fnmatch.fnmatchcase(rel, pat):
212
+ matched.append(rel)
213
+ labels.setdefault(rel, label)
214
+ per_pattern.append((pat, label, matched))
215
+ return labels, per_pattern
216
+
217
+
218
+ def load_lines(f):
219
+ try:
220
+ with open(f, encoding="utf-8", errors="replace") as fh:
221
+ return [norm(l) for l in fh.read().split("\n")] # per line, so line numbers stay exact
222
+ except OSError:
223
+ return None
224
+
225
+
226
+ def split_blocks(lines):
227
+ """Blocks = list of (lineno, text) lists; blank-line paragraphs, or one fenced ``` block each."""
228
+ blocks, cur, in_fence = [], [], False
229
+ for i, l in enumerate(lines, 1):
230
+ s = l.strip()
231
+ if s.startswith("```"):
232
+ if in_fence:
233
+ cur.append((i, l)); blocks.append(cur); cur = []; in_fence = False
234
+ else:
235
+ if cur:
236
+ blocks.append(cur); cur = []
237
+ in_fence = True; cur.append((i, l))
238
+ continue
239
+ if in_fence:
240
+ cur.append((i, l)); continue
241
+ if s == "":
242
+ if cur:
243
+ blocks.append(cur); cur = []
244
+ continue
245
+ cur.append((i, l))
246
+ if cur:
247
+ blocks.append(cur)
248
+ return blocks
249
+
250
+
251
+ def block_text(block):
252
+ text = "\n".join(l for _, l in block)
253
+ offsets, pos = [], 0
254
+ for _, l in block:
255
+ offsets.append(pos)
256
+ pos += len(l) + 1
257
+ return text, offsets
258
+
259
+
260
+ def line_of(offsets, block, off):
261
+ idx = 0
262
+ for k, o in enumerate(offsets):
263
+ if o <= off:
264
+ idx = k
265
+ else:
266
+ break
267
+ return block[idx][0], idx
268
+
269
+
270
+ def caption_line(block):
271
+ """First content line of the block (for a fence: the first line after ```)."""
272
+ if block and block[0][1].strip().startswith("```") and len(block) > 1:
273
+ return block[1][1]
274
+ return block[0][1] if block else ""
275
+
276
+
277
+ def in_scope_text(text, offsets, block, m, scope, nchars):
278
+ if scope == "line":
279
+ _, idx = line_of(offsets, block, m.start())
280
+ return block[idx][1]
281
+ if scope == "block":
282
+ return text
283
+ a = max(0, m.start() - nchars)
284
+ b = min(len(text), m.end() + nchars)
285
+ return text[a:b]
286
+
287
+
288
+ def scan(claims, files, root, excluded, args):
289
+ marker_re = re.compile(norm(args.markers))
290
+ per_token = {c["token"]: {"token": c["token"], "anchor": c["anchor"], "source": c["source"],
291
+ "bare": 0, "bare_files": set(), "live": [], "excluded_file": [],
292
+ "retraction": [], "no_anchor": [], "mention": [], "refused": ""} for c in claims}
293
+ # one read per file; blocks are the unit for BOTH passes (bare and classification)
294
+ docs = []
295
+ for f in files:
296
+ lines = load_lines(f)
297
+ if lines is None:
298
+ continue
299
+ rel = rel_of(f, root)
300
+ blocks = []
301
+ for b in split_blocks(lines):
302
+ text, offsets = block_text(b)
303
+ blocks.append((b, text, offsets, caption_line(b)))
304
+ docs.append((rel, excluded.get(rel, ""), blocks))
305
+ # pass 1 — bare occurrences (report columns + ⓒ), same regex on the same block text as pass 2
306
+ for rel, _, blocks in docs:
307
+ for c in claims:
308
+ n = sum(sum(1 for _ in c["re"].finditer(text)) for _, text, _, _ in blocks)
309
+ if n:
310
+ rec = per_token[c["token"]]
311
+ rec["bare"] += n
312
+ rec["bare_files"].add(rel)
313
+ # ⓒ′ FORM rule first (primary), ⓒ frequency guard second — both only for BARE tokens.
314
+ for c in claims:
315
+ rec = per_token[c["token"]]
316
+ if c["anchor"]:
317
+ continue
318
+ if not args.no_form_rule and NUMERIC_FORM_RE.fullmatch(norm(c["token"])) is not None:
319
+ rec["refused"] = "form"
320
+ elif not args.no_ubiquity and (rec["bare"] > args.ubiquity_max_occ
321
+ or len(rec["bare_files"]) > args.ubiquity_max_files):
322
+ rec["refused"] = "ubiquity"
323
+ # pass 2 — classification
324
+ for rel, exlabel, blocks in docs:
325
+ for block, text, offsets, cap in blocks:
326
+ quotes = [(q.start(), q.end()) for q in QUOTE_RE.finditer(text)] if args.quote_excl else []
327
+ for c in claims:
328
+ rec = per_token[c["token"]]
329
+ if rec["refused"]:
330
+ continue
331
+ for m in c["re"].finditer(text):
332
+ ln, _ = line_of(offsets, block, m.start())
333
+ sa, sb = max(0, m.start() - 70), min(len(text), m.end() + 70)
334
+ hit = {"file": rel, "line": ln, "snippet": text[sa:sb].replace("\n", "⏎"), "why": ""}
335
+ # ⓓ
336
+ if quotes and any(a <= m.start() and m.end() <= b for a, b in quotes):
337
+ hit["why"] = "ⓓ inside quote span"; rec["mention"].append(hit); continue
338
+ # ⓑ
339
+ if not args.no_retraction_context:
340
+ win = in_scope_text(text, offsets, block, m, args.retraction_scope, args.retraction_chars)
341
+ mm = marker_re.search(win)
342
+ if mm:
343
+ hit["why"] = "ⓑ marker in window: " + mm.group(0); rec["retraction"].append(hit); continue
344
+ if args.retraction_scope != "line":
345
+ mc = marker_re.search(cap)
346
+ if mc:
347
+ hit["why"] = "ⓑ marker in block caption: " + mc.group(0); rec["retraction"].append(hit); continue
348
+ # ⓐ
349
+ if c["anchor_re"] is not None and not args.no_anchor:
350
+ win = in_scope_text(text, offsets, block, m, args.anchor_scope, args.anchor_chars)
351
+ am = c["anchor_re"].search(win)
352
+ if not am and args.anchor_scope != "line":
353
+ am = c["anchor_re"].search(cap)
354
+ if not am:
355
+ hit["why"] = "ⓐ no anchor in window"; rec["no_anchor"].append(hit); continue
356
+ hit["why"] = "ⓐ anchor: " + am.group(0)
357
+ # would be LIVE — an excluded-class file classifies it EXCLUDED-FILE instead (counted, shown, never rc)
358
+ if exlabel:
359
+ hit["why"] = "EXCLUDED-FILE · " + exlabel + ((" · " + hit["why"]) if hit["why"] else "")
360
+ rec["excluded_file"].append(hit); continue
361
+ rec["live"].append(hit)
362
+ return per_token
363
+
364
+
365
+ def print_exclusions(per_pattern, no_default):
366
+ if not per_pattern:
367
+ print(" excluded: (none — --no-default-exclude; record- and fixture-class hits count as LIVE)")
368
+ return
369
+ width = max(len(p) for p, _, _ in per_pattern)
370
+ for pat, label, rels in per_pattern:
371
+ tag = "[--exclude]" if label == "--exclude" else "[default · %s]" % label
372
+ shown = ", ".join(rels) if len(rels) <= 5 else "%s, … (+%d)" % (", ".join(rels[:5]), len(rels) - 5)
373
+ print(" excluded: %-*s %-26s → %d file%s%s" % (width, pat, tag, len(rels),
374
+ "" if len(rels) == 1 else "s", (": " + shown) if rels else ""))
375
+
376
+
377
+ def main():
378
+ global NFKC_ON
379
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
380
+ ap.add_argument("--claims", required=True, help="TSV: token<TAB>anchor-regex<TAB>source")
381
+ ap.add_argument("--root", default=".")
382
+ ap.add_argument("--paths", nargs="*", default=None, help="pathspecs under --root (dirs · files · globs)")
383
+ ap.add_argument("--untracked", action="store_true", help="walk the filesystem instead of `git ls-files`")
384
+ ap.add_argument("--exclude", action="append", default=None, metavar="GLOB",
385
+ help="add an excluded-class pattern (root-relative fnmatch; repeatable); hits there are EXCLUDED-FILE")
386
+ ap.add_argument("--no-default-exclude", action="store_true",
387
+ help="drop the default classes (%s) — their hits then count as LIVE" % ", ".join(p for p, _ in DEFAULT_EXCLUDES))
388
+ ap.add_argument("--markers", default=DEFAULT_MARKERS, help="ⓑ retraction-marker regex (frozen vocabulary)")
389
+ ap.add_argument("--strict-markers", action="store_true", help="ⓑ narrow vocabulary only: " + STRICT_MARKERS)
390
+ ap.add_argument("--retraction-scope", choices=["line", "chars", "block"], default="chars")
391
+ ap.add_argument("--retraction-chars", type=int, default=200)
392
+ ap.add_argument("--anchor-scope", choices=["line", "chars", "block"], default="chars")
393
+ ap.add_argument("--anchor-chars", type=int, default=200)
394
+ ap.add_argument("--ubiquity-max-occ", type=int, default=20, help="ⓒ: refuse a bare token above this many occurrences")
395
+ ap.add_argument("--ubiquity-max-files", type=int, default=8, help="ⓒ: refuse a bare token present in more files than this")
396
+ ap.add_argument("--no-nfkc", action="store_true", help="disable NFKC normalization (ablation — full-width copies go silent)")
397
+ ap.add_argument("--no-anchor", action="store_true", help="disable ⓐ (ignore anchor regexes)")
398
+ ap.add_argument("--no-retraction-context", action="store_true", help="disable ⓑ (ablation / revert probe)")
399
+ ap.add_argument("--no-form-rule", action="store_true", help="disable ⓒ′ (scan bare numeric tokens)")
400
+ ap.add_argument("--no-ubiquity", action="store_true", help="disable ⓒ (scan bare tokens regardless of frequency)")
401
+ ap.add_argument("--quote-excl", action="store_true", help="enable ⓓ (quoted span = mention)")
402
+ ap.add_argument("--show-excluded", action="store_true",
403
+ help="also list EXCLUDED-FILE / retraction-context / no-anchor / mention sites as file:line")
404
+ ap.add_argument("--json", action="store_true")
405
+ ap.add_argument("--quiet", action="store_true", help="print only the exclusion line(s) and the verdict line")
406
+ args = ap.parse_args()
407
+ if args.strict_markers:
408
+ args.markers = STRICT_MARKERS
409
+ if args.no_nfkc:
410
+ NFKC_ON = False
411
+ excludes = ([] if args.no_default_exclude else list(DEFAULT_EXCLUDES)) + [(p, "--exclude") for p in (args.exclude or [])]
412
+
413
+ if not os.path.isfile(args.claims):
414
+ print("🟥 claims file not found: %s" % args.claims, file=sys.stderr); return 10
415
+ claims = read_claims(args.claims)
416
+ root = os.path.abspath(args.root)
417
+ files = list_corpus(root, args.paths, tracked=not args.untracked)
418
+ if not files:
419
+ print("🟥 corpus is empty under %s (paths=%s)" % (root, args.paths), file=sys.stderr); return 10
420
+ excluded, per_pattern = classify_excludes(files, root, excludes)
421
+ # no corpus cut here on purpose — excluded-class files stay in `files` and are scanned (lane L12)
422
+ if not claims:
423
+ print("⬜ DEAD CONTROL — 0 tokens parsed from %s; %d files enumerated but NOTHING was scanned. rc=4 (not a clean scan)."
424
+ % (args.claims, len(files)))
425
+ return 4
426
+
427
+ res = scan(claims, files, root, excluded, args)
428
+ n_live = sum(len(r["live"]) for r in res.values())
429
+ n_excl = sum(len(r["excluded_file"]) for r in res.values())
430
+ n_retr = sum(len(r["retraction"]) for r in res.values())
431
+ n_noanc = sum(len(r["no_anchor"]) for r in res.values())
432
+ n_ment = sum(len(r["mention"]) for r in res.values())
433
+ n_ref = sum(1 for r in res.values() if r["refused"])
434
+ rc = 2 if n_live else (3 if n_ref else 0)
435
+ verdict = ("R-claim verdict: LIVE=%d EXCLUDED-FILE=%d RETRACTION-CONTEXT=%d NO-ANCHOR=%d MENTION=%d REFUSED=%d rc=%d"
436
+ % (n_live, n_excl, n_retr, n_noanc, n_ment, n_ref, rc))
437
+
438
+ if args.json:
439
+ out = {}
440
+ for k, r in res.items():
441
+ rr = dict(r); rr["bare_files"] = sorted(r["bare_files"])
442
+ out[k] = rr
443
+ print(json.dumps({"files": len(files), "root": root,
444
+ "excluded": {"patterns": [p for p, _, _ in per_pattern],
445
+ "classes": {p: l for p, l, _ in per_pattern},
446
+ "files": sorted(excluded)},
447
+ "mechanisms": {"nfkc": NFKC_ON, "anchor": not args.no_anchor,
448
+ "retraction_context": not args.no_retraction_context,
449
+ "form_rule": not args.no_form_rule, "ubiquity": not args.no_ubiquity,
450
+ "quote": args.quote_excl, "markers": args.markers},
451
+ "summary": {"live": n_live, "excluded_file": n_excl, "retraction_context": n_retr,
452
+ "no_anchor": n_noanc, "mention": n_ment, "refused": n_ref, "rc": rc},
453
+ "tokens": out}, ensure_ascii=False, indent=1))
454
+ return rc
455
+
456
+ if args.quiet:
457
+ print_exclusions(per_pattern, args.no_default_exclude)
458
+ print(verdict)
459
+ return rc
460
+
461
+ print("R-claim scan · corpus=%d files%s · root=%s" % (
462
+ len(files), (" (%d in excluded classes — scanned, hits classified EXCLUDED-FILE)" % len(excluded)) if excluded else "", root))
463
+ print_exclusions(per_pattern, args.no_default_exclude)
464
+ print(" mechanisms: nfkc=%s ⓐanchor=%s(%s±%d) ⓑretract=%s(%s±%d%s) ⓒ′form=%s ⓒubiquity=%s(>%d occ|>%d files) ⓓquote=%s" % (
465
+ "on" if NFKC_ON else "off",
466
+ "off" if args.no_anchor else "on", args.anchor_scope, args.anchor_chars,
467
+ "off" if args.no_retraction_context else "on", args.retraction_scope, args.retraction_chars,
468
+ ",strict" if args.strict_markers else "",
469
+ "off" if args.no_form_rule else "on",
470
+ "off" if args.no_ubiquity else "on", args.ubiquity_max_occ, args.ubiquity_max_files,
471
+ "on" if args.quote_excl else "off"))
472
+ print(" %-18s %6s %5s %8s %6s %7s %6s %5s %s" % ("token", "bare", "files", "retract", "noanc", "mention", "exclf", "LIVE", "note"))
473
+ for k, r in res.items():
474
+ note = ""
475
+ if r["refused"] == "form":
476
+ note = "REFUSED by ⓒ′ (numeric FORM, no anchor supplied) — NOT scanned"
477
+ elif r["refused"] == "ubiquity":
478
+ note = "REFUSED by ⓒ (ubiquitous, no anchor supplied) — NOT scanned"
479
+ print(" %-18s %6d %5d %8d %6d %7d %6d %5d %s" % (k, r["bare"], len(r["bare_files"]),
480
+ len(r["retraction"]), len(r["no_anchor"]), len(r["mention"]), len(r["excluded_file"]), len(r["live"]), note))
481
+ for k, r in res.items():
482
+ for h in r["live"]:
483
+ print(" 🟥 LIVE `%s` %s:%d [%s] …%s…" % (k, h["file"], h["line"], h["why"], h["snippet"][:150]))
484
+ if args.show_excluded:
485
+ for k, r in res.items():
486
+ for h in r["excluded_file"] + r["retraction"] + r["no_anchor"] + r["mention"]:
487
+ print(" ⬜ excl `%s` %s:%d [%s] …%s…" % (k, h["file"], h["line"], h["why"], h["snippet"][:120]))
488
+ elif n_excl:
489
+ print("ⓘ %d would-be-LIVE hit(s) sit in excluded-class files — counted as EXCLUDED-FILE, not in rc; --show-excluded lists them." % n_excl)
490
+ if n_live:
491
+ print("ⓘ ADVISORY — MARK, DO NOT BLOCK. A LIVE hit is «the retracted token still asserted here», judged by form, not truth.")
492
+ if n_ref:
493
+ print("ⓘ PARTIAL — a REFUSED token was not scanned at all; this output is NOT a clean-corpus verdict for it.")
494
+ print(verdict)
495
+ return rc
496
+
497
+
498
+ if __name__ == "__main__":
499
+ sys.exit(main())