@chrono-meta/fh-gate 3.15.0 → 3.16.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/knowledge/shared/learnings/subagent_invocations_log.yaml +41 -0
- package/package.json +3 -1
- package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
- package/scripts/selfcheck.sh +18 -0
- package/scripts/stale_ref_scan.py +510 -0
- package/scripts/test_stale_ref_scan_lanes.sh +129 -0
|
@@ -11,25 +11,25 @@
|
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "fh-meta",
|
|
14
|
-
"version": "3.
|
|
14
|
+
"version": "3.16.0",
|
|
15
15
|
"description": "New in 2.2.0: BREAKING (gate): chamber step 6 now reads ACTUAL.md, not BUDGET.md — an in-flight chamber run whose actual cost sits in BUDGET.md blocks until the ACTUAL: line moves to tracks/_chamber/<slug>/ACTUAL.md (the runner prints the path). Why: BUDGET.md's pre-verdict hash IS the ordering witness, and step 6 hard-blocked until that same file changed, so every run that reached COMPLETE necessarily mutated a witnessed artifact and verify returned TAMPERED — the chamber's promotion condition was unsatisfiable by construction, not by strictness. Two roles (immutable witness / post-verdict calibration sink) had collided in one file; each was correct alone, so neither side's code showed the conflict. Also: ko-tech-writer Step 2/4-b scans are now calibration-backed (known-pair fixtures + reproducible command, shipped) — discrimination is proven, 'zero residue' is explicitly NOT; chamber lane suite 12 -> 33 including the runner x witness seam no test covered; chamber_run.sh now teaches the two-commit discipline (gate hashes and verdict hash must land in separate commits/PRs — it previously advised the opposite). New in 2.1.0: BREAKING (gate): `crossfamily: declined` in an Axes 2-3 marker now requires grounds naming a record path that RESOLVES on disk — bare `declined`, and `declined` justified by author judgment, are blocked at commit. Remedy: cite where the operator decision lives (e.g. `.. — operator declined sidecars, per knowledge/shared/rules/operational_adaptation.md`), or use `DEGRADED_PANEL_UNUSED` if a panel was reachable and you chose not to recruit it — which is what author judgment actually is. `declined` was the only enum value with no grounds requirement; a cross-family review then broke the first (vocabulary-grep) fix three ways — self-validating on the value's own token, vacuous keyword passes, and over-blocking real declinations in natural prose — so the check asserts a resolvable record instead of words. Also: standpoint axis gains `tier1b` (a STATIC read of a target repo, executed nothing) plus a decide-in-order procedure, after blind floor-tier sims graded pure cold-reads as `tier2` three rounds running; steel-quench Wave 1's sixth angle (gate-locality) gains the output-template row it never had, so a mandatory angle stops being structurally unreportable; verify-bidirectional gains category 5 (prescriptive doctrine statement); Sister Asset Protocol gains an active-adoption trigger; new resident doctrine — Mechanization Boundary, Local Execution First, Skeleton-not-Muscle, Expedition track, and this package's versioning policy. Hub meta-operations toolkit — 35 skills + 7 agents. New in 2.0.1: harness-doctor cadence hook, portability lint wired into pre-commit, branch_claim.sh claim-count-vs-tree-count warning, louder confidentiality-scan fail-open notice, fh-gate.sh missing-package.json survival, identity ① reclassified 🟢 (cross-harness adapters + relay argument channel). New in 1.4.53: `fh-codex-doctor` (npm bin) — Codex adapter drift scanner; reads the documented M1/M2/M3 skill tier map + skill/agent source and reports codex-native/adapter-required/claude-native/unclassified per unit, wired into `npm test`/`prepublishOnly` (fail-closed on unclassified Claude-native primitives). New in 1.4.49: steel-quench gains Step 0.6 Verdict-Invariance Probe (groundedness axis — a load-bearing judged gate's verdict must track behavior, not rubric phrasing; measured flip-count over cross-family paraphrases; arXiv:2605.06161 Policy Invariance anchor); multi_model_sidecar_strategy §Vendor-native harness (a model is strongest in its own vendor CLI — Claude/CC, GPT/codex, Gemini/Antigravity; a universal router degrades all of them, so it stays an autocomplete/QA sidecar, never orchestration); predelete_check.sh fail-closed rewrite; memory-hygiene A-TMA anchor. New in 1.4.48: phantom-quench + steel-quench gain external frontier anchors (arXiv:2607.02052 package-hallucination; arXiv:2607.02057 prompt-coverage-adequacy); README model-flat claim reframed from a per-release point-curve to structural invariants (operation flattens across tiers; depth tier-order fixed within a generation). New in 1.4.47: onboarding step ① surfaces the Mode D companion-store session-start load in the auto-read salience anchor (previously only in the local binding + rules, so a greeting could skip the load). New in 1.4.46: context-doctor command-output axis (route to rtk/proxy for verbose CLI stdout, complementing .claudeignore; risk-gated to token-scarce envs). New in 1.4.41: context-doctor 2026 trigger vocab (context engineering/rot/collapse) + phantom-citation hardening; hub measurement-integrity-checklist (cross-model measurement pre-flight: display-name pin/reps≥3/discriminating probe). New in 1.4.40: install-wizard queryable-wiki scaffold (INDEX + session-start read + R/W/C ingest). New in 1.4.39: auto-decorrelation (cross-family verifier sidecar recruitment) + video-ingest (capability-routed video ingestion). New in 1.4.x: verify-axis check-class taxonomy (mandatory-pass/measured/judged), no-reinvention Tier-0 inventory, 7-class failure taxonomy, Destructive-Op Gate, Wave-T (Temper), tier-floor governance, Mode D Model Notice, FC consent lane, default-Sonnet guidance. New in 1.3.0: public-surface-audit, field-harvest Mode B auto-trigger, 4-axis gate scope ext. Validated cross-CLI: Claude Code, Codex, Gemini.",
|
|
16
16
|
"source": "./plugins/fh-meta"
|
|
17
17
|
},
|
|
18
18
|
{
|
|
19
19
|
"name": "fh-commons",
|
|
20
|
-
"version": "3.
|
|
20
|
+
"version": "3.16.0",
|
|
21
21
|
"description": "Project-agnostic utility skills — 6 skills (convergence-loop · deliberation · mcp-circuit-breaker · token-budget-gate · ko-tech-writer · persona-cast) + 7 agents (quench-challenger + the web-review cast: designer · ux-writer · fe-dev · be-dev · qa · a11y). Domain-independent utilities transplantable into any project.",
|
|
22
22
|
"source": "./plugins/fh-commons"
|
|
23
23
|
},
|
|
24
24
|
{
|
|
25
25
|
"name": "fh-qp",
|
|
26
|
-
"version": "3.
|
|
26
|
+
"version": "3.16.0",
|
|
27
27
|
"description": "QP (Quality Platform) — the generic edition of a field QA harness's Prepare→Automation→Regression loop as an FH plugin: 4 skills (qp router · qp-plan · qp-run · qp-regress) + qp_tools.sh (target-class · adapter-probe · mask · surface-reach · mtm-check · run-verbs, typed exit codes) + a zero-domain-constant profile slot + 29 known-pair lanes. Drives web targets through the session's Playwright MCP and desktop targets through computer-use MCP (mobile deferred); calls a registered qasp typed capability when one exists (strictest-wins) — none is registered today, so the MCP fallback is the first edition. Verdict contract: a MACHINE closure requires a recorded assertion; a failed first step is attributed BLOCKED, not FAIL; surface_reach counts every TC in the denominator. Born as chamber run #18 (EMIT, 2026-09-05).",
|
|
28
28
|
"source": "./plugins/fh-qp"
|
|
29
29
|
},
|
|
30
30
|
{
|
|
31
31
|
"name": "fh-preprep",
|
|
32
|
-
"version": "3.
|
|
32
|
+
"version": "3.16.0",
|
|
33
33
|
"description": "preprep — a presentation-preparation harness. 1 skill. One CLI over 17 lanes (7 built-in + 10 module) that reads a declared surface manifest and checks a talk's assets against each other: canonical terms, jargon glosses, retired vocabulary, inter-slide dependencies, pacing, get/put round-trips, adjacent duplication, slide relations, geometry, attribute consistency, fonts, diagrams, slide refs, and screen-parity between manuscript and deck. Verdict contract: exit 0 pass / 1 findings / 2 cannot-judge — a surface that could not be read is UNMEASURED, never 0. Promoted out of fh-commons 2026-09-13 after the skill grew past one role (routing / lane modules / fixtures).",
|
|
34
34
|
"source": "./plugins/fh-preprep"
|
|
35
35
|
}
|
|
@@ -4213,3 +4213,44 @@
|
|
|
4213
4213
|
|
|
4214
4214
|
🟥 통합 엔트리인 이유: 13건을 낱개로 적으면 위 네 줄이 묻힌다. 그리고 총계 미기입이
|
|
4215
4215
|
이 원장의 금지 사항이지 통합 자체는 아니다.
|
|
4216
|
+
|
|
4217
|
+
- date: 2026-09-20
|
|
4218
|
+
agent: "하루 전체 — 적대검증 1 + 병렬 2(사망) + 재발명 1(사망) (통합 엔트리)"
|
|
4219
|
+
purpose: "stale_ref_scan 적대검증 · 낡은주장 스캐너(중복) · 신호 중복판정 재검"
|
|
4220
|
+
dispatch_count: 4 # 🟥 내가 «이름으로 아는» 것만 4. 아래 미계상 참조
|
|
4221
|
+
sidecar_count: 0 # 외부 계열 0 — opus challenger 는 동계열이다
|
|
4222
|
+
outcome: partial
|
|
4223
|
+
evidence: |
|
|
4224
|
+
🟥 **먼저 못 센 것부터 적는다.** 마감 게이트가 «오늘 154 디스패치» 라고 말했는데,
|
|
4225
|
+
나는 그중 **넷만 이름으로 안다.** 나머지는 압축 이전 세션들의 것이고 이 컨텍스트에
|
|
4226
|
+
안 남았다. 총계를 지어내지 않는다 — `dispatch_count` 는 **내가 아는 수**이고,
|
|
4227
|
+
훅 탤리(154)와 다르다는 사실을 여기 적는 것이 이 엔트리의 첫 값이다.
|
|
4228
|
+
([[feedback_not_found_is_not_zero_family]] — «못 셌다» 를 «0» 으로도 «154» 로도 접지 않는다)
|
|
4229
|
+
|
|
4230
|
+
── 이름으로 아는 넷 ──
|
|
4231
|
+
|
|
4232
|
+
① **`fh-meta:challenger` (opus) — `scripts/stale_ref_scan.py` 적대검증** → accepted
|
|
4233
|
+
반환: S 1 · A 8 · B 7 · *"머지하지 마라"*. 🟥 **자기가 아무것도 못 돌린다고 명시**했다
|
|
4234
|
+
(Bash 없음). 내가 무거운 셋을 직접 확인했고 **셋 다 참**이었다:
|
|
4235
|
+
· S-1 PDF 가 `0 sites · rc=0` — 깨끗한 스캔과 **바이트가 같은 출구**
|
|
4236
|
+
· A-2 `# forge-harness (fh-meta) Changelog` 를 changelog 로 못 알아봄
|
|
4237
|
+
· A-4 `scan_body → return []` 로 죽여도 **SELF-CHECK: PASS 4/4**
|
|
4238
|
+
6건 수리 · 7건(A-1·A-3·A-8·B-2·B-4·B-5·B-7)은 마커에 이름으로 남김.
|
|
4239
|
+
⇒ **도구를 못 돌리는 팔이 337줄 중 24줄짜리 증거를 잡아냈다.** 이 엔트리의 하중선.
|
|
4240
|
+
|
|
4241
|
+
② **낡은주장 스캐너 신설 지시** → rejected (내 잘못)
|
|
4242
|
+
🟥 같은 일을 하는 계기가 **이미 셋** 있었다(`halffix_propagation_scan.sh` ·
|
|
4243
|
+
`claim_propagation_scan.py` · `doc_claim_triad_scan.py`). **재발명 게이트를 안 돌렸다.**
|
|
4244
|
+
팔이 600초 무진전으로 죽어서 그 덕에 잡혔다 — 안 죽었으면 네 번째가 생겼을 것이다.
|
|
4245
|
+
|
|
4246
|
+
③④ **병렬 2건(낡은주장 스캐너 · 신호 중복판정 재검)** → rejected
|
|
4247
|
+
둘 다 600초 무진전 사망, 산출 0. 원인 추정 = 프롬프트가 넓고 «읽을 것» 이 많았다(미확정).
|
|
4248
|
+
뒤 프롬프트부터 «20분 안에 못 끝내면 거기까지 보고해라» 를 붙였다.
|
|
4249
|
+
|
|
4250
|
+
── 그래서 오늘 배운 것 ──
|
|
4251
|
+
|
|
4252
|
+
🟥 **적발의 주력이 에이전트가 아니었다.** 오늘 실제 적발 축은 ⓐ 운영자의 실물 관찰
|
|
4253
|
+
(점 크기 · 점 미끄러짐 · 기울기 오판 · 사각 테두리 · 기괴한 눈동자 · 급 멈춤)과
|
|
4254
|
+
ⓑ 되돌림 프로브(자기참조 레인 · 약한 known-pair)였다.
|
|
4255
|
+
디스패치는 ①에서 **한 번** 크게 벌었고, ②③④는 **내 발주 품질** 문제로 0을 냈다.
|
|
4256
|
+
⇒ 다음 회차의 레버는 «더 많이 띄우기» 가 아니라 **재발명 게이트 선행 + 좁은 임무문**이다.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chrono-meta/fh-gate",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.16.0",
|
|
4
4
|
"description": "FH runtime adapters — run FH governance, skills, and agents via Claude or Codex with machine-parseable gates.",
|
|
5
5
|
"homepage": "https://github.com/chrono-meta/forge-harness#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -224,6 +224,7 @@
|
|
|
224
224
|
"scripts/sidecar_wait.sh",
|
|
225
225
|
"scripts/sim_isolated_run.sh",
|
|
226
226
|
"scripts/stale_clone_guard.sh",
|
|
227
|
+
"scripts/stale_ref_scan.py",
|
|
227
228
|
"scripts/substrate_jump_detector.sh",
|
|
228
229
|
"scripts/target_freeze.sh",
|
|
229
230
|
"scripts/test_action_yml_lanes.sh",
|
|
@@ -319,6 +320,7 @@
|
|
|
319
320
|
"scripts/test_sim_isolated_run_lanes.sh",
|
|
320
321
|
"scripts/test_skill_canon_preload_lanes.sh",
|
|
321
322
|
"scripts/test_stale_clone_guard_lanes.sh",
|
|
323
|
+
"scripts/test_stale_ref_scan_lanes.sh",
|
|
322
324
|
"scripts/test_tag_version_lanes.sh",
|
|
323
325
|
"scripts/test_target_freeze_lanes.sh",
|
|
324
326
|
"scripts/test_temper_check_lanes.sh",
|
package/scripts/selfcheck.sh
CHANGED
|
@@ -1640,6 +1640,24 @@ else
|
|
|
1640
1640
|
fail=1
|
|
1641
1641
|
fi
|
|
1642
1642
|
|
|
1643
|
+
# Stale-reference lanes — «this value is alive and resolves, but the world it points at moved».
|
|
1644
|
+
# Added 2026-09-20 after CITATION.cff and four paper versions were found citing the SUPERSEDED v1.0
|
|
1645
|
+
# record of this very work: every «does this DOI resolve» check passed, because the DOI does resolve.
|
|
1646
|
+
# 🟥 The suite exists because `new-code-anchor` caught the scanner shipping with no lane that RUNS
|
|
1647
|
+
# it — the author's own commit said «배선 안 함» and the gate turned that sentence red. A tool's own
|
|
1648
|
+
# `--self-check` is not an anchor until a runner surface executes it. Same pairing rule as above:
|
|
1649
|
+
# the lane exists only because the scanner does, so its absence beside a present subject is a FAIL.
|
|
1650
|
+
if [ ! -f scripts/stale_ref_scan.py ]; then
|
|
1651
|
+
_absent_subject_verdict "test_stale_ref_scan_lanes.sh" "scripts/stale_ref_scan.py" || fail=1
|
|
1652
|
+
elif [ -f scripts/test_stale_ref_scan_lanes.sh ]; then
|
|
1653
|
+
if ! bash scripts/test_stale_ref_scan_lanes.sh; then
|
|
1654
|
+
fail=1
|
|
1655
|
+
fi
|
|
1656
|
+
else
|
|
1657
|
+
echo "FAIL test_stale_ref_scan_lanes.sh: stale_ref_scan.py present but its anchor is missing"
|
|
1658
|
+
fail=1
|
|
1659
|
+
fi
|
|
1660
|
+
|
|
1643
1661
|
# Paper-integrity lanes — the three checks the governor ran BY HAND with ad-hoc python on 2026-09-17
|
|
1644
1662
|
# (paper 2; the sister paper had just been rejected by arXiv for 11/17 reference mismatches): every
|
|
1645
1663
|
# cited key defined and every defined key cited (+ NEAR-MISS pairing for [MF24]↔[MF22]-style
|
|
@@ -0,0 +1,510 @@
|
|
|
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 의 실물 형태
|
|
332
|
+
url = ['> **FH papers**: v1.0.1 methodology · [Zenodo](https://zenodo.org/records/22542168)']
|
|
333
|
+
got = [r for _, r, _, _ in scan_body("x.md", url)]
|
|
334
|
+
lane("extract: zenodo.org/records/<id> URL", got == ["22542168"], str(got))
|
|
335
|
+
|
|
336
|
+
# ⓒ 🟥 known-NEGATIVE — 추출기가 «아무 숫자나» 집지 않는다
|
|
337
|
+
noise = ['version 20397566 of the spec', 'see zenodo for details', 'id=20397566']
|
|
338
|
+
got = [r for _, r, _, _ in scan_body("x.md", noise)]
|
|
339
|
+
lane("extract NEG: bare digits are NOT a citation", got == [], str(got))
|
|
340
|
+
|
|
341
|
+
# ⓓ changelog 제외 — 헤딩 «텍스트 안» 어디든. plugins/fh-meta/CHANGELOG.md:1 의 실물 형태
|
|
342
|
+
cl = ['# forge-harness (fh-meta) Changelog', 'see 10.5281/zenodo.20397566 for what was wrong']
|
|
343
|
+
got = [(r, inc) for _, r, _, inc in scan_body("x.md", cl)]
|
|
344
|
+
lane("exclude: '# <name> Changelog' heading is recognised", got == [("20397566", True)], str(got))
|
|
345
|
+
|
|
346
|
+
# ⓔ 🟥 known-NEGATIVE — 본문 산문의 «changelog» 낱말은 컷오프가 아니다
|
|
347
|
+
prose = ['We keep a changelog for this reason.', 'cite 10.5281/zenodo.20397566 here']
|
|
348
|
+
got = [(r, inc) for _, r, _, inc in scan_body("x.md", prose)]
|
|
349
|
+
lane("exclude NEG: prose mention does NOT cut off", got == [("20397566", False)], str(got))
|
|
350
|
+
|
|
351
|
+
# ⓕ pin 마커 — 발행된 스냅샷은 통째로 기록으로 취급
|
|
352
|
+
pin = ['<!-- stale-ref: pinned — published snapshot, editing it destroys the record -->',
|
|
353
|
+
'cite 10.5281/zenodo.20397566']
|
|
354
|
+
got = [(r, inc) for _, r, _, inc in scan_body("x.html", pin)]
|
|
355
|
+
lane("exclude: 'stale-ref: pinned' marks the whole file a record", got == [("20397566", True)], str(got))
|
|
356
|
+
|
|
357
|
+
# ⓖ 🟥 못 읽은 입력 — 이 파일 자신을 바이너리로 만들어 본다(임시 파일)
|
|
358
|
+
import tempfile
|
|
359
|
+
with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as tf:
|
|
360
|
+
tf.write(b"%PDF-1.4\x00\x00binary garbage")
|
|
361
|
+
binpath = tf.name
|
|
362
|
+
lines, err = load(binpath)
|
|
363
|
+
os.unlink(binpath)
|
|
364
|
+
lane("load: binary input is UNSCANNABLE, not empty", lines is None and "binary" in (err or ""), str(err))
|
|
365
|
+
|
|
366
|
+
# ⓗ known-NEGATIVE 짝 — 평범한 텍스트는 읽힌다(계기가 «전부 거부» 가 아님)
|
|
367
|
+
lines2, err2 = load(__file__)
|
|
368
|
+
lane("load NEG: this very file reads fine", lines2 is not None and err2 is None, str(err2))
|
|
369
|
+
|
|
370
|
+
# ⓘ 🟥 rc 계산 — 이 레인이 없으면 `rc = 0` 한 줄 뮤턴트가 전 레인을 통과한다(실측 확인)
|
|
371
|
+
lane("rc: clean → 0", compute_rc([], [], []) == 0)
|
|
372
|
+
lane("rc: superseded → 1", compute_rc(["20397566"], [], []) == 1)
|
|
373
|
+
lane("rc: unresolved dominates → 10", compute_rc(["20397566"], ["999"], []) == 10)
|
|
374
|
+
lane("rc: unscannable dominates → 10", compute_rc(["20397566"], [], [("x.pdf", "binary")]) == 10)
|
|
375
|
+
# 🟥 known-NEGATIVE — «항상 10» 을 내는 구현을 막는다
|
|
376
|
+
lane("rc NEG: not always 10", compute_rc([], [], []) != 10)
|
|
377
|
+
|
|
378
|
+
print("SELF-CHECK: %s" % ("PASS" if ok else "FAIL"))
|
|
379
|
+
return 0 if ok else 10
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# ---------------------------------------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def main():
|
|
386
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
387
|
+
ap.add_argument("--body", nargs="+", metavar="FILE", help="file(s) to scan for Zenodo references")
|
|
388
|
+
ap.add_argument("--offline-fixture", metavar="JSON",
|
|
389
|
+
help="use this fixture file instead of live Zenodo calls (see module docstring)")
|
|
390
|
+
ap.add_argument("--timeout", type=float, default=15, help="per-request timeout, seconds (live mode only)")
|
|
391
|
+
ap.add_argument("--max-sites", type=int, default=6, help="usage sites printed per flagged id (0 = all)")
|
|
392
|
+
ap.add_argument("--json", action="store_true")
|
|
393
|
+
ap.add_argument("--self-check", action="store_true", help="run the built-in offline known-pair and exit")
|
|
394
|
+
args = ap.parse_args()
|
|
395
|
+
|
|
396
|
+
if args.self_check:
|
|
397
|
+
return run_self_check()
|
|
398
|
+
|
|
399
|
+
if not args.body:
|
|
400
|
+
print("🟥 --body is required unless --self-check is given", file=sys.stderr)
|
|
401
|
+
return 10
|
|
402
|
+
|
|
403
|
+
# 🟥 못 읽은 파일에서 **즉시 나가지 않는다** — 나머지를 안 재면 그것도 미측정이다.
|
|
404
|
+
# 이름으로 모아 두고 rc 로 지배하게 한다(아래 `rc` 계산).
|
|
405
|
+
files, unscannable = {}, []
|
|
406
|
+
for p in args.body:
|
|
407
|
+
lines, err = load(p)
|
|
408
|
+
if lines is None:
|
|
409
|
+
unscannable.append((p, err))
|
|
410
|
+
continue
|
|
411
|
+
files[p] = lines
|
|
412
|
+
|
|
413
|
+
if args.offline_fixture:
|
|
414
|
+
try:
|
|
415
|
+
with open(args.offline_fixture, encoding="utf-8") as fh:
|
|
416
|
+
fixture = json.load(fh)
|
|
417
|
+
except (OSError, json.JSONDecodeError) as e:
|
|
418
|
+
print("🟥 cannot read --offline-fixture %s: %s — rc=10" % (args.offline_fixture, e), file=sys.stderr)
|
|
419
|
+
return 10
|
|
420
|
+
raw_fetch = make_offline_fetch(fixture)
|
|
421
|
+
else:
|
|
422
|
+
raw_fetch = fetch_live
|
|
423
|
+
cached_fetch = make_cached(raw_fetch)
|
|
424
|
+
|
|
425
|
+
# candidate[id] = list of (file, line, snippet); changelog[id] = same, kept separate & uncounted
|
|
426
|
+
candidates, changelog = {}, {}
|
|
427
|
+
for p in files:
|
|
428
|
+
for line_no, rid, snippet, in_changelog in scan_body(p, files[p]):
|
|
429
|
+
bucket = changelog if in_changelog else candidates
|
|
430
|
+
bucket.setdefault(rid, []).append((p, line_no, snippet))
|
|
431
|
+
|
|
432
|
+
n_sites = sum(len(v) for v in candidates.values())
|
|
433
|
+
n_changelog_sites = sum(len(v) for v in changelog.values())
|
|
434
|
+
if not args.json:
|
|
435
|
+
print("stale-ref-scan · body=%d file%s · %d Zenodo reference site(s) across %d distinct id(s) "
|
|
436
|
+
"(+%d site(s) / %d id(s) excluded as changelog context)%s · review surface, not a gate"
|
|
437
|
+
% (len(args.body), "" if len(args.body) == 1 else "s", n_sites, len(candidates),
|
|
438
|
+
n_changelog_sites, len(changelog),
|
|
439
|
+
"" if not unscannable else " · 🟥 %d UNSCANNABLE" % len(unscannable)))
|
|
440
|
+
|
|
441
|
+
verdicts = {rid: resolve(rid, cached_fetch, args.timeout) for rid in candidates}
|
|
442
|
+
|
|
443
|
+
superseded = sorted(rid for rid, v in verdicts.items() if v["status"] == "SUPERSEDED")
|
|
444
|
+
unresolved = sorted(rid for rid, v in verdicts.items() if v["status"] == "UNRESOLVED")
|
|
445
|
+
concept = sorted(rid for rid, v in verdicts.items() if v["status"] == "CONCEPT")
|
|
446
|
+
current = sorted(rid for rid, v in verdicts.items() if v["status"] == "CURRENT")
|
|
447
|
+
|
|
448
|
+
def where(sites):
|
|
449
|
+
shown = sites if args.max_sites == 0 else sites[:args.max_sites]
|
|
450
|
+
more = "" if len(shown) == len(sites) else " (+%d more)" % (len(sites) - len(shown))
|
|
451
|
+
return " · ".join("%s:%d" % (os.path.basename(f), n) for f, n, _ in shown) + more
|
|
452
|
+
|
|
453
|
+
# 🟥 **계기 실패와 문서 결함을 같은 rc 로 접지 않는다.**
|
|
454
|
+
# 초판은 둘 다 rc=1 이었다. 그러면 Zenodo 429 한 번에 전 파일이 «문서 결함» 으로 뜨고,
|
|
455
|
+
# 그걸 배선하면 «rc=1 은 보통 네트워크» 를 학습한 리뷰어가 **진짜 SUPERSEDED 를 무시**한다.
|
|
456
|
+
# 이 레포 정본이 그 자리를 이름 붙였다 — 계기 오류는 «별도 비-PASS»(fh-gate.sh 의 exit-10).
|
|
457
|
+
# 🟥 **10 이 1 을 지배한다** — 못 잰 것이 있으면 «발견 목록» 을 신뢰할 수 없다.
|
|
458
|
+
# (`gate_shape_scan.sh` 의 «exit 3 이 히트를 지배» 와 같은 형태.) 적대검증 A-7.
|
|
459
|
+
rc = compute_rc(superseded, unresolved, unscannable)
|
|
460
|
+
|
|
461
|
+
if args.json:
|
|
462
|
+
print(json.dumps({
|
|
463
|
+
"body": args.body,
|
|
464
|
+
"sites": n_sites, "changelog_sites": n_changelog_sites,
|
|
465
|
+
"superseded": superseded, "unresolved": unresolved, "concept": concept, "current": current,
|
|
466
|
+
"unscannable": [{"file": f, "reason": e} for f, e in unscannable],
|
|
467
|
+
# 🟥 기계 소비자에게 «어디인지» 를 준다 — 초판은 id 만 주고 file:line 이 0 이었다(B-1)
|
|
468
|
+
"sites_by_id": {rid: [[f, n, sn] for f, n, sn in v] for rid, v in candidates.items()},
|
|
469
|
+
"verdicts": verdicts,
|
|
470
|
+
"summary": {"superseded": len(superseded), "unresolved": len(unresolved),
|
|
471
|
+
"concept": len(concept), "current": len(current),
|
|
472
|
+
"changelog_excluded": len(changelog),
|
|
473
|
+
"unscannable": len(unscannable), "rc": rc},
|
|
474
|
+
}, ensure_ascii=False, indent=1, default=str))
|
|
475
|
+
return rc
|
|
476
|
+
|
|
477
|
+
for rid in superseded:
|
|
478
|
+
v = verdicts[rid]
|
|
479
|
+
print(" 🟥 SUPERSEDED [%s] cited ×%d — %s" % (rid, len(candidates[rid]), where(candidates[rid])))
|
|
480
|
+
print(" family %s — current version is [%s] (%s), this citation points at an old one"
|
|
481
|
+
% (v.get("concept"), v.get("latest_id"), v.get("latest_doi")))
|
|
482
|
+
for rid in unresolved:
|
|
483
|
+
v = verdicts[rid]
|
|
484
|
+
print(" 🟥 UNRESOLVED [%s] cited ×%d — %s — %s" % (rid, len(candidates[rid]), where(candidates[rid]), v.get("detail")))
|
|
485
|
+
for rid in concept:
|
|
486
|
+
print(" ⬜ CONCEPT [%s] cited ×%d — %s — always resolves to current, not stale by construction"
|
|
487
|
+
% (rid, len(candidates[rid]), where(candidates[rid])))
|
|
488
|
+
for rid in current:
|
|
489
|
+
print(" ⬜ CURRENT [%s] cited ×%d — %s — this version IS the latest in its family"
|
|
490
|
+
% (rid, len(candidates[rid]), where(candidates[rid])))
|
|
491
|
+
for f, err in unscannable:
|
|
492
|
+
print(" 🟥 UNSCANNABLE [%s] — %s — NOT scanned. «읽지 못한 것» 은 «깨끗함» 이 아니다"
|
|
493
|
+
% (os.path.basename(f), err))
|
|
494
|
+
for rid in sorted(changelog):
|
|
495
|
+
print(" ⬜ CHANGELOG-EXCLUDED [%s] ×%d — %s — after a Changelog heading, not counted as a live citation"
|
|
496
|
+
% (rid, len(changelog[rid]), where(changelog[rid])))
|
|
497
|
+
|
|
498
|
+
print("stale-ref verdict: SUPERSEDED=%d UNRESOLVED=%d UNSCANNABLE=%d CONCEPT=%d CURRENT=%d "
|
|
499
|
+
"CHANGELOG-EXCLUDED=%d rc=%d"
|
|
500
|
+
% (len(superseded), len(unresolved), len(unscannable), len(concept), len(current),
|
|
501
|
+
len(changelog), rc))
|
|
502
|
+
if superseded or unresolved:
|
|
503
|
+
print("ⓘ review surface — a stale citation may be intentional (pinning a past claim); confirm by eye "
|
|
504
|
+
"before editing. §Pre-Publish Surface Gate's Step 1b (draft API / md5 / machine fields) is the "
|
|
505
|
+
"deposit-time counterpart of this check.")
|
|
506
|
+
return rc
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
if __name__ == "__main__":
|
|
510
|
+
sys.exit(main())
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# test_stale_ref_scan_lanes.sh — known pairs + revert probes for scripts/stale_ref_scan.py
|
|
3
|
+
#
|
|
4
|
+
# WHY THIS SUITE EXISTS AT ALL
|
|
5
|
+
# `new-code-anchor` caught the author's own admission: the scanner shipped with no lane that
|
|
6
|
+
# RUNS it. The commit message said «배선 안 함» and the gate turned that sentence into a red
|
|
7
|
+
# check. 🟥 A `--self-check` inside the tool is not an anchor — nothing on a runner surface
|
|
8
|
+
# executes it, so «a green suite total» would mean «nothing touched this file».
|
|
9
|
+
#
|
|
10
|
+
# WHY LANES ON FIXTURES, NOT ON THE REPO'S OWN PAPERS
|
|
11
|
+
# The three demonstrations the author ran (v1.0.3 · v1.0.4 · CITATION.cff) need the LIVE Zenodo
|
|
12
|
+
# API and drift with every future deposit. Both are disqualifying for a consumer install. So the
|
|
13
|
+
# network arms here go through `--offline-fixture`, and the shapes are copied byte-for-byte from
|
|
14
|
+
# the real corpus (fixture shape from the artifact, not a mental model):
|
|
15
|
+
# · `10.5281/<wbr>zenodo.<wbr>20397566` paper/forge_harness_v1.0.3.html:159
|
|
16
|
+
# · `[Zenodo](https://zenodo.org/records/22542168)` README.md:418
|
|
17
|
+
# · `# forge-harness (fh-meta) Changelog` plugins/fh-meta/CHANGELOG.md:1
|
|
18
|
+
#
|
|
19
|
+
# THE TWO-SIGNALS RULE
|
|
20
|
+
# A 0 is evidence only if the instrument SAW something. L3 asserts the id was extracted AND
|
|
21
|
+
# classified as changelog; L6 asserts a binary body is named UNSCANNABLE rather than silently
|
|
22
|
+
# producing «0 sites», which is exactly the defect the adversarial round measured (S-1).
|
|
23
|
+
#
|
|
24
|
+
# REVERT PROBES (a mechanism is load-bearing only if removing it turns a known pair red)
|
|
25
|
+
# L8 scan_body · L9 rc dominance · L10 binary detection. Each mutates a COPY by source edit,
|
|
26
|
+
# asserts the copy's --self-check goes red, and byte-compares the original before and after.
|
|
27
|
+
# 🟥 Before the 2026-09-20 hardening, mutating scan_body left --self-check at 4/4 PASS.
|
|
28
|
+
#
|
|
29
|
+
# 🟥 PITFALL (this repo's lanes): `out="$(cmd)"` runs in a SUBSHELL, so `rc=$?` after it is the
|
|
30
|
+
# assignment's status. Every lane below redirects to a file and reads `$?` directly.
|
|
31
|
+
set -u
|
|
32
|
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
33
|
+
cd "$ROOT" || { printf '🟥 HARNESS ERROR — 레포 루트로 못 갔다\n'; exit 10; }
|
|
34
|
+
SCAN="scripts/stale_ref_scan.py"
|
|
35
|
+
# 🟥 인터프리터도 «리터럴» 이어야 한다 — new_code_anchor_check 의 인보커 정규식이
|
|
36
|
+
# (bash|sh|zsh|python3?|source|.) 리터럴을 요구한다. 변수로 부르면 MENTION_ONLY 로 막힌다(실측 2회).
|
|
37
|
+
# 🟥 **리터럴 경로로 부른다.** 변수 경유 호출은 `new_code_anchor_check.sh` 가 «실행» 으로
|
|
38
|
+
# 못 읽어서 MENTION_ONLY 로 막았다(실측) — 그 게이트가 잡는 것이 바로 «이름만 부르는 레인» 이다.
|
|
39
|
+
PASS=0; FAIL=0
|
|
40
|
+
ok () { printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
|
|
41
|
+
ng () { printf ' ❌ %s\n' "$1"; FAIL=$((FAIL+1)); }
|
|
42
|
+
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
|
|
43
|
+
|
|
44
|
+
if [ ! -f scripts/stale_ref_scan.py ]; then
|
|
45
|
+
printf '🟥 HARNESS ERROR — scripts/stale_ref_scan.py 가 없다. 「0 실패」가 아니라 계기 부재다.\n'; exit 10
|
|
46
|
+
fi
|
|
47
|
+
|
|
48
|
+
# 오프라인 픽스처 — 실물 id 관계를 그대로 옮긴다(라이브 API 직독 2026-09-20)
|
|
49
|
+
cat > "$TMP/fx.json" <<'JSON'
|
|
50
|
+
{ "20397566": {"id": 20397566, "conceptrecid": "20397565"},
|
|
51
|
+
"22843702": {"id": 22843702, "conceptrecid": "20397565"},
|
|
52
|
+
"20397565": {"id": 22843702, "conceptrecid": "20397565"},
|
|
53
|
+
"22542168": {"id": 22542168, "conceptrecid": "20397565"} }
|
|
54
|
+
JSON
|
|
55
|
+
run () { python3 scripts/stale_ref_scan.py --offline-fixture "$TMP/fx.json" --body "$@" > "$TMP/out" 2>&1; echo $?; }
|
|
56
|
+
|
|
57
|
+
# ── L1 자기검사가 실제로 돈다 ─────────────────────────────────────────────────
|
|
58
|
+
python3 scripts/stale_ref_scan.py --self-check > "$TMP/sc" 2>&1; rc=$?
|
|
59
|
+
n_pass=$(/usr/bin/grep -c '^ PASS' "$TMP/sc" || true)
|
|
60
|
+
if [ "$rc" = "0" ] && [ "$n_pass" -ge 17 ]; then ok "L1 --self-check rc=0 · PASS 레인 $n_pass (>=17)"
|
|
61
|
+
else ng "L1 --self-check rc=$rc · PASS $n_pass"; fi
|
|
62
|
+
|
|
63
|
+
# ── L2 known-POSITIVE: <wbr> 분할 DOI 가 SUPERSEDED 로 잡힌다 ─────────────────
|
|
64
|
+
printf '<tr><td>forge-harness</td><td>10.5281/<wbr>zenodo.<wbr>20397566</td></tr>\n' > "$TMP/a.html"
|
|
65
|
+
rc=$(run "$TMP/a.html")
|
|
66
|
+
if [ "$rc" = "1" ] && /usr/bin/grep -q 'SUPERSEDED=1' "$TMP/out"; then ok "L2 <wbr> 분할 DOI → SUPERSEDED rc=1"
|
|
67
|
+
else ng "L2 rc=$rc · $(/usr/bin/grep -o 'SUPERSEDED=[0-9]*' "$TMP/out" | head -1)"; fi
|
|
68
|
+
|
|
69
|
+
# ── L3 changelog 제외 — 🟥 «봤는데 제외했다» 를 같이 단언한다 ─────────────────
|
|
70
|
+
printf '# forge-harness (fh-meta) Changelog\nsee 10.5281/zenodo.20397566 for what was wrong\n' > "$TMP/b.md"
|
|
71
|
+
rc=$(run "$TMP/b.md")
|
|
72
|
+
if [ "$rc" = "0" ] && /usr/bin/grep -q 'CHANGELOG-EXCLUDED=1' "$TMP/out" \
|
|
73
|
+
&& /usr/bin/grep -q 'SUPERSEDED=0' "$TMP/out"; then
|
|
74
|
+
ok "L3 '# <이름> Changelog' → 제외 1건 · SUPERSEDED 0 (봤고 제외했다)"
|
|
75
|
+
else ng "L3 rc=$rc · $(/usr/bin/grep -o 'CHANGELOG-EXCLUDED=[0-9]*' "$TMP/out" | head -1)"; fi
|
|
76
|
+
|
|
77
|
+
# ── L4 known-NEGATIVE: 본문 산문의 «changelog» 는 컷오프가 아니다 ────────────
|
|
78
|
+
printf 'We keep a changelog for this reason.\ncite 10.5281/zenodo.20397566 here\n' > "$TMP/c.md"
|
|
79
|
+
rc=$(run "$TMP/c.md")
|
|
80
|
+
if [ "$rc" = "1" ] && /usr/bin/grep -q 'SUPERSEDED=1' "$TMP/out"; then
|
|
81
|
+
ok "L4 NEG 산문의 changelog 는 컷오프가 아니다 — 인용이 살아 있다"
|
|
82
|
+
else ng "L4 rc=$rc — 산문 낱말이 진짜 인용을 삼켰다"; fi
|
|
83
|
+
|
|
84
|
+
# ── L5 pin 마커 — 발행 스냅샷은 통째로 기록 ───────────────────────────────────
|
|
85
|
+
printf '<!-- stale-ref: pinned — published snapshot -->\n10.5281/zenodo.20397566\n' > "$TMP/d.html"
|
|
86
|
+
rc=$(run "$TMP/d.html")
|
|
87
|
+
if [ "$rc" = "0" ] && /usr/bin/grep -q 'CHANGELOG-EXCLUDED=1' "$TMP/out"; then ok "L5 pin 마커 → rc=0"
|
|
88
|
+
else ng "L5 rc=$rc — pin 이 안 먹는다"; fi
|
|
89
|
+
|
|
90
|
+
# ── L6 🟥 못 읽은 입력은 UNSCANNABLE + rc=10 (적대검증 S-1) ───────────────────
|
|
91
|
+
printf '%%PDF-1.4\000\000binary\n' > "$TMP/e.pdf"
|
|
92
|
+
rc=$(run "$TMP/e.pdf")
|
|
93
|
+
if [ "$rc" = "10" ] && /usr/bin/grep -q 'UNSCANNABLE=1' "$TMP/out"; then
|
|
94
|
+
ok "L6 바이너리 → UNSCANNABLE rc=10 (0 sites rc=0 아님)"
|
|
95
|
+
else ng "L6 rc=$rc — 못 읽은 것이 «깨끗함» 으로 나간다"; fi
|
|
96
|
+
|
|
97
|
+
# ── L7 컨셉 DOI 는 CONCEPT · 최신 버전은 CURRENT ──────────────────────────────
|
|
98
|
+
printf '10.5281/zenodo.20397565 and 10.5281/zenodo.22843702\n' > "$TMP/f.md"
|
|
99
|
+
rc=$(run "$TMP/f.md")
|
|
100
|
+
if [ "$rc" = "0" ] && /usr/bin/grep -q 'CONCEPT=1' "$TMP/out" && /usr/bin/grep -q 'CURRENT=1' "$TMP/out"; then
|
|
101
|
+
ok "L7 컨셉→CONCEPT · 최신→CURRENT rc=0"
|
|
102
|
+
else ng "L7 rc=$rc · $(/usr/bin/grep -o 'CONCEPT=[0-9]* CURRENT=[0-9]*' "$TMP/out" | head -1)"; fi
|
|
103
|
+
|
|
104
|
+
# ── 되돌림 프로브 ─────────────────────────────────────────────────────────────
|
|
105
|
+
probe () { # $1=이름 $2=원문 $3=치환문
|
|
106
|
+
cp scripts/stale_ref_scan.py "$TMP/mut.py"
|
|
107
|
+
python3 - "$TMP/mut.py" "$2" "$3" <<'PYX'
|
|
108
|
+
import io,sys
|
|
109
|
+
p,a,b=sys.argv[1],sys.argv[2],sys.argv[3]
|
|
110
|
+
s=io.open(p,encoding="utf-8").read()
|
|
111
|
+
if s.count(a)!=1: sys.exit(3)
|
|
112
|
+
io.open(p,"w",encoding="utf-8").write(s.replace(a,b,1))
|
|
113
|
+
PYX
|
|
114
|
+
if [ $? -ne 0 ]; then ng "$1 — 뮤턴트 생성 실패(치환 대상 부재). HARNESS ERROR, 초록으로 안 읽는다"; return; fi
|
|
115
|
+
python3 "$TMP/mut.py" --self-check > "$TMP/mo" 2>&1; mrc=$?
|
|
116
|
+
if [ "$mrc" != "0" ] && /usr/bin/grep -q '^ FAIL' "$TMP/mo"; then ok "$1 — 뮤턴트가 빨개진다"
|
|
117
|
+
else ng "$1 — 뮤턴트인데 self-check 가 초록이다(앵커가 장식)"; fi
|
|
118
|
+
}
|
|
119
|
+
probe "L8 scan_body 죽이기" " return sites" " return []"
|
|
120
|
+
probe "L9 rc 지배 제거" " if unresolved or unscannable:" " if False:"
|
|
121
|
+
probe "L10 바이너리 검사 제거" ' if b"\x00" in raw:' " if False:"
|
|
122
|
+
|
|
123
|
+
# 원본 불변 확인 — 프로브가 대상을 건드리지 않았나
|
|
124
|
+
python3 scripts/stale_ref_scan.py --self-check > "$TMP/sc2" 2>&1
|
|
125
|
+
if [ $? -eq 0 ]; then ok "L11 프로브 후에도 원본 --self-check rc=0 (사본만 건드렸다)"
|
|
126
|
+
else ng "L11 원본이 오염됐다"; fi
|
|
127
|
+
|
|
128
|
+
printf '\n PASS %d FAIL %d\n' "$PASS" "$FAIL"
|
|
129
|
+
[ "$FAIL" -eq 0 ] || exit 1
|