@chrono-meta/fh-gate 3.15.0 → 3.17.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.
Files changed (60) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/AGENTS.md +27 -0
  3. package/CATALOG.md +60 -0
  4. package/CLAUDE.md +5 -0
  5. package/README.ja.md +2 -2
  6. package/README.ko.md +2 -2
  7. package/README.md +2 -2
  8. package/README.zh.md +2 -2
  9. package/docs/OUTPUT_EVIDENCE.md +1 -1
  10. package/docs/codex-compat.md +24 -0
  11. package/knowledge/shared/harness-core/checkout_layer_drift.md +301 -0
  12. package/knowledge/shared/learnings/subagent_invocations_log.yaml +66 -0
  13. package/package.json +13 -1
  14. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  15. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  16. package/plugins/fh-meta/CHANGELOG.md +42 -0
  17. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  18. package/plugins/fh-preprep/skills/preprep/SKILL.md +5 -0
  19. package/plugins/fh-preprep/skills/preprep/lane_font_embed.py +235 -0
  20. package/plugins/fh-preprep/skills/preprep/ooxml/gate.py +67 -5
  21. package/plugins/fh-preprep/skills/preprep/ooxml/test_gate_exitcodes.py +136 -0
  22. package/plugins/fh-preprep/skills/preprep/preprep.py +16 -1
  23. package/plugins/fh-preprep/skills/preprep/presentation_checklist.md +108 -6
  24. package/plugins/fh-preprep/skills/preprep/safe_install.py +22 -3
  25. package/plugins/fh-preprep/skills/preprep/surfaces.example.yaml +11 -0
  26. package/plugins/fh-preprep/skills/preprep/test_lane_font_embed.py +117 -0
  27. package/plugins/fh-preprep/skills/preprep/test_safe_install_app_xml.py +77 -0
  28. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  29. package/scripts/count_check.sh +46 -14
  30. package/scripts/daily_report.sh +17 -1
  31. package/scripts/env_layer_fingerprint.sh +309 -0
  32. package/scripts/gate_bootstrap_ephemeral.sh +248 -0
  33. package/scripts/governor_board.sh +841 -0
  34. package/scripts/map_postprocess.py +89 -4
  35. package/scripts/multibyte_bracket_lint.sh +135 -0
  36. package/scripts/outbound_pr_gate.sh +12 -0
  37. package/scripts/package_coverage_check.sh +34 -0
  38. package/scripts/selfcheck.sh +263 -0
  39. package/scripts/session_close_check.sh +96 -1
  40. package/scripts/stale_ref_scan.py +511 -0
  41. package/scripts/test_count_check_decl_lanes.sh +176 -0
  42. package/scripts/test_env_layer_fingerprint_lanes.sh +192 -0
  43. package/scripts/test_gate_bootstrap_ephemeral_lanes.sh +262 -0
  44. package/scripts/test_locale_invariance_lanes.sh +581 -0
  45. package/scripts/test_map_postprocess_lanes.sh +84 -4
  46. package/scripts/test_marker_crossfamily_lanes.sh +5 -1
  47. package/scripts/test_marker_defense_lanes.sh +5 -1
  48. package/scripts/test_marker_standpoint_lanes.sh +5 -1
  49. package/scripts/test_marker_thirdparty_lanes.sh +5 -1
  50. package/scripts/test_multibyte_bracket_lint_lanes.sh +107 -0
  51. package/scripts/test_outbound_pr_gate_lanes.sh +133 -0
  52. package/scripts/test_preprep_drift_anchor.sh +34 -9
  53. package/scripts/test_preprep_drift_anchor_lanes.sh +64 -2
  54. package/scripts/test_session_close_chain_lanes.sh +45 -0
  55. package/scripts/test_stale_ref_close_lanes.sh +197 -0
  56. package/scripts/test_stale_ref_scan_lanes.sh +134 -0
  57. package/scripts/test_worktree_reclaim_lanes.sh +267 -1
  58. package/scripts/worktree_reclaim.sh +246 -11
  59. package/templates/.git-hooks/pre-commit +108 -27
  60. package/templates/settings.PreToolUse.snippet.json +54 -1
@@ -0,0 +1,511 @@
1
+ #!/usr/bin/env python3
2
+ """stale_ref_scan.py — a Zenodo reference is USED, and it resolves, but it points at a version of its
3
+ OWN RECORD FAMILY that is no longer the latest one.
4
+
5
+ WHY THIS EXISTS (measured 2026-09-20, this repo)
6
+ `CITATION.cff` and four paper drafts cited the version DOI `10.5281/zenodo.20397566` — the v1.0
7
+ DRAFT, arXiv-rejected, superseded twice since. That DOI is not broken: it resolves, HTTP 200, to a
8
+ real record. So every check that asks "is this DOI valid?" passed. What was stale was not the
9
+ VALUE — it was the WORLD the value pointed at. No instrument in this repo asked that question:
10
+ halffix_propagation_scan.sh only reads staged-diff tokens — silent if nobody touches the line
11
+ claim_propagation_scan.py only fires once someone registers a "retraction token"
12
+ doc_claim_triad_scan.py a different axis ("A calls B"), not "this ID is old"
13
+ This tool asks Zenodo directly: for a cited record id, is there a NEWER version in the same family?
14
+
15
+ WHAT IT DOES NOT DO — read before trusting a 0
16
+ 🟥 It is a REVIEW SURFACE, not a block. Citing an OLD version on purpose is legitimate — pinning
17
+ "what was claimed at that moment" (the exact use `field_verdict_crossfamily_gate.md §7`'s
18
+ `tier1`/`tier2` distinction relies on for its own citations). So this tool does not fail a build;
19
+ it lists candidates for a human to look at, same posture as `phantom-quench`.
20
+ 🟥 It checks the Zenodo API's OWN answer, not bibliographic truth beyond that. If Zenodo itself is
21
+ wrong or slow to index a new version, this tool inherits that lag — UNRESOLVED and SUPERSEDED are
22
+ read FROM Zenodo, not independently re-derived.
23
+ 🟥 Changelog / retraction prose is EXCLUDED on purpose. A line documenting "we used to cite X, now
24
+ we cite Y" legitimately contains the old id — flagging it would bury the real signal under the
25
+ record of already-fixed history. Detection is a HEADING cutoff (`<h1-6>…Changelog…`, or Markdown
26
+ `#…Changelog`): once seen, every following line in that file is changelog context. This is
27
+ mechanical and coarse — a doc with prose sections AFTER "Changelog" (unusual, none seen in this
28
+ repo) would also be excluded; a paper that mentions an old id in body prose BEFORE any Changelog
29
+ heading, without using changelog language, is NOT excluded (this is the case this tool exists to
30
+ catch — see v1.0.3 below). Not a keyword scan of "retraction"/"superseded" prose — a heading is
31
+ the only mechanical anchor calibrated here.
32
+ 🟥 Extraction requires the FULL DOI prefix (`10.5281/zenodo.<digits>`) or a Zenodo record URL
33
+ (`zenodo.org/record(s)/<digits>`). A bare mention like `` `zenodo.20397566` `` (no `10.5281/`)
34
+ inside prose is NOT extracted — this is deliberate, not an oversight: house convention marks such
35
+ spans as code (backtick), i.e. a MENTION, the same class `citation_key_check.py` carves out for
36
+ code spans. Widening this would need the same code-span-vs-prose split that tool already has.
37
+ 🟥 HTML soft-hyphenation (`10.5281/<wbr>zenodo.<wbr>20397566`) is unwrapped by stripping inline tags
38
+ before matching — but only per-line; a DOI split ACROSS lines by markup is not reassembled.
39
+ 🟥 A "record id" here is a bare Zenodo numeric id (from a DOI or URL) — not an arXiv id, not a GitHub
40
+ release tag, not a DOI from a different registrant prefix. Out of scope by construction.
41
+
42
+ RESOLUTION ALGORITHM (verified against the live API, 2026-09-20)
43
+ GET https://zenodo.org/api/records/<id> (urllib follows the redirect Zenodo issues for a concept id)
44
+ · queried a CONCEPT id → Zenodo 302s to the latest version; the JSON's own `id` != the id you
45
+ queried → verdict CONCEPT (always resolves to current by construction; never stale)
46
+ · queried a VERSION id → JSON's own `id` == the id you queried. Its `conceptrecid` names the
47
+ family. A second call, `GET …/records/<conceptrecid>`, redirects to the family's CURRENT
48
+ version and returns ITS `id`:
49
+ current id == the id you queried → verdict CURRENT
50
+ current id != the id you queried → verdict SUPERSEDED (this is the defect class)
51
+ · fetch failed (404 / network / malformed JSON) → verdict UNRESOLVED — NOT a pass; see below.
52
+
53
+ EXIT CODES
54
+ 0 scanned; zero SUPERSEDED and zero UNRESOLVED candidates (changelog-excluded and CONCEPT/CURRENT
55
+ candidates do not affect this)
56
+ 1 at least one SUPERSEDED or UNRESOLVED candidate — a review-surface finding, not a hard failure;
57
+ the two are distinguished in the printed detail, not in the exit code (house convention already
58
+ folds several defect classes into one rc in `citation_key_check.py`; UNRESOLVED is grouped here
59
+ because the task statement is explicit that it "is not PASS", and this repo defines only three
60
+ codes for this tool — 0 / 1 / 10 — leaving no fourth slot to split it into)
61
+ 10 instrument error — an input file could not be read, or (self-check only) a known-pair lane
62
+ produced the wrong verdict
63
+
64
+ USAGE
65
+ python3 scripts/stale_ref_scan.py --body <files...> [--offline-fixture <json>] [--json] [--timeout N]
66
+ python3 scripts/stale_ref_scan.py --self-check # known-pair, no network, run this first
67
+
68
+ OFFLINE FIXTURE FORMAT (for --offline-fixture, and what --self-check builds internally)
69
+ A JSON object keyed by the EXACT string you would query (an id as it appears in the source text).
70
+ Value = the JSON Zenodo's API would return AFTER following any redirect for that query, i.e.
71
+ `{"id": <int>, "conceptrecid": "<str>"}`. A key absent from the fixture simulates a 404/UNRESOLVED —
72
+ this is how the `--self-check` UNRESOLVED lane is produced without touching the network.
73
+
74
+ Python >= 3.9, stdlib only (urllib for the live path; --self-check and --offline-fixture need none).
75
+ """
76
+ import argparse
77
+ import json
78
+ import os
79
+ import re
80
+ import sys
81
+ import urllib.error
82
+ import urllib.request
83
+
84
+ TAG_RE = re.compile(r"<[^>]+>")
85
+ ZID_RE = re.compile(r"(?:10\.5281/zenodo\.|zenodo\.org/records?/)(\d+)", re.IGNORECASE)
86
+ #: 🟥 **헤딩 «텍스트 안 어디든»** 을 본다 — 초판은 «해시/태그 바로 뒤 첫 낱말» 이라
87
+ #: `# forge-harness (fh-meta) Changelog` 가 **안 걸렸다**(실행으로 확인: 4천 줄 릴리스 기록이
88
+ #: 통째로 «살아있는 인용» 으로 스캔됐다). 적대검증 A-2.
89
+ _CL_WORDS = r"(?:changelog|change\s+log|version\s+history|revision\s+history|release\s+notes)"
90
+ CHANGELOG_HTML_RE = re.compile(r"<h[1-6][^>]*>(?P<t>.*?)</h[1-6]>", re.IGNORECASE | re.DOTALL)
91
+ CHANGELOG_MD_RE = re.compile(r"^\s*#{1,6}\s+(?P<t>.+)$")
92
+ CHANGELOG_WORD_RE = re.compile(_CL_WORDS, re.IGNORECASE)
93
+
94
+ #: 🟥 **고정 인용(pin) 을 위한 탈출구.** 이미 발행된 판의 로컬 사본은 «고치면 기록이 아니게»
95
+ #: 되므로 구조적으로 수리 불가능한 SUPERSEDED 를 영구히 낸다(적대검증 A-5: 이 레포에만 셋).
96
+ #: 만족 불가능한 요구는 override 를 훈련시키므로, 파일이 스스로 «이건 스냅샷이다» 라고
97
+ #: 말할 수단을 준다. 🟥 **파일명 추론이 아니라 «파일이 선언한 것»** 이다 — 추론은 조용히 틀린다.
98
+ PIN_MARKER_RE = re.compile(r"stale-ref:\s*pinned", re.IGNORECASE)
99
+
100
+ #: 못 읽은 입력의 판별 — NUL 바이트 또는 디코드 실패율. 적대검증 S-1.
101
+ UNSCANNABLE_REPLACEMENT_RATIO = 0.02
102
+
103
+ API_BASE = "https://zenodo.org/api/records/"
104
+
105
+
106
+ def is_changelog_heading(line):
107
+ """헤딩인가 + 그 헤딩 «텍스트 안에» changelog 계열 낱말이 있나. 두 조건 다 필요하다 —
108
+ 본문 산문에 「changelog」 가 나온다고 그 뒤를 전부 버리면 진짜 인용을 삼킨다."""
109
+ for rx in (CHANGELOG_HTML_RE, CHANGELOG_MD_RE):
110
+ m = rx.search(line) if rx is CHANGELOG_HTML_RE else rx.match(line)
111
+ if m and CHANGELOG_WORD_RE.search(TAG_RE.sub("", m.group("t"))):
112
+ return True
113
+ return False
114
+
115
+
116
+ def load(path):
117
+ """→ (lines, error). 🟥 **«읽지 못한 것» 을 «깨끗함» 으로 내보내지 않는다.**
118
+
119
+ 초판은 `errors="replace"` 로 무엇이든 읽어서, PDF 를 주면 `0 sites · rc=0` 이 나왔다 —
120
+ 정상 스캔과 **출력이 바이트로 같았다**(실행으로 확인). `paper/` 에는 같은 stem 의 `.pdf` 가
121
+ `.html` 바로 옆에 다섯 개 있고 `--body paper/*` 가 가장 자연스러운 호출이다.
122
+ 이 레포 정본이 그 자리를 이미 이름 붙였다 — «A missing measurement is not a zero».
123
+ 적대검증 S-1.
124
+ """
125
+ try:
126
+ with open(path, "rb") as fh:
127
+ raw = fh.read()
128
+ except OSError as e:
129
+ return None, str(e)
130
+ if b"\x00" in raw:
131
+ return None, "binary (NUL byte) — not a text body"
132
+ text = raw.decode("utf-8", errors="replace")
133
+ if text:
134
+ bad = text.count("\ufffd") / len(text)
135
+ if bad > UNSCANNABLE_REPLACEMENT_RATIO:
136
+ return None, "not decodable as UTF-8 (%.1f%% replacement chars)" % (bad * 100)
137
+ return text.split("\n"), None
138
+
139
+
140
+ def scan_body(path, lines):
141
+ """→ list of (line_no, record_id, snippet, in_changelog). Extraction runs on a per-line, inline-
142
+ tag-stripped copy so `10.5281/<wbr>zenodo.<wbr>20397566` still matches; the ORIGINAL line is kept
143
+ for the printed snippet. `in_changelog` reflects the flag's state AFTER this line is checked for a
144
+ heading, so a heading line itself and everything after it (same file) are marked True."""
145
+ in_changelog = False
146
+ pinned = any(PIN_MARKER_RE.search(l) for l in lines[:40])
147
+ sites = []
148
+ for i, line in enumerate(lines, 1):
149
+ if is_changelog_heading(line):
150
+ in_changelog = True
151
+ if pinned:
152
+ in_changelog = True # 스냅샷 파일 전체를 «기록» 으로 취급
153
+ flat = TAG_RE.sub("", line)
154
+ for m in ZID_RE.finditer(flat):
155
+ snippet = line.strip()[:140]
156
+ sites.append((i, m.group(1), snippet, in_changelog))
157
+ return sites
158
+
159
+
160
+ def fetch_live(query_id, timeout):
161
+ """One GET, following redirects (urllib does this by default) — this is how a CONCEPT id's query
162
+ comes back as its LATEST version's own JSON. 404 / network / malformed JSON → None (UNRESOLVED)."""
163
+ req = urllib.request.Request(
164
+ API_BASE + str(query_id),
165
+ headers={"User-Agent": "forge-harness/stale_ref_scan.py (+https://github.com/chrono-meta/forge-harness)"},
166
+ )
167
+ try:
168
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
169
+ if resp.status != 200:
170
+ return None
171
+ return json.loads(resp.read().decode("utf-8"))
172
+ except urllib.error.HTTPError:
173
+ return None
174
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError):
175
+ return None
176
+
177
+
178
+ def make_offline_fetch(fixture):
179
+ def _fetch(query_id, timeout=0):
180
+ return fixture.get(str(query_id))
181
+ return _fetch
182
+
183
+
184
+ def make_cached(fetch_fn):
185
+ """Wraps a raw fetch so the same query string is never sent twice in one run (a SUPERSEDED verdict
186
+ needs two calls — the id itself, then its conceptrecid — and the concept is frequently shared
187
+ across several cited sites of the same stale id)."""
188
+ cache = {}
189
+
190
+ def _cached(query_id, timeout=15):
191
+ key = str(query_id)
192
+ if key not in cache:
193
+ cache[key] = fetch_fn(key, timeout)
194
+ return cache[key]
195
+ return _cached
196
+
197
+
198
+ def compute_rc(superseded, unresolved, unscannable):
199
+ """🟥 **계기 실패와 문서 결함을 같은 rc 로 접지 않는다.**
200
+
201
+ 초판은 둘 다 rc=1 이었다. 그러면 Zenodo 429 한 번에 전 파일이 «문서 결함» 으로 뜨고,
202
+ 그걸 배선하면 «rc=1 은 보통 네트워크» 를 학습한 리뷰어가 **진짜 SUPERSEDED 를 무시**한다.
203
+ 이 레포 정본이 그 자리를 이름 붙였다 — 계기 오류는 «별도 비-PASS»(fh-gate.sh 의 exit-10).
204
+ 🟥 **10 이 1 을 지배한다** — 못 잰 것이 있으면 «발견 목록» 을 신뢰할 수 없다
205
+ (`gate_shape_scan.sh` 의 «exit 3 이 히트를 지배» 와 같은 형태). 적대검증 A-7.
206
+
207
+ 🟥 **함수로 뽑은 이유**: `main()` 안에 인라인으로 두면 self-check 가 그 줄을 지나가지
208
+ 않아서, `rc = 0` 으로 고정하는 한 줄 뮤턴트가 **self-check 전 레인을 통과한다**(실측).
209
+ """
210
+ if unresolved or unscannable:
211
+ return 10
212
+ return 1 if superseded else 0
213
+
214
+
215
+ def resolve(record_id, cached_fetch, timeout=15):
216
+ """→ dict with at least {"status": CONCEPT|CURRENT|SUPERSEDED|UNRESOLVED}. See module docstring
217
+ §RESOLUTION ALGORITHM for the two-call shape."""
218
+ rec = cached_fetch(record_id, timeout)
219
+ if not rec or "id" not in rec:
220
+ return {"status": "UNRESOLVED", "detail": "fetch failed (404 / network / malformed response)"}
221
+
222
+ # 🟥 **정수 파싱을 감싼다** — 밖에 두면 InvenioRDM 의 영숫자 PID 나 비정수 `id` 에서
223
+ # 미처리 예외가 나고, 파이썬 종료코드 1 이 «발견됨» 과 구별이 안 된다(적대검증 B-3).
224
+ try:
225
+ rid_int = int(record_id)
226
+ api_id_raw = rec.get("id")
227
+ api_id = None if api_id_raw is None else int(api_id_raw)
228
+ except (TypeError, ValueError):
229
+ return {"status": "UNRESOLVED",
230
+ "detail": "record id is not an integer (schema changed?) — cannot compare families"}
231
+
232
+ # `conceptrecid` 는 레거시 키, `parent.id` 는 InvenioRDM 키. 둘 다 본다.
233
+ concept = rec.get("conceptrecid") or (rec.get("parent") or {}).get("id")
234
+
235
+ # 🟥 **CONCEPT 은 «양성 테스트» 로 판정한다 — «id 가 다르다» 라는 부정 판별자가 아니라.**
236
+ # 초판은 리다이렉트가 나면 무조건 CONCEPT 이라 적었는데, 그건 «리다이렉트의 이유» 를
237
+ # 안 묻는다. Zenodo 가 병합·이전으로 «버전» id 를 리다이렉트하면 그건 정확히 이 도구가
238
+ # 잡으려는 결함인데 «늙지 않음» 으로 조용히 흡수된다(적대검증 A-6, 방향이 false-negative).
239
+ # 🟥 판별자는 **같은 응답 안에 이미 있다** — 라이브 API 직독(2026-09-20)으로 확인했다:
240
+ # GET /records/20397565 (컨셉) → id=22843702 · conceptrecid=20397565 ← 물어본 id 와 같다
241
+ # GET /records/20397566 (버전) → id=20397566 · conceptrecid=20397565 ← 다르다
242
+ # ⇒ CONCEPT ⟺ conceptrecid == 물어본 id. 네트워크 추가 호출 0.
243
+ if concept is not None:
244
+ try:
245
+ if int(concept) == rid_int:
246
+ return {"status": "CONCEPT", "resolved_to": api_id, "concept": concept}
247
+ except (TypeError, ValueError):
248
+ pass
249
+
250
+ if api_id is None or api_id != rid_int:
251
+ # 리다이렉트인데 컨셉이 아니다 — 무엇인지 모른다. 🟥 «안 늙음» 으로 접지 않는다.
252
+ return {"status": "UNRESOLVED",
253
+ "detail": "query %s redirected to %s but its concept is %s — not a concept id, "
254
+ "reason unknown" % (record_id, api_id, concept)}
255
+
256
+ if not concept:
257
+ return {"status": "UNRESOLVED", "detail": "response has no conceptrecid / parent.id — can't find its family"}
258
+
259
+ latest = cached_fetch(concept, timeout)
260
+ if not latest or "id" not in latest:
261
+ return {"status": "UNRESOLVED", "detail": "concept %s did not resolve to a latest version" % concept}
262
+
263
+ latest_id = latest.get("id")
264
+ try:
265
+ latest_int = int(latest_id)
266
+ except (TypeError, ValueError):
267
+ return {"status": "UNRESOLVED", "detail": "latest id is not an integer (schema changed?)"}
268
+ if latest_int == rid_int:
269
+ return {"status": "CURRENT", "concept": concept}
270
+ return {"status": "SUPERSEDED", "concept": concept, "latest_id": latest_id, "latest_doi": latest.get("doi")}
271
+
272
+
273
+ # ---------------------------------------------------------------------------------------------------
274
+ # --self-check — known-pair, offline by construction (no --offline-fixture file needed)
275
+ # ---------------------------------------------------------------------------------------------------
276
+
277
+ SELF_CHECK_FIXTURE = {
278
+ # known-positive: the real v1.0 draft version DOI this repo actually shipped stale, until
279
+ # 2026-09-20 — querying it returns ITSELF (a genuine version id), whose family's current is a
280
+ # DIFFERENT id → SUPERSEDED.
281
+ "20397566": {"id": 20397566, "conceptrecid": "20397565"},
282
+ # the family's current version, so the concept lookup above resolves here
283
+ "22843702": {"id": 22843702, "conceptrecid": "20397565"},
284
+ # known-negative: the real concept DOI — querying it comes back as ITS OWN latest version's JSON
285
+ # (id 22843702 != the 20397565 you asked for) → CONCEPT, never stale by construction.
286
+ "20397565": {"id": 22843702, "conceptrecid": "20397565"},
287
+ # 99999999999 deliberately ABSENT → simulates 404 → UNRESOLVED
288
+ }
289
+
290
+
291
+ def run_self_check():
292
+ fetch = make_cached(make_offline_fetch(SELF_CHECK_FIXTURE))
293
+ lanes = [
294
+ ("known-positive (stale version DOI)", "20397566", "SUPERSEDED"),
295
+ ("known-negative (concept DOI)", "20397565", "CONCEPT"),
296
+ ("unresolved (id absent from fixture / simulated 404)", "99999999999", "UNRESOLVED"),
297
+ # control: querying the current version itself should read as CURRENT, not SUPERSEDED —
298
+ # without this lane a scanner that always answers SUPERSEDED for any known version id would
299
+ # still pass the known-positive lane above.
300
+ ("control (current version DOI)", "22843702", "CURRENT"),
301
+ ]
302
+ print("stale-ref-scan self-check (known-pair, offline fixture, 0 network calls)")
303
+ ok = True
304
+ for label, rid, expect in lanes:
305
+ got = resolve(rid, fetch)["status"]
306
+ verdict = "PASS" if got == expect else "FAIL"
307
+ if got != expect:
308
+ ok = False
309
+ print(" %s %-55s [%s] expected=%s got=%s" % (verdict, label, rid, expect, got))
310
+
311
+ # ═══════════════════════════════════════════════════════════════════════════════════════
312
+ # 🟥 **추출·제외·rc 레인 — 이게 없으면 self-check 는 `resolve()` 24줄짜리 증거다.**
313
+ # 적대검증 A-4 가 지적했고 **실행으로 확정됐다**: `scan_body` 를 `return []` 로 죽여도
314
+ # 위 4레인이 그대로 4/4 PASS 였고, 그 상태로 실물을 돌리면 SUPERSEDED=1 이 0 으로
315
+ # 바뀌었다. 즉 «아무것도 안 스캔하는 구현» 이 통과했다.
316
+ # 픽스처 문구는 **이 레포 실물에서 뽑았다** — 머릿속 모형이 아니다.
317
+ # ═══════════════════════════════════════════════════════════════════════════════════════
318
+ print(" ── extraction / exclusion / rc lanes ──")
319
+
320
+ def lane(label, cond, detail=""):
321
+ nonlocal ok
322
+ print(" %s %-55s %s" % ("PASS" if cond else "FAIL", label, detail))
323
+ if not cond:
324
+ ok = False
325
+
326
+ # ⓐ `<wbr>` 분할 — paper/forge_harness_v1.0.3.html:159 의 실물 형태
327
+ wbr = ['<tr><td>forge-harness</td><td>10.5281/<wbr>zenodo.<wbr>20397566</td></tr>']
328
+ got = [r for _, r, _, _ in scan_body("x.html", wbr)]
329
+ lane("extract: <wbr>-split DOI", got == ["20397566"], str(got))
330
+
331
+ # ⓑ URL 형태 — README.md:418 의 실물 형태 (as of c4b4ffa; 그 줄은 이후 v1.0.2 id
332
+ # 22843702 로 옮겨갔다. 픽스처는 «낡은 id» 를 일부러 유지한다 — stale-ref 레인이라서다)
333
+ url = ['> **FH papers**: v1.0.1 methodology · [Zenodo](https://zenodo.org/records/22542168)']
334
+ got = [r for _, r, _, _ in scan_body("x.md", url)]
335
+ lane("extract: zenodo.org/records/<id> URL", got == ["22542168"], str(got))
336
+
337
+ # ⓒ 🟥 known-NEGATIVE — 추출기가 «아무 숫자나» 집지 않는다
338
+ noise = ['version 20397566 of the spec', 'see zenodo for details', 'id=20397566']
339
+ got = [r for _, r, _, _ in scan_body("x.md", noise)]
340
+ lane("extract NEG: bare digits are NOT a citation", got == [], str(got))
341
+
342
+ # ⓓ changelog 제외 — 헤딩 «텍스트 안» 어디든. plugins/fh-meta/CHANGELOG.md:1 의 실물 형태
343
+ cl = ['# forge-harness (fh-meta) Changelog', 'see 10.5281/zenodo.20397566 for what was wrong']
344
+ got = [(r, inc) for _, r, _, inc in scan_body("x.md", cl)]
345
+ lane("exclude: '# <name> Changelog' heading is recognised", got == [("20397566", True)], str(got))
346
+
347
+ # ⓔ 🟥 known-NEGATIVE — 본문 산문의 «changelog» 낱말은 컷오프가 아니다
348
+ prose = ['We keep a changelog for this reason.', 'cite 10.5281/zenodo.20397566 here']
349
+ got = [(r, inc) for _, r, _, inc in scan_body("x.md", prose)]
350
+ lane("exclude NEG: prose mention does NOT cut off", got == [("20397566", False)], str(got))
351
+
352
+ # ⓕ pin 마커 — 발행된 스냅샷은 통째로 기록으로 취급
353
+ pin = ['<!-- stale-ref: pinned — published snapshot, editing it destroys the record -->',
354
+ 'cite 10.5281/zenodo.20397566']
355
+ got = [(r, inc) for _, r, _, inc in scan_body("x.html", pin)]
356
+ lane("exclude: 'stale-ref: pinned' marks the whole file a record", got == [("20397566", True)], str(got))
357
+
358
+ # ⓖ 🟥 못 읽은 입력 — 이 파일 자신을 바이너리로 만들어 본다(임시 파일)
359
+ import tempfile
360
+ with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as tf:
361
+ tf.write(b"%PDF-1.4\x00\x00binary garbage")
362
+ binpath = tf.name
363
+ lines, err = load(binpath)
364
+ os.unlink(binpath)
365
+ lane("load: binary input is UNSCANNABLE, not empty", lines is None and "binary" in (err or ""), str(err))
366
+
367
+ # ⓗ known-NEGATIVE 짝 — 평범한 텍스트는 읽힌다(계기가 «전부 거부» 가 아님)
368
+ lines2, err2 = load(__file__)
369
+ lane("load NEG: this very file reads fine", lines2 is not None and err2 is None, str(err2))
370
+
371
+ # ⓘ 🟥 rc 계산 — 이 레인이 없으면 `rc = 0` 한 줄 뮤턴트가 전 레인을 통과한다(실측 확인)
372
+ lane("rc: clean → 0", compute_rc([], [], []) == 0)
373
+ lane("rc: superseded → 1", compute_rc(["20397566"], [], []) == 1)
374
+ lane("rc: unresolved dominates → 10", compute_rc(["20397566"], ["999"], []) == 10)
375
+ lane("rc: unscannable dominates → 10", compute_rc(["20397566"], [], [("x.pdf", "binary")]) == 10)
376
+ # 🟥 known-NEGATIVE — «항상 10» 을 내는 구현을 막는다
377
+ lane("rc NEG: not always 10", compute_rc([], [], []) != 10)
378
+
379
+ print("SELF-CHECK: %s" % ("PASS" if ok else "FAIL"))
380
+ return 0 if ok else 10
381
+
382
+
383
+ # ---------------------------------------------------------------------------------------------------
384
+
385
+
386
+ def main():
387
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
388
+ ap.add_argument("--body", nargs="+", metavar="FILE", help="file(s) to scan for Zenodo references")
389
+ ap.add_argument("--offline-fixture", metavar="JSON",
390
+ help="use this fixture file instead of live Zenodo calls (see module docstring)")
391
+ ap.add_argument("--timeout", type=float, default=15, help="per-request timeout, seconds (live mode only)")
392
+ ap.add_argument("--max-sites", type=int, default=6, help="usage sites printed per flagged id (0 = all)")
393
+ ap.add_argument("--json", action="store_true")
394
+ ap.add_argument("--self-check", action="store_true", help="run the built-in offline known-pair and exit")
395
+ args = ap.parse_args()
396
+
397
+ if args.self_check:
398
+ return run_self_check()
399
+
400
+ if not args.body:
401
+ print("🟥 --body is required unless --self-check is given", file=sys.stderr)
402
+ return 10
403
+
404
+ # 🟥 못 읽은 파일에서 **즉시 나가지 않는다** — 나머지를 안 재면 그것도 미측정이다.
405
+ # 이름으로 모아 두고 rc 로 지배하게 한다(아래 `rc` 계산).
406
+ files, unscannable = {}, []
407
+ for p in args.body:
408
+ lines, err = load(p)
409
+ if lines is None:
410
+ unscannable.append((p, err))
411
+ continue
412
+ files[p] = lines
413
+
414
+ if args.offline_fixture:
415
+ try:
416
+ with open(args.offline_fixture, encoding="utf-8") as fh:
417
+ fixture = json.load(fh)
418
+ except (OSError, json.JSONDecodeError) as e:
419
+ print("🟥 cannot read --offline-fixture %s: %s — rc=10" % (args.offline_fixture, e), file=sys.stderr)
420
+ return 10
421
+ raw_fetch = make_offline_fetch(fixture)
422
+ else:
423
+ raw_fetch = fetch_live
424
+ cached_fetch = make_cached(raw_fetch)
425
+
426
+ # candidate[id] = list of (file, line, snippet); changelog[id] = same, kept separate & uncounted
427
+ candidates, changelog = {}, {}
428
+ for p in files:
429
+ for line_no, rid, snippet, in_changelog in scan_body(p, files[p]):
430
+ bucket = changelog if in_changelog else candidates
431
+ bucket.setdefault(rid, []).append((p, line_no, snippet))
432
+
433
+ n_sites = sum(len(v) for v in candidates.values())
434
+ n_changelog_sites = sum(len(v) for v in changelog.values())
435
+ if not args.json:
436
+ print("stale-ref-scan · body=%d file%s · %d Zenodo reference site(s) across %d distinct id(s) "
437
+ "(+%d site(s) / %d id(s) excluded as changelog context)%s · review surface, not a gate"
438
+ % (len(args.body), "" if len(args.body) == 1 else "s", n_sites, len(candidates),
439
+ n_changelog_sites, len(changelog),
440
+ "" if not unscannable else " · 🟥 %d UNSCANNABLE" % len(unscannable)))
441
+
442
+ verdicts = {rid: resolve(rid, cached_fetch, args.timeout) for rid in candidates}
443
+
444
+ superseded = sorted(rid for rid, v in verdicts.items() if v["status"] == "SUPERSEDED")
445
+ unresolved = sorted(rid for rid, v in verdicts.items() if v["status"] == "UNRESOLVED")
446
+ concept = sorted(rid for rid, v in verdicts.items() if v["status"] == "CONCEPT")
447
+ current = sorted(rid for rid, v in verdicts.items() if v["status"] == "CURRENT")
448
+
449
+ def where(sites):
450
+ shown = sites if args.max_sites == 0 else sites[:args.max_sites]
451
+ more = "" if len(shown) == len(sites) else " (+%d more)" % (len(sites) - len(shown))
452
+ return " · ".join("%s:%d" % (os.path.basename(f), n) for f, n, _ in shown) + more
453
+
454
+ # 🟥 **계기 실패와 문서 결함을 같은 rc 로 접지 않는다.**
455
+ # 초판은 둘 다 rc=1 이었다. 그러면 Zenodo 429 한 번에 전 파일이 «문서 결함» 으로 뜨고,
456
+ # 그걸 배선하면 «rc=1 은 보통 네트워크» 를 학습한 리뷰어가 **진짜 SUPERSEDED 를 무시**한다.
457
+ # 이 레포 정본이 그 자리를 이름 붙였다 — 계기 오류는 «별도 비-PASS»(fh-gate.sh 의 exit-10).
458
+ # 🟥 **10 이 1 을 지배한다** — 못 잰 것이 있으면 «발견 목록» 을 신뢰할 수 없다.
459
+ # (`gate_shape_scan.sh` 의 «exit 3 이 히트를 지배» 와 같은 형태.) 적대검증 A-7.
460
+ rc = compute_rc(superseded, unresolved, unscannable)
461
+
462
+ if args.json:
463
+ print(json.dumps({
464
+ "body": args.body,
465
+ "sites": n_sites, "changelog_sites": n_changelog_sites,
466
+ "superseded": superseded, "unresolved": unresolved, "concept": concept, "current": current,
467
+ "unscannable": [{"file": f, "reason": e} for f, e in unscannable],
468
+ # 🟥 기계 소비자에게 «어디인지» 를 준다 — 초판은 id 만 주고 file:line 이 0 이었다(B-1)
469
+ "sites_by_id": {rid: [[f, n, sn] for f, n, sn in v] for rid, v in candidates.items()},
470
+ "verdicts": verdicts,
471
+ "summary": {"superseded": len(superseded), "unresolved": len(unresolved),
472
+ "concept": len(concept), "current": len(current),
473
+ "changelog_excluded": len(changelog),
474
+ "unscannable": len(unscannable), "rc": rc},
475
+ }, ensure_ascii=False, indent=1, default=str))
476
+ return rc
477
+
478
+ for rid in superseded:
479
+ v = verdicts[rid]
480
+ print(" 🟥 SUPERSEDED [%s] cited ×%d — %s" % (rid, len(candidates[rid]), where(candidates[rid])))
481
+ print(" family %s — current version is [%s] (%s), this citation points at an old one"
482
+ % (v.get("concept"), v.get("latest_id"), v.get("latest_doi")))
483
+ for rid in unresolved:
484
+ v = verdicts[rid]
485
+ print(" 🟥 UNRESOLVED [%s] cited ×%d — %s — %s" % (rid, len(candidates[rid]), where(candidates[rid]), v.get("detail")))
486
+ for rid in concept:
487
+ print(" ⬜ CONCEPT [%s] cited ×%d — %s — always resolves to current, not stale by construction"
488
+ % (rid, len(candidates[rid]), where(candidates[rid])))
489
+ for rid in current:
490
+ print(" ⬜ CURRENT [%s] cited ×%d — %s — this version IS the latest in its family"
491
+ % (rid, len(candidates[rid]), where(candidates[rid])))
492
+ for f, err in unscannable:
493
+ print(" 🟥 UNSCANNABLE [%s] — %s — NOT scanned. «읽지 못한 것» 은 «깨끗함» 이 아니다"
494
+ % (os.path.basename(f), err))
495
+ for rid in sorted(changelog):
496
+ print(" ⬜ CHANGELOG-EXCLUDED [%s] ×%d — %s — after a Changelog heading, not counted as a live citation"
497
+ % (rid, len(changelog[rid]), where(changelog[rid])))
498
+
499
+ print("stale-ref verdict: SUPERSEDED=%d UNRESOLVED=%d UNSCANNABLE=%d CONCEPT=%d CURRENT=%d "
500
+ "CHANGELOG-EXCLUDED=%d rc=%d"
501
+ % (len(superseded), len(unresolved), len(unscannable), len(concept), len(current),
502
+ len(changelog), rc))
503
+ if superseded or unresolved:
504
+ print("ⓘ review surface — a stale citation may be intentional (pinning a past claim); confirm by eye "
505
+ "before editing. §Pre-Publish Surface Gate's Step 1b (draft API / md5 / machine fields) is the "
506
+ "deposit-time counterpart of this check.")
507
+ return rc
508
+
509
+
510
+ if __name__ == "__main__":
511
+ sys.exit(main())