Skip to content

知らない分野を、原文にたどりつくまで芋づる式に掘る Claude Code のスキル

Python

chain.py の著者の候補・同じ問い合わせの2回目・向きの制御文字・Anubis のページ

MaryCache980ec7f50f0b
diff --git a/skills/imozuru/SKILL.md b/skills/imozuru/SKILL.md
index d0002d0..0d0ebe9 100644
--- a/skills/imozuru/SKILL.md
+++ b/skills/imozuru/SKILL.md
@@ -229,7 +229,7 @@ map.md を下の書式で作り、**問い**と、答えるのに要る**主張*
- 動画の場所は行番号の代わりに時刻で指す(`sources/x.md [12:34]`)
- `scripts/report.py <topic_dir> [--check]` — extracts.json の抜き書きを原文と照合し、合えば report.html にする。`--check` は照合だけ
- `scripts/watch.py add|list|check` — 見張り。RSS / Atom を引いて前回からの新着を出す。検索を使わないので費用はかからず結果も揺れない。DOCTYPE・ENTITY を含むフィードは安全のため読まない。フィードの場所にタブや改行が入っていたら足さない
-- `scripts/chain.py find|refs|cites|author` — OpenAlex で引用と著者をたどる。1日 1,000 回まで無料の枠で、プリペイド残高が 0 なら超えても止まるだけ。**API キーや支払いの登録はしない**。古めの論文に強く、新しい論文と同名の多い著者に弱い(author は同名の別人の論文を返すことがある)
+- `scripts/chain.py find|refs|cites|author` — OpenAlex で引用と著者をたどる。1日 1,000 回まで無料の枠で、プリペイド残高が 0 なら超えても止まるだけ。**API キーや支払いの登録はしない**。古めの論文に強く、新しい論文と同名の多い著者に弱い(author は名前の検索の1位を使うので、同名の別人の論文を返すことがある。出力の「# 別の候補」に別人の ID が並ぶので、所属と論文数で確かめ、違えば `chain.py author A…` で引き直す)
- ファイル名は `<著者>-<年>-<短い題>`、arXiv は `arxiv-<番号>-<短い題>`
## 境界
diff --git a/skills/imozuru/scripts/chain.py b/skills/imozuru/scripts/chain.py
index 3b1d09a..1c663d1 100755
--- a/skills/imozuru/scripts/chain.py
+++ b/skills/imozuru/scripts/chain.py
@@ -11,7 +11,8 @@ OpenAlex は1日 1,000 回まで無料の枠(x-ratelimit-limit-usd 0.1)。
chain.py find <DOI か題名> … 論文を特定して ID を出す(題名なら候補5件)
chain.py refs <ID か DOI> [-n 20] … 後ろへ: その論文が引いている文献
chain.py cites <ID か DOI> [-n 20] … 前へ: その論文を引いている文献(被引用の多い順)
- chain.py author <著者名> [-n 20] … 著者で追う: その人の論文(被引用の多い順)
+ chain.py author <著者名か著者ID> [-n 20] … 著者で追う: その人の論文(被引用の多い順)
+ 名前なら「# 別の候補」の行に同名の別人の ID も出す
出力: 1行1本、タブ区切り(年 被引用数 ID 題名 DOI 無料PDF)
"""
@@ -24,6 +25,7 @@ import urllib.request
API = "https://api.openalex.org"
# OpenAlex の work ID(W と数字だけ)。「Weak …」のような題名と取り違えないよう、形で見分ける
WORK_ID = re.compile(r"W\d+")
+AUTHOR_ID = re.compile(r"A\d+")
FIELDS = "id,display_name,publication_year,cited_by_count,doi,best_oa_location"
# API の応答の大きさの上限。200本の一覧でも数百 KB に収まる。
MAX_BYTES = 20_000_000
@@ -65,8 +67,16 @@ def clean(s: object) -> str:
題名や著者名は論文の著者や登録者が書く。タブや改行が残ると列や行が増え、エージェントが表を読み違える。
端末を操る ESC の並びも、ここで消す。
+ 文字の向きを変える制御文字(U+202E など)と幅の無い空白も消す。題名の一部を逆向きに見せたり、
+ 見た目が同じで中身の違う文字列を作ったりできる。ZWJ・ZWNJ は絵文字や一部の文字で要るので残す。
"""
- return re.sub(r"[\s\x00-\x1f\x7f-\x9f

]+", " ", str(s)).strip()
+ return re.sub(r"[\s\x00-\x1f\x7f-\x9f

\u200b\u200e\u200f\u202a-\u202e\u2060-\u2069\ufeff]+", " ", str(s)).strip()
+
+
+def author_line(a: dict, aid: str) -> str:
+ """著者1人を「名前 ID 所属 論文数」の1行にする。"""
+ inst = ", ".join(clean(i.get("display_name") or "") for i in a.get("last_known_institutions") or [])
+ return f"{clean(a.get('display_name') or '')} {aid} {inst} 論文{clean(a.get('works_count'))}本"
def search_title(key: str) -> list[dict]:
@@ -80,7 +90,10 @@ def search_title(key: str) -> list[dict]:
だけ)。全部の語では0件になるので、0件なら前半の3語で引き直す。
"""
words = key.replace(",", " ").replace(":", " ").split()
- for terms in (words, words[:3]):
+ if not words: # 空の条件で問い合わせると、題名を絞らない検索になる
+ return []
+ # 3語以下なら前半の3語は全部と同じ。同じ問い合わせを2回送って枠を使わない
+ for terms in (words, words[:3]) if len(words) > 3 else (words,):
hits = get("/works", filter="title.search:" + " ".join(terms),
sort="cited_by_count:desc", **{"per-page": 5}, select=FIELDS)["results"]
if hits:
@@ -98,16 +111,16 @@ def resolve(key: str) -> dict:
if WORK_ID.fullmatch(key) or "openalex.org/" in key:
wid = key.rstrip("/").rsplit("/", 1)[-1]
if not WORK_ID.fullmatch(wid):
- raise SystemExit(f"OpenAlex の ID の形ではない: {key}")
+ raise SystemExit(f"OpenAlex の ID の形ではない: {clean(key)}")
return get(f"/works/{wid}", select=FIELDS)
if key.startswith("10.") or "doi.org/" in key:
doi = urllib.parse.unquote(key.split("doi.org/")[-1]) if "doi.org/" in key else key
if any(part in {".", ".."} for part in doi.split("/")):
- raise SystemExit(f"DOI に「.」か「..」の区切りがある: {key}")
+ raise SystemExit(f"DOI に「.」か「..」の区切りがある: {clean(key)}")
return get(f"/works/doi:{urllib.parse.quote(doi, safe='/')}", select=FIELDS)
hits = search_title(key)
if not hits:
- raise SystemExit(f"見つからない: {key}")
+ raise SystemExit(f"見つからない: {clean(key)}")
return hits[0]
@@ -141,7 +154,7 @@ def main() -> int:
# 題名のときは候補を全部見せる。どれが本体かを読み手が確かめられるように。
hits = [resolve(key)] if WORK_ID.fullmatch(key) or key.startswith("10.") or "/" in key else search_title(key)
if not hits:
- print(f"候補なし: {key}(DOI で引き直すか、題名の語を減らす)")
+ print(f"候補なし: {clean(key)}(DOI で引き直すか、題名の語を減らす)")
for w in hits:
print(row(w))
elif cmd in ("refs", "cites"):
@@ -156,15 +169,21 @@ def main() -> int:
for w in res["results"]:
print(row(w))
elif cmd == "author":
- hits = get("/authors", search=key, **{"per-page": 1})["results"]
+ # 著者 ID(A と数字)ならその人を直接引く。名前なら検索の1位を使い、ほかの候補も並べる。
+ # 名前だけでは同姓同名を見分けられないので、別人だったら候補の ID で引き直せるようにする
+ if AUTHOR_ID.fullmatch(key):
+ hits = [get(f"/authors/{key}")]
+ else:
+ hits = get("/authors", search=key, **{"per-page": 5})["results"]
if not hits:
- raise SystemExit(f"著者が見つからない: {key}")
- a = hits[0]
- aid = (a.get("id") or "").rsplit("/", 1)[-1]
- if not re.fullmatch(r"A\d+", aid):
- raise SystemExit(f"応答の著者 ID の形がおかしい: {clean(aid)}")
- inst = ", ".join(clean(i.get("display_name") or "") for i in a.get("last_known_institutions") or [])
- print(f"# author {clean(a.get('display_name') or '')} {aid} {inst} 論文{clean(a.get('works_count'))}本")
+ raise SystemExit(f"著者が見つからない: {clean(key)}")
+ ids = [(a.get("id") or "").rsplit("/", 1)[-1] for a in hits]
+ if not all(AUTHOR_ID.fullmatch(i) for i in ids):
+ raise SystemExit(f"応答の著者 ID の形がおかしい: {clean(' '.join(ids))}")
+ a, aid = hits[0], ids[0]
+ print(f"# author {author_line(a, aid)}")
+ for other, oid in zip(hits[1:], ids[1:]):
+ print(f"# 別の候補 {author_line(other, oid)}(この人なら chain.py author {oid})")
res = get("/works", filter=f"author.id:{aid}", sort="cited_by_count:desc",
**{"per-page": n}, select=FIELDS)
for w in res["results"]:
diff --git a/skills/imozuru/scripts/fetch.py b/skills/imozuru/scripts/fetch.py
index 124f2ab..966de51 100755
--- a/skills/imozuru/scripts/fetch.py
+++ b/skills/imozuru/scripts/fetch.py
@@ -59,6 +59,9 @@ WALL_PATTERNS = (
"enable javascript",
"are you a robot",
"captcha",
+ # Anubis(ボット除けの計算をさせるページ)。HAL などが使う。中身の無い 1,000 字ほどのページが
+ # HTML の下限を越えて OK になった(2026-10-20)
+ "you're not a bot",
)
@@ -617,8 +620,9 @@ def clean(s: str) -> str:
他人が決めた文字列(本文・転送先の URL・HTTP のエラーの文)は、1行の出力の列や行を増やしたり、
端末を操ったりできる(2026-10-20 の2回目のレビュー)。
+ 文字の向きを変える制御文字(U+202E など)と幅の無い空白も消す。ZWJ・ZWNJ は絵文字や一部の文字で要るので残す。
"""
- return re.sub(r"[\s\x00-\x1f\x7f-\x9f

]+", " ", s).strip()
+ return re.sub(r"[\s\x00-\x1f\x7f-\x9f

\u200b\u200e\u200f\u202a-\u202e\u2060-\u2069\ufeff]+", " ", s).strip()
def first_line(text: str) -> str:
diff --git a/skills/imozuru/scripts/watch.py b/skills/imozuru/scripts/watch.py
index 7f3da97..f037773 100644
--- a/skills/imozuru/scripts/watch.py
+++ b/skills/imozuru/scripts/watch.py
@@ -246,7 +246,7 @@ def md_text(s: str) -> str:
def clean(s: str) -> str:
"""制御文字(端末を操る ESC の並び)と改行の仲間を空白にする。fetch.py の clean と同じ。"""
- return re.sub(r"[\s\x00-\x1f\x7f-\x9f

]+", " ", s).strip()
+ return re.sub(r"[\s\x00-\x1f\x7f-\x9f

\u200b\u200e\u200f\u202a-\u202e\u2060-\u2069\ufeff]+", " ", s).strip()
def md_link(url: str) -> str:
diff --git a/tests/test_security.py b/tests/test_security.py
index 4b0ce3e..0e41f73 100644
--- a/tests/test_security.py
+++ b/tests/test_security.py
@@ -557,5 +557,65 @@ class SecondRoundTests(unittest.TestCase):
self.assertTrue(report.verify(src, {"file": "a.md", "line": 1, "end": None, "text": "first line"})[0])
+class DeepSeekSplitReviewTests(unittest.TestCase):
+ """2026-10-20、DeepSeek に1ファイルずつ読ませたレビューで当たったもの。"""
+
+ def test_bidi_controls_are_removed(self):
+ for module in (fetch, watch, chain):
+ with self.subTest(module=module.__name__):
+ self.assertEqual(module.clean("abc‮def​g"), "abc def g")
+ # 絵文字の並びや一部の文字に要る ZWJ・ZWNJ は残す
+ self.assertEqual(module.clean("a‍b‌c"), "a‍b‌c")
+
+ def test_short_title_is_queried_once(self):
+ with patch.object(chain, "get", return_value={"results": []}) as get:
+ self.assertEqual(chain.search_title("Exploratory search"), [])
+ self.assertEqual(get.call_count, 1)
+
+ def test_empty_title_is_not_queried(self):
+ with patch.object(chain, "get") as get:
+ self.assertEqual(chain.search_title(" : , "), [])
+ get.assert_not_called()
+
+ def test_author_lists_other_candidates_and_accepts_an_id(self):
+ people = [{"id": f"https://openalex.org/A{i}", "display_name": "Same Name", "works_count": i,
+ "last_known_institutions": [{"display_name": f"Inst {i}"}]} for i in (1, 2)]
+ calls = []
+
+ def get(path, **params):
+ calls.append(path)
+ if path == "/authors":
+ return {"results": people}
+ if path == "/authors/A2":
+ return people[1]
+ return {"results": []}
+
+ with patch.object(chain, "get", side_effect=get), \
+ patch.object(sys, "argv", ["chain.py", "author", "Same Name"]), \
+ contextlib.redirect_stdout(io.StringIO()) as out:
+ chain.main()
+ self.assertIn("# 別の候補 Same Name A2 Inst 2", out.getvalue())
+ self.assertIn("chain.py author A2", out.getvalue())
+
+ with patch.object(chain, "get", side_effect=get), \
+ patch.object(sys, "argv", ["chain.py", "author", "A2"]), \
+ contextlib.redirect_stdout(io.StringIO()) as out:
+ chain.main()
+ self.assertIn("# author Same Name A2", out.getvalue())
+ self.assertIn("/authors/A2", calls)
+
+ def test_anubis_page_is_a_wall(self):
+ page = ("# Making sure you're not a bot!\n\nLoading...\n\n"
+ + "You are seeing this because the administrator set up Anubis. " * 20)
+ with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()) as out, \
+ patch.object(fetch, "download", return_value=(b"<html>anubis</html>", "text/html")), \
+ patch.object(fetch, "html_to_md", side_effect=lambda url, o, *a: (o.write_text(page), page)[1]), \
+ patch.object(fetch, "pdf_save", return_value=False), \
+ patch.object(fetch, "resolve", lambda host: {PUBLIC_IP}), \
+ patch.object(sys, "argv", ["fetch.py", tmp, "paper", "https://example.test/x"]):
+ self.assertEqual(fetch.main(), 1)
+ self.assertIn("壁に当たった(you're not a bot)", out.getvalue())
+
+
if __name__ == "__main__":
unittest.main()