@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.
- package/.claude-plugin/marketplace.json +4 -4
- package/CLAUDE.md +8 -4
- package/bin/fh-codex-doctor.js +223 -25
- package/knowledge/shared/harness-core/claude_md_gate_details.md +8 -4
- package/knowledge/shared/harness-core/governance_engineering_definition.md +403 -7
- package/knowledge/shared/learnings/subagent_invocations_log.yaml +99 -0
- package/package.json +268 -257
- package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-meta/CHANGELOG.md +54 -0
- package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
- package/scripts/citation_key_check.py +357 -0
- package/scripts/claim_propagation_scan.py +499 -0
- package/scripts/numeric_token_diff.py +389 -0
- package/scripts/outbound_pr_gate.sh +283 -0
- package/scripts/package_coverage_check.sh +10 -0
- package/scripts/section_ref_check.py +591 -0
- package/scripts/selfcheck.sh +111 -0
- package/scripts/session_checklist.py +704 -0
- package/scripts/test_claim_propagation_lanes.sh +573 -0
- package/scripts/test_codex_doctor_root_lanes.sh +384 -0
- package/scripts/test_outbound_pr_gate_lanes.sh +214 -0
- package/scripts/test_paper_integrity_lanes.sh +1473 -0
- package/scripts/test_session_checklist_lanes.sh +746 -0
- package/templates/predelete_check.sh +28 -4
|
@@ -1,5 +1,59 @@
|
|
|
1
1
|
# forge-harness (fh-meta) Changelog
|
|
2
2
|
|
|
3
|
+
### [3.13.0] — 2026-09-19 — 규칙은 있었고 배선이 없었다, 두 자리
|
|
4
|
+
|
|
5
|
+
**minor — 새 자산 하나(발신 전 3프로브 훅)와 발행 확인 계기 하나가 늘었다.**
|
|
6
|
+
🟢 **게이트 수용을 깨는 변경은 없다** (`BREAKING (gate):` 줄 불요) — `outbound_pr_gate.sh` 는 파일로
|
|
7
|
+
출하되지만 **어떤 settings 스니펫에도 배선되지 않는다**(기계 확인: 컨트롤 `outbound_query_hook` 은
|
|
8
|
+
`templates/settings.PreToolUse.snippet.json` 에 히트, 이것은 0). deny 를 내는 훅이라
|
|
9
|
+
`outbound_query_hook` 과 **같은 처분**이다 — 배선은 운영자 결정으로 남긴다.
|
|
10
|
+
|
|
11
|
+
- **발신 전 3프로브 훅 (`scripts/outbound_pr_gate.sh`, #754)** — PreToolUse(Bash), 비소유 레포에 PR 을
|
|
12
|
+
«열기 직전» 에 건다. 실측 근거: 비소유 레포 outbound 9건 중 기술 결함 지적 3건이 **전부 같은 형태**였다 —
|
|
13
|
+
우리 가드와 테스트가 «대상의 모형» 위에서 돌았고 메인테이너의 증거는 우리가 한 번도 안 돌린 실행이었다.
|
|
14
|
+
규칙(§Skeleton-Not-Muscle · §7 standpoint enum)은 이미 있었고 **배선이 0** 이었다.
|
|
15
|
+
레인 25(경로/인용 형태 · 변수간접 **잔여 핀** · enum 클래스닫힘 · 되돌림 프로브).
|
|
16
|
+
- **발행 «확인» 을 발행 «판정» 에서 분리 (`scripts/publish_verify_poll.sh`, #754)** — verify 단계는
|
|
17
|
+
발행을 판정하지 않는다. 앞 단계 `npm publish` 가 이미 rc=0 이므로 여기서 보는 것은 읽기 복제본 전파뿐이다.
|
|
18
|
+
종전 60초 인라인 루프가 **성공한 v3.12.0 발행을 빨간 잡으로** 만들었고(판별 = 레지스트리 멱등성),
|
|
19
|
+
그 빨강이 v3.2.0·v3.4.0 에서 손 발행을 훈련시켜 OIDC 경로를 깨뜨렸다. 예산 5분 + 판정은 `outcome=`,
|
|
20
|
+
종료코드는 **계기 오류에만**. 레인 16.
|
|
21
|
+
- **cross-family(codex)가 S급 2 + A급 4 를 냈고 넷을 고쳤다** — `|| true` 가 계기 오류를 삼켜 조회기
|
|
22
|
+
부재를 `not_yet_visible` 로 내보내던 것 · 출력 채널 부재 시 판정이 사라지던 것 · `${{ }}` 셸 주입 ·
|
|
23
|
+
경로/인용 형태 트리거 미탐. ⚠️ **A3 주장 7건 중 5건은 실측으로 반증**했다(종전 정규식으로도 잡힌다) —
|
|
24
|
+
받은 것을 그대로 옮기지 않았다.
|
|
25
|
+
- 🟥 **selfcheck 와 CI 가 저자의 배선 구멍 셋을 잡았다** — 레인을 페어링 «선언만» 하고 실행 블록 미첨부 ·
|
|
26
|
+
출하 문서가 이름을 대는데 `files[]` 부재 · 스텁을 shim 으로만 간접 호출(MENTION_ONLY/zero-caller).
|
|
27
|
+
마지막 것을 선언(EXEMPT)으로 안 빼고 **직접 실행 레인**으로 닫자 **스텁 자기 계약이 한 번도 검증된 적
|
|
28
|
+
없었다**는 것이 드러났다.
|
|
29
|
+
|
|
30
|
+
**안 닫은 것**: 변수 간접(`$GH_CMD`)·alias·gh 래퍼는 정규식으로 못 닫는다(레인이 **고정만** 한다) ·
|
|
31
|
+
`gh pr edit --body` 는 NAMED GAP · `echo gh pr create` 과차단 1건(막는 쪽이라 유지) ·
|
|
32
|
+
소비자 install 에서 publish-verify 레인은 **SKIP**(SKIP 은 PASS 가 아니다).
|
|
33
|
+
|
|
34
|
+
### [3.12.0] — 2026-09-18 — 논문이 계기를 낳고, 계기가 저자를 잡은 밤
|
|
35
|
+
|
|
36
|
+
**minor — 새 계기(논문 무결성 3종 · 철회 숫자 전파 스캐너 · 세션 요청 체크리스트)가 늘었고, `fh-codex-doctor` 의
|
|
37
|
+
`--json` 계약이 바뀐다(`inputErrors` 필드 · 종료코드 붕괴 3건 수리).** 게이트 수용을 깨는 변경은 **없다**
|
|
38
|
+
(`BREAKING (gate):` 줄 불요 — 새 계기는 전부 advisory 이고 커밋 게이트에 안 건다).
|
|
39
|
+
|
|
40
|
+
- **`fh-codex-doctor` 과차단 수리 (#745)** — 출하 바이너리가 **읽지도 않는** `package.json` 으로 문을 잠가
|
|
41
|
+
모든 비-npm 소비자를 거절했다(rc=11). 같은 결함족 둘 더: 빈 `plugins/` 가 «OK · 0 scanned · rc=0»(역방향) ·
|
|
42
|
+
`collectAgents()` 하드코딩 네임스페이스. cross-family 가 종료코드 붕괴 3건 추가 적발. `--json` 에
|
|
43
|
+
`inputErrors` — 옛 rc=11 의존 호출부 0건 확인.
|
|
44
|
+
- **논문 무결성 계기 3종 (#749)** — `citation_key_check.py`(인용키 used↔defined + 근사키 + MALFORMED) ·
|
|
45
|
+
`numeric_token_diff.py`(재작성 전후 숫자 토큰 DROPPED/INVENTED — 부호·지수·전각·범위) · `section_ref_check.py`
|
|
46
|
+
(§/Section/섹션/N절/부록/K.n → 헤딩 해석, 범위 내부 포함). 레인 73. 🟥 cross-family 열여덟 라운드가 무음 결함
|
|
47
|
+
40 을 하나씩 잡았다 — 같은 계열 known-pair 는 매 라운드 초록이었다. 실논문에 실제로 돌려 고아 인용 1 을 편집.
|
|
48
|
+
- **철회된 숫자의 전파 스캐너 `claim_propagation_scan.py` (#748)** — 정본이 철회한 수치가 다른 파일에 살아남는
|
|
49
|
+
것을 잡는다(식별자 전파는 `halffix_propagation_scan.sh` 가, 주장 전파는 이것이). 레인 28.
|
|
50
|
+
- **세션 요청 체크리스트 `session_checklist.py` (#750)** — 운영자 발화를 두 채널(raw 전사본 + 압축 요약)에서 전부
|
|
51
|
+
뽑아 «달성 상태 · 사유 · 이월 제안» 결과서의 형식을 검사한다. 공정 말미의 «영혼 다지기». 첫 실사용에서 저자의
|
|
52
|
+
손표 한 행을 잡았다. 마감 체인 미배선(advisory).
|
|
53
|
+
- **정본·상주층 정정** — 5팔 표(2.7~13.6 %) 철회 → 4팔 스펙트럼(0.0~1.1 %)로 교체(#743) · «Axis 1 은 안 돈다» 낡은 CI
|
|
54
|
+
서술 여섯 자리 정정(#746) · 간판 둘째 동사 «상주» → «플로어에서 발화한다(측정)»(#747) · 선행조사 4·5라운드 +
|
|
55
|
+
formal model(#744) · `predelete_check.sh` 가 유령 원격 ref 236 을 회수 대상으로 보고하던 것 수리(#742).
|
|
56
|
+
|
|
3
57
|
### [3.11.0] — 2026-09-17 — 세 번째 레지스터, 그리고 「목록을 손으로 다시 적던」 자리들
|
|
4
58
|
|
|
5
59
|
**minor — 새 자산(낭독 레지스터)이 늘었고 행동이 바뀐다.** 게이트 수용을 깨는 변경은 **없다**
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""citation_key_check.py — every citation key a paper USES is DEFINED, and every DEFINED key is USED.
|
|
3
|
+
|
|
4
|
+
WHAT IT CLOSES (measured 2026-09-17, paper-2 draft, the night the sister paper had been rejected by
|
|
5
|
+
arXiv for 11/17 reference mismatches)
|
|
6
|
+
The governor had to check citation-key integrity BY HAND with ad-hoc python. Two live defects that
|
|
7
|
+
night: `[EBP18]` was cited in §9.4 and had NO row in the references table (a PHANTOM), and `[MF24]`
|
|
8
|
+
was cited where the table's row read `[MF22]` — the arXiv-posting year had been used as the key
|
|
9
|
+
while the journal year is 2022 (a NEAR-MISS: same letters, different year). A plain used-vs-defined
|
|
10
|
+
diff reports that second case as one phantom PLUS one orphan and never says they are the same key,
|
|
11
|
+
so a renumbering can silently orphan the row and phantom the citation at once. This tool pairs them.
|
|
12
|
+
|
|
13
|
+
WHAT IT DOES NOT DO — read before trusting a 0
|
|
14
|
+
🟥 It checks KEY integrity, not bibliographic truth. A key that is used and defined can still point
|
|
15
|
+
at a row whose title, year, venue or DOI is wrong — that is `phantom-quench` / the refs table's
|
|
16
|
+
own «확인» column, not this tool.
|
|
17
|
+
🟥 Keys inside code spans (`[K26]`, fenced blocks) are MENTIONS, not citations — a paper's own
|
|
18
|
+
«citation verification» table names keys that way. They are counted separately and printed, never
|
|
19
|
+
silently dropped; `--count-code` turns them into usages if a body really cites in code style.
|
|
20
|
+
🟥 A definition row is recognised ONLY by the house table shape: the row's FIRST cell is `[KEY]`
|
|
21
|
+
(`| [C70] | Chow … |`, bold allowed). A bibliography written as a list is invisible → rc=10, not
|
|
22
|
+
«all phantom». The whole definition row is excluded from usage counting, so a paper that carries
|
|
23
|
+
its own table in the body still works (the row's note column is not scanned for usages).
|
|
24
|
+
🟥 Grouped citations `[C70, EW10, T24]` are split on `,` / `;`; every element that fully matches the
|
|
25
|
+
key grammar counts. An element that does not (`[C70, p. 41]` → `p. 41`) is ignored, not reported.
|
|
26
|
+
🟥 Keys in a --refs file OUTSIDE its definition rows are NOT usages unless that file is also passed
|
|
27
|
+
as --body (the drop-in prior-art section is both a body and the table — pass it as both).
|
|
28
|
+
|
|
29
|
+
KEY GRAMMAR (house style) [A-Z][A-Za-z]{0,6}\\d{2}[a-z]? e.g. [C70] [EBP18] [BES26a] [OCR26]
|
|
30
|
+
NEAR-MISS two DIFFERENT keys with the same letter prefix (case-insensitive), where at
|
|
31
|
+
least one side is PHANTOM or ORPHAN — [MF24]↔[MF22], [BES26]↔[BES26a].
|
|
32
|
+
Two keys both used and both defined are two papers, not a near-miss.
|
|
33
|
+
`--no-near-miss` disables the pairing (ablation / revert probe).
|
|
34
|
+
|
|
35
|
+
EXIT CODES
|
|
36
|
+
0 scanned, every used key defined, every defined key used (orphans listed but not counted)
|
|
37
|
+
1 PHANTOM (used, undefined) or DUP-DEF (one key defined twice)
|
|
38
|
+
2 no phantom, but ORPHAN keys present and --strict-orphans was given
|
|
39
|
+
4 DEAD CONTROL: the body yields ZERO citation usages — a paper with no citations is not
|
|
40
|
+
«clean», it is unscanned (mentions-only counts as zero). Distinct from 0 on purpose.
|
|
41
|
+
10 input error (file missing / unreadable · 0 definition rows parsed from the references table)
|
|
42
|
+
|
|
43
|
+
USAGE
|
|
44
|
+
python3 scripts/citation_key_check.py --body <md...> [--refs <md...>] [--strict-orphans]
|
|
45
|
+
[--count-code] [--no-near-miss] [--json]
|
|
46
|
+
bash scripts/test_paper_integrity_lanes.sh # known pairs + revert probe
|
|
47
|
+
Python ≥ 3.9, stdlib only.
|
|
48
|
+
"""
|
|
49
|
+
import argparse
|
|
50
|
+
import json
|
|
51
|
+
import os
|
|
52
|
+
import re
|
|
53
|
+
import sys
|
|
54
|
+
import unicodedata
|
|
55
|
+
|
|
56
|
+
KEY = r"[A-Z][A-Za-z]{0,6}\d{2}[a-z]?"
|
|
57
|
+
KEY_RE = re.compile(r"^" + KEY + r"$")
|
|
58
|
+
# 🟥 v3 (codex round 2, 2026-09-18): `[BAD–26]` — letters, a Unicode dash, digits — is a citation the
|
|
59
|
+
# reader SEES and the table cannot match, and v2 skipped it silently because it failed KEY_RE. A key
|
|
60
|
+
# with any dash/underscore between letters and year is MALFORMED: reported and counted, never
|
|
61
|
+
# normalized away (a typo the reader sees is a defect even when a human would guess the row).
|
|
62
|
+
MALFORMED_RE = re.compile(r"^[A-Z][A-Za-z]{0,6}[\-‐‑‒–—−_]\d{2}[a-z]?$")
|
|
63
|
+
# v10 (codex round 9): `[mf22]` — key-shaped but case-mismatched — cannot match the house table either
|
|
64
|
+
CASE_RE = re.compile(r"^[A-Za-z]{1,7}[\-‐‑‒–—−_]?\d{2}[A-Za-z]?$") # v11: `[BES26A]` too
|
|
65
|
+
BRACKET_RE = re.compile(r"\[([^\[\]\n]{1,160})\]")
|
|
66
|
+
# v7 (codex round 6): a definitions table inside a blockquote (`> | [KEY] | … |`) is still the visible table
|
|
67
|
+
DEF_ROW_RE = re.compile(r"^\s*(?:>\s*)*\|\s*(?:\*\*)?\[(" + KEY + r")\](?:\*\*)?\s*\|")
|
|
68
|
+
CODE_SPAN_RE = re.compile(r"`[^`\n]*`")
|
|
69
|
+
LETTERS_RE = re.compile(r"^([A-Za-z]+)\d{2}[a-z]?$")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def letters(key):
|
|
73
|
+
m = LETTERS_RE.match(key)
|
|
74
|
+
return m.group(1).lower() if m else key.lower()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _elements(text):
|
|
78
|
+
"""Bracket elements, NFKC-normalized (`[MF22]`-style full-width forms read as ASCII)."""
|
|
79
|
+
for m in BRACKET_RE.finditer(unicodedata.normalize("NFKC", text)):
|
|
80
|
+
for el in re.split(r"[,;&、·]|\s+and\s+", m.group(1)): # v14: `[AB24 & ZZ99]` · `[AB24 and ZZ99]` · v17: `[AB24、ZZ99]` · v18: `[AB24 · ZZ99]`
|
|
81
|
+
yield el.strip()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def keys_in(text):
|
|
85
|
+
"""Every key cited in `text`: single `[K26]` and grouped `[C70, EW10]` brackets."""
|
|
86
|
+
return [el for el in _elements(text) if KEY_RE.match(el)]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def malformed_in(text):
|
|
90
|
+
"""Citation-shaped bracket elements that are NOT keys (`[BAD–26]`, `[MF-22]`, `[GE_17]`, `[mf22]`)."""
|
|
91
|
+
return [el for el in _elements(text) if not KEY_RE.match(el) and (MALFORMED_RE.match(el) or CASE_RE.match(el))]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
CODE_SPAN_MASK_RE = re.compile(r"`[^`\n]*`")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
FENCE_RE = re.compile(r"^(?:>\s*)*(`{3,}|~{3,})(.*)$")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _fence_step(line, fence):
|
|
101
|
+
"""→ (fence_after, on_fence_line). `fence` = (char, opener length) while inside a fenced block, else
|
|
102
|
+
None. v9 (codex round 8) — CommonMark: a closer uses the same char, is at least as long as the
|
|
103
|
+
opener and carries nothing but spaces after it (a 3-tick line does not close a 4-tick fence); a
|
|
104
|
+
`> ` prefix is allowed (a fence inside a blockquote). Kept byte-identical across the three tools."""
|
|
105
|
+
m = FENCE_RE.match(line.lstrip())
|
|
106
|
+
if fence is None:
|
|
107
|
+
return ((m.group(1)[0], len(m.group(1))), True) if m else (None, False)
|
|
108
|
+
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= fence[1] and not m.group(2).strip():
|
|
109
|
+
return None, True
|
|
110
|
+
return fence, False
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def strip_html_comments(text):
|
|
114
|
+
"""v6 (codex round 5): text inside `<!-- … -->` is invisible to the reader, so it is neither a defect
|
|
115
|
+
nor an anchor. 🟥 v7 (codex round 6): the v6 regex strip ERASED PROSE between a `<!--` and a `-->`
|
|
116
|
+
that sat inside code spans or fenced blocks — a delimiter inside code is a literal. 🟥 v8 (codex
|
|
117
|
+
round 7): the same for `~~~` fences and 4-space / tab INDENTED code blocks (a block starts after a
|
|
118
|
+
blank line and runs while lines stay indented). v9: fences go through _fence_step (opener length ·
|
|
119
|
+
blockquote prefix). Fences and indented code are left untouched, code spans are masked before a
|
|
120
|
+
delimiter is looked for. Line numbers are preserved; comment text becomes spaces. Kept
|
|
121
|
+
byte-identical in the three tools (lanes L11l / L11o / L11q pin all three)."""
|
|
122
|
+
out, fence, in_comment, prev_blank, prev_code = [], None, False, True, False
|
|
123
|
+
for line in text.split("\n"):
|
|
124
|
+
if in_comment:
|
|
125
|
+
j = line.find("-->")
|
|
126
|
+
if j < 0:
|
|
127
|
+
out.append(" " * len(line))
|
|
128
|
+
continue
|
|
129
|
+
line, in_comment = " " * (j + 3) + line[j + 3:], False
|
|
130
|
+
s = line.strip()
|
|
131
|
+
fence, on_fence = _fence_step(line, fence)
|
|
132
|
+
if on_fence or fence is not None:
|
|
133
|
+
out.append(line)
|
|
134
|
+
prev_blank, prev_code = False, False
|
|
135
|
+
continue
|
|
136
|
+
indented = (line.startswith(" ") or line.startswith("\t")) and (prev_blank or prev_code)
|
|
137
|
+
if indented:
|
|
138
|
+
out.append(line)
|
|
139
|
+
prev_blank, prev_code = False, True
|
|
140
|
+
continue
|
|
141
|
+
prev_blank, prev_code = (s == ""), False
|
|
142
|
+
masked = CODE_SPAN_MASK_RE.sub(lambda m: " " * len(m.group(0)), line)
|
|
143
|
+
res, pos = [], 0
|
|
144
|
+
while True:
|
|
145
|
+
i = masked.find("<!--", pos)
|
|
146
|
+
if i < 0:
|
|
147
|
+
res.append(line[pos:])
|
|
148
|
+
break
|
|
149
|
+
res.append(line[pos:i])
|
|
150
|
+
j = line.find("-->", i + 4)
|
|
151
|
+
if j < 0:
|
|
152
|
+
res.append(" " * (len(line) - i))
|
|
153
|
+
in_comment = True
|
|
154
|
+
break
|
|
155
|
+
res.append(" " * (j + 3 - i))
|
|
156
|
+
pos = j + 3
|
|
157
|
+
out.append("".join(res))
|
|
158
|
+
return "\n".join(out)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def load(path):
|
|
162
|
+
try:
|
|
163
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
164
|
+
return strip_html_comments(fh.read()).split("\n"), None
|
|
165
|
+
except OSError as e:
|
|
166
|
+
return None, str(e)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def scan_body(path, lines, count_code, used, mentions, malformed):
|
|
170
|
+
"""Fill used[key] / mentions[key] / malformed[element] with (file, line, snippet) sites. Definition
|
|
171
|
+
rows are skipped. MALFORMED elements are collected from prose only — inside a fence or a code span
|
|
172
|
+
they are text, like every other key there."""
|
|
173
|
+
fence = None # v8/v9: ``` and ~~~ fences via _fence_step (opener length · `> ` prefix)
|
|
174
|
+
for i, line in enumerate(lines, 1):
|
|
175
|
+
s = line.strip()
|
|
176
|
+
fence, on_fence = _fence_step(line, fence)
|
|
177
|
+
if on_fence:
|
|
178
|
+
continue
|
|
179
|
+
in_fence = fence is not None
|
|
180
|
+
if not in_fence and DEF_ROW_RE.match(line):
|
|
181
|
+
continue # a definition row is not a citation of itself
|
|
182
|
+
snippet = s[:110]
|
|
183
|
+
if in_fence and not count_code:
|
|
184
|
+
for k in keys_in(line):
|
|
185
|
+
mentions.setdefault(k, []).append((path, i, snippet))
|
|
186
|
+
continue
|
|
187
|
+
if count_code:
|
|
188
|
+
prose, code = line, ""
|
|
189
|
+
else:
|
|
190
|
+
prose = CODE_SPAN_RE.sub(" ", line)
|
|
191
|
+
code = " ".join(CODE_SPAN_RE.findall(line))
|
|
192
|
+
for k in keys_in(prose):
|
|
193
|
+
used.setdefault(k, []).append((path, i, snippet))
|
|
194
|
+
for k in malformed_in(prose):
|
|
195
|
+
malformed.setdefault(k, []).append((path, i, snippet))
|
|
196
|
+
for k in keys_in(code):
|
|
197
|
+
mentions.setdefault(k, []).append((path, i, snippet))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def scan_defs(path, lines, defined):
|
|
201
|
+
"""🟥 v8 (codex round 7): a `| [KEY] |` row INSIDE a code fence is code, not a definition — v7 counted
|
|
202
|
+
it, so a key whose only «definition» was a quoted table read as defined."""
|
|
203
|
+
fence = None
|
|
204
|
+
for i, line in enumerate(lines, 1):
|
|
205
|
+
fence, on_fence = _fence_step(line, fence)
|
|
206
|
+
if on_fence or fence is not None:
|
|
207
|
+
continue
|
|
208
|
+
m = DEF_ROW_RE.match(line)
|
|
209
|
+
if m:
|
|
210
|
+
defined.setdefault(m.group(1), []).append((path, i))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def near_miss_pairs(phantom, orphan, used, defined):
|
|
214
|
+
problematic = set(phantom) | set(orphan)
|
|
215
|
+
pool = set(used) | set(defined)
|
|
216
|
+
pairs = {}
|
|
217
|
+
for x in sorted(problematic):
|
|
218
|
+
for y in sorted(pool):
|
|
219
|
+
if y == x or letters(x) != letters(y):
|
|
220
|
+
continue
|
|
221
|
+
a, b = sorted((x, y))
|
|
222
|
+
pairs[(a, b)] = True
|
|
223
|
+
return sorted(pairs)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def role(k, phantom, orphan, used, defined):
|
|
227
|
+
tags = []
|
|
228
|
+
if k in phantom:
|
|
229
|
+
tags.append("PHANTOM")
|
|
230
|
+
if k in orphan:
|
|
231
|
+
tags.append("ORPHAN")
|
|
232
|
+
if not tags:
|
|
233
|
+
tags.append("ok")
|
|
234
|
+
if k in used:
|
|
235
|
+
tags.append("used ×%d" % len(used[k]))
|
|
236
|
+
if k in defined:
|
|
237
|
+
tags.append("defined %s" % ", ".join("%s:%d" % (os.path.basename(f), n) for f, n in defined[k]))
|
|
238
|
+
return " · ".join(tags)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def main():
|
|
242
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
243
|
+
ap.add_argument("--body", nargs="+", required=True, metavar="MD", help="body file(s) whose citations are checked")
|
|
244
|
+
ap.add_argument("--refs", nargs="*", default=[], metavar="MD",
|
|
245
|
+
help="file(s) carrying the references table (`| [KEY] | … |`); definition rows found in --body files count too")
|
|
246
|
+
ap.add_argument("--strict-orphans", action="store_true", help="a defined-but-unused key fails (rc=2)")
|
|
247
|
+
ap.add_argument("--count-code", action="store_true", help="keys inside code spans / fences count as usages, not mentions")
|
|
248
|
+
ap.add_argument("--no-near-miss", action="store_true", help="disable NEAR-MISS pairing (ablation / revert probe)")
|
|
249
|
+
ap.add_argument("--no-malformed", action="store_true",
|
|
250
|
+
help="ABLATION ONLY: skip MALFORMED keys (`[BAD–26]`) — the v2 arm, where they read as clean")
|
|
251
|
+
ap.add_argument("--max-sites", type=int, default=6, help="usage sites printed per phantom key (0 = all)")
|
|
252
|
+
ap.add_argument("--json", action="store_true")
|
|
253
|
+
args = ap.parse_args()
|
|
254
|
+
|
|
255
|
+
files = {}
|
|
256
|
+
for p in list(args.body) + list(args.refs):
|
|
257
|
+
if p in files:
|
|
258
|
+
continue
|
|
259
|
+
lines, err = load(p)
|
|
260
|
+
if lines is None:
|
|
261
|
+
print("🟥 cannot read %s: %s" % (p, err), file=sys.stderr)
|
|
262
|
+
return 10
|
|
263
|
+
files[p] = lines
|
|
264
|
+
|
|
265
|
+
used, mentions, defined, malformed = {}, {}, {}, {}
|
|
266
|
+
for p in args.body:
|
|
267
|
+
scan_body(p, files[p], args.count_code, used, mentions, malformed)
|
|
268
|
+
if args.no_malformed:
|
|
269
|
+
malformed = {}
|
|
270
|
+
for p in dict.fromkeys(list(args.refs) + list(args.body)):
|
|
271
|
+
scan_defs(p, files[p], defined)
|
|
272
|
+
|
|
273
|
+
if not defined:
|
|
274
|
+
print("🟥 0 definition rows parsed from %s — wrong file or wrong shape (expected a table row whose FIRST "
|
|
275
|
+
"cell is `[KEY]`). %d usage(s) of %d key(s) were seen and are NOT reported as phantom. rc=10"
|
|
276
|
+
% (", ".join(args.refs) if args.refs else "the body (no --refs given)",
|
|
277
|
+
sum(len(v) for v in used.values()), len(used)))
|
|
278
|
+
return 10
|
|
279
|
+
n_usages = sum(len(v) for v in used.values())
|
|
280
|
+
n_ment = sum(len(v) for v in mentions.values())
|
|
281
|
+
if n_usages == 0 and not malformed:
|
|
282
|
+
print("⬜ DEAD CONTROL — 0 citation usages in %d body file(s) (%d line(s) read; %d mention(s) in code spans "
|
|
283
|
+
"not counted); %d definition(s) present but NOTHING was checked. rc=4 (not a clean check)."
|
|
284
|
+
% (len(args.body), sum(len(files[p]) for p in args.body), n_ment, len(defined)))
|
|
285
|
+
return 4
|
|
286
|
+
|
|
287
|
+
phantom = sorted(k for k in used if k not in defined)
|
|
288
|
+
orphan = sorted(k for k in defined if k not in used)
|
|
289
|
+
dup = sorted(k for k, sites in defined.items() if len(sites) > 1)
|
|
290
|
+
mention_only = sorted(k for k in mentions if k not in used and k not in defined)
|
|
291
|
+
bad = sorted(malformed)
|
|
292
|
+
pairs = [] if args.no_near_miss else near_miss_pairs(phantom, orphan, used, defined)
|
|
293
|
+
rc = 1 if (phantom or dup or bad) else (2 if (orphan and args.strict_orphans) else 0)
|
|
294
|
+
|
|
295
|
+
if args.json:
|
|
296
|
+
print(json.dumps({
|
|
297
|
+
"body": args.body, "refs": args.refs,
|
|
298
|
+
"count_code": args.count_code, "near_miss_enabled": not args.no_near_miss,
|
|
299
|
+
"used": {k: [{"file": f, "line": n, "snippet": s} for f, n, s in v] for k, v in sorted(used.items())},
|
|
300
|
+
"mentions": {k: [{"file": f, "line": n} for f, n, _ in v] for k, v in sorted(mentions.items())},
|
|
301
|
+
"defined": {k: [{"file": f, "line": n} for f, n in v] for k, v in sorted(defined.items())},
|
|
302
|
+
"phantom": phantom, "orphan": orphan, "dup_def": dup, "mention_only": mention_only,
|
|
303
|
+
"malformed": {k: [{"file": f, "line": n, "snippet": s} for f, n, s in v] for k, v in sorted(malformed.items())},
|
|
304
|
+
"near_miss": [{"a": a, "b": b, "a_role": role(a, phantom, orphan, used, defined),
|
|
305
|
+
"b_role": role(b, phantom, orphan, used, defined)} for a, b in pairs],
|
|
306
|
+
"summary": {"usages": n_usages, "used_distinct": len(used), "defined": len(defined),
|
|
307
|
+
"mentions": n_ment, "phantom": len(phantom), "orphan": len(orphan),
|
|
308
|
+
"near_miss": len(pairs), "dup_def": len(dup), "mention_only": len(mention_only),
|
|
309
|
+
"malformed": len(bad), "rc": rc},
|
|
310
|
+
}, ensure_ascii=False, indent=1))
|
|
311
|
+
return rc
|
|
312
|
+
|
|
313
|
+
print("citation-key check · body=%d file%s (%d usages · %d distinct keys) · refs=%s (%d definitions) · mentions in code=%d%s"
|
|
314
|
+
% (len(args.body), "" if len(args.body) == 1 else "s", n_usages, len(used),
|
|
315
|
+
", ".join(args.refs) if args.refs else "(body rows)", len(defined), n_ment,
|
|
316
|
+
" (counted as usages: --count-code)" if args.count_code else ""))
|
|
317
|
+
print(" mechanisms: near-miss=%s · code-spans=%s · strict-orphans=%s · malformed=%s"
|
|
318
|
+
% ("off" if args.no_near_miss else "on", "usage" if args.count_code else "mention",
|
|
319
|
+
"on" if args.strict_orphans else "off", "off (ABLATION)" if args.no_malformed else "on"))
|
|
320
|
+
for k in bad:
|
|
321
|
+
sites = malformed[k]
|
|
322
|
+
print(" 🟥 MALFORMED [%s] cited ×%d — %s — citation-shaped but not a key (dash/underscore between letters and year); no row can match it"
|
|
323
|
+
% (k, len(sites), " · ".join("%s:%d" % (os.path.basename(f), n) for f, n, _ in sites[:args.max_sites or None])))
|
|
324
|
+
print(" …%s…" % sites[0][2])
|
|
325
|
+
for k in phantom:
|
|
326
|
+
sites = used[k]
|
|
327
|
+
shown = sites if args.max_sites == 0 else sites[:args.max_sites]
|
|
328
|
+
where = " · ".join("%s:%d" % (os.path.basename(f), n) for f, n, _ in shown)
|
|
329
|
+
more = "" if len(shown) == len(sites) else " (+%d more)" % (len(sites) - len(shown))
|
|
330
|
+
print(" 🟥 PHANTOM [%s] used ×%d — %s%s" % (k, len(sites), where, more))
|
|
331
|
+
print(" …%s…" % sites[0][2])
|
|
332
|
+
for k in dup:
|
|
333
|
+
print(" 🟥 DUP-DEF [%s] defined ×%d — %s" % (k, len(defined[k]),
|
|
334
|
+
" · ".join("%s:%d" % (os.path.basename(f), n) for f, n in defined[k])))
|
|
335
|
+
for k in orphan:
|
|
336
|
+
ment = mentions.get(k, [])
|
|
337
|
+
print(" 🟨 ORPHAN [%s] defined %s, used ×0%s" % (
|
|
338
|
+
k, " · ".join("%s:%d" % (os.path.basename(f), n) for f, n in defined[k]),
|
|
339
|
+
(" (mentioned ×%d in code: %s)" % (len(ment), " · ".join("%s:%d" % (os.path.basename(f), n) for f, n, _ in ment[:3]))) if ment else ""))
|
|
340
|
+
for a, b in pairs:
|
|
341
|
+
print(" 🟧 NEAR-MISS [%s] (%s) ↔ [%s] (%s) — same letters, different key"
|
|
342
|
+
% (a, role(a, phantom, orphan, used, defined), b, role(b, phantom, orphan, used, defined)))
|
|
343
|
+
for k in mention_only:
|
|
344
|
+
ment = mentions[k]
|
|
345
|
+
print(" ⬜ MENTION-ONLY [%s] undefined, appears only in code spans ×%d — %s (not a citation; --count-code to count it)"
|
|
346
|
+
% (k, len(ment), " · ".join("%s:%d" % (os.path.basename(f), n) for f, n, _ in ment[:3])))
|
|
347
|
+
if phantom:
|
|
348
|
+
print("ⓘ a PHANTOM key has no row a reader can resolve — this is the class that got the sister paper rejected.")
|
|
349
|
+
if orphan and not args.strict_orphans:
|
|
350
|
+
print("ⓘ ORPHAN keys are listed, not counted (rc unaffected) — --strict-orphans to count them.")
|
|
351
|
+
print("citation-key verdict: PHANTOM=%d ORPHAN=%d NEAR-MISS=%d DUP-DEF=%d MENTION-ONLY=%d MALFORMED=%d rc=%d"
|
|
352
|
+
% (len(phantom), len(orphan), len(pairs), len(dup), len(mention_only), len(bad), rc))
|
|
353
|
+
return rc
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
if __name__ == "__main__":
|
|
357
|
+
sys.exit(main())
|