知らない分野を、原文にたどりつくまで芋づる式に掘る Claude Code のスキル
Python
照合: 箇条書きにまたがる抜き書きを通す・Windows で原文を LF で保存し、保存先のフォルダを動かさない
MaryCache7e113aa698b6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94ed2cf..0bfbaef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,10 @@ mainにコミットが入るたびに、使っている人へ更新が届きま- PCにIPv6の経路が無いとき、原文の取得(fetch.py)と見張り(watch.py)が、IPv6の宛先ごとに接続の待ち時間(fetch.pyは90秒、watch.pyは60秒)いっぱい待ってからIPv4へ進み、IPv6の宛先が4つあるサイト(raw.githubusercontent.comなど)では1件に最大6分かかっていたのを直しました。IPv6とIPv4を交互に試し、次の宛先があるときは1つを10秒まで待って次へ移ります。つないだあとの読み込みの待ち時間は変えていません。- PCのEdgeなどでアプリとして入れた窓の中に、アプリとして入れる案内(右上のボタンと帯)が出続けていたのを直しました。manifestが無いうちに入れた窓はminimal-uiの表示で開くため、standaloneだけを見ていた判定ではアプリの窓と分かりませんでした。+- 箇条書きの何行かにまたがる抜き書きが、原文のとおりでも照合に落ちていたのを直しました。行をスペースでつないでから箇条書きの印を消していたため、2行目より後の「- 」が残っていました。Markdownの原文(.md)では、印を除いて写した抜き書きも通ります。PDFから起こした.txtでは、行頭の「- 」が負号のことがあるので、これまでどおり印を消さずに照合します。抜き書きのページ(report.py)と詳細レポート(digest.py)の両方の照合が直ります。penpenguinさんの記事で指摘をいただきました。+- Windowsで、保存した原文の改行がCRLFになっていたのを直しました。OSによらずLFで保存します。+- Windowsで、原文の保存先に同じ名前のフォルダがあると、そのフォルダが隠れた名前(`.paper.txt-` で始まる名前)に移されたまま残っていたのを直しました。保存先にフォルダがあるときは、何も動かさずに止まります。+- Windowsで試験の一部が落ちていたのを直しました。シンボリックリンクを作る権限が無い環境ではその試験を飛ばし、Windowsで使えない文字を含むフォルダ名は作らずに検査します。## [2.0.0] - 2026-10-25diff --git a/skills/imozuru/scripts/fetch.py b/skills/imozuru/scripts/fetch.pyindex 3eaa3dc..0d0a7f9 100755--- a/skills/imozuru/scripts/fetch.py+++ b/skills/imozuru/scripts/fetch.py@@ -49,6 +49,9 @@ CJK_RATIO_FOR_PDF = 0.3# 和文の字=かな・漢字・全角の英数字と記号_CJK = re.compile(r"[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]")MAX_BYTES = 40_000_000+# 保存する原文の改行。Windows の write_text は \n を \r\n に変えるので、同じ原文の写しが+# OS によってバイトで食い違っていた(2026-10-26 に Windows で試験を回して分かった)。OS によらず LF にそろえる+SOURCE_NEWLINE = "\n"# 外のコマンド(pdftotext・pdftoppm・tesseract・ax・yt-dlp)1回の時間の上限(秒)。# 細工した PDF やページで止まらなくなるのを防ぐ。ふつうの論文は数秒〜数十秒で終わる。TOOL_TIMEOUT = 300@@ -574,7 +577,7 @@ def ocr_if_longer(pdf: Path, text: str) -> tuple[str, str]:return text, notepdf.with_suffix(".txt").write_text(f"(OCR で起こした本文。{OCR_MAX_PAGES} ページを超える分は起こしていない。"- "誤りが残るので、引用は原本の PDF で確かめる)\n\n" + ocr, encoding="utf-8")+ "誤りが残るので、引用は原本の PDF で確かめる)\n\n" + ocr, encoding="utf-8", newline=SOURCE_NEWLINE)return ocr, ""@@ -707,7 +710,7 @@ def html_to_md(url: str, out: Path, body: bytes | None = None, ctype: str = "")parser = _TextExtractor(url)parser.feed(decode_text(body, ctype))text = parser.text()- out.write_text(text, encoding="utf-8")+ out.write_text(text, encoding="utf-8", newline=SOURCE_NEWLINE)return text@@ -812,7 +815,7 @@ def youtube_to_md(url: str, out: Path) -> str:info = " / ".join(head[1:3]) if len(head) > 1 else ""body = "\n".join(lines)out.write_text(f"# {title}\n\n{url}\n{info}\n字幕: {kind + ' ' + vtts[0].name if vtts else 'なし'}\n\n{body}\n",- encoding="utf-8")+ encoding="utf-8", newline=SOURCE_NEWLINE)return body@@ -1003,6 +1006,14 @@ def save_verified(saved: Path, kept: Path, destination: Path) -> Path:"""検査済みの原文を移し、途中で失敗したら保存済みの原文を戻す。"""files = [saved, kept] if saved != kept else [kept]files = [p for p in files if p.parent != destination]+ # 保存先に同じ名前のフォルダがあれば、何も動かす前に断る。Linux はフォルダを退避の一時ファイルへ+ # 移す操作を断るが、Windows の os.replace は移してしまい、後片付けで消せずに失敗して、+ # フォルダが隠れた名前のまま残った(2026-10-26 に Windows で試験を回して分かった)。+ # 検査のあと移すまでのあいだに、別のプロセスが同じ名前のフォルダを作る競合までは防いでいない+ for source in files:+ target = destination / source.name+ if target.is_dir() and not target.is_symlink():+ raise IsADirectoryError(f"保存先に同じ名前のフォルダがある: {target}")backups, moved = {}, []# 強制終了や電源断のときは退避した写しが残るだけで、自動では戻らない(その備えが要るなら復旧の記録を残す形にする)try:@@ -1089,7 +1100,7 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:"PMC は captcha なので、ブラウザで開いてもらう候補")return 1kept = saved = sources / f"{name}.md"- kept.write_text(text, encoding="utf-8")+ kept.write_text(text, encoding="utf-8", newline=SOURCE_NEWLINE)return verify_and_save(name, text, saved, kept, destination)try:@@ -1121,7 +1132,7 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:ext = ".json" if "json" in ctype else ".csv" if "csv" in ctype else ".md"kept = saved = sources / f"{name}{ext}"text = decode_text(body, ctype)- kept.write_text(text, encoding="utf-8")+ kept.write_text(text, encoding="utf-8", newline=SOURCE_NEWLINE)elif "html" in ctype or body.lstrip()[:1] == b"<":kept = sources / f"{name}.md"text = html_to_md(url, kept, body, ctype)diff --git a/skills/imozuru/scripts/report.py b/skills/imozuru/scripts/report.pyindex 331b018..8a00876 100644--- a/skills/imozuru/scripts/report.py+++ b/skills/imozuru/scripts/report.py@@ -76,21 +76,35 @@ def verify(src_dir: Path, q: dict) -> tuple[bool, list[str], int, int]:start = max(1, first - 2)end = min(len(lines), last + 2)# ここから先は、検査を通った first・last だけを使う- region = norm(" ".join(lines[start - 1:end]))+ # スペースでつないでから整えると、行頭の印は1行目のものしか消えない。2行目より後の「- 」が残り、+ # 箇条書きにまたがる抜き書きが落ちた(penpenguin の記事・2026-10-17)。+ # Markdown の原文に限り、行ごとに印を消した形でも照らす。Markdown の行頭の「- 」はリストの印で、+ # HTML から起こした .md は段落が1行にまとまる。PDF から起こした .txt では行頭の「- 」が負号のことがあり、+ # 消すと「- 5 mg」を「5 mg」と写した抜き書きまで通る(2026-10-26 のレビュー)ので、従来の形だけで照らす。+ # 従来の形を残すのは、印ごと写した前からの抜き書きを落とさないため+ window = lines[start - 1:end]+ regions = [norm(" ".join(window))]+ if path.suffix.lower() == ".md":+ regions.append(norm("\n".join(window)))# 2段組の PDF は左右の段が1行に混ざり、何行かにまたがる文はそのままでは照合できない# (Yoshida 2008 で起きた)。抜き書きを「…」で区切れば、区切りごとに順に照らす。# 区切りはページにも「…」として残るので、省いたことが読む人に見える。pieces = [norm(p) for p in q["text"].split("…") if norm(p)]- ok, pos = bool(pieces), 0+ ok = bool(pieces) and any(_in_order(pieces, region) for region in regions)+ c0 = max(1, q["line"] - CONTEXT_LINES)+ c1 = min(len(lines), last + CONTEXT_LINES)+ return ok, lines[c0 - 1:c1], c0, c1+++def _in_order(pieces: list[str], region: str) -> bool:+ """区切りがどれも、前の区切りより後ろに region の中で現れるか。"""+ pos = 0for piece in pieces:at = region.find(piece, pos)if at < 0:- ok = False- break+ return Falsepos = at + len(piece)- c0 = max(1, q["line"] - CONTEXT_LINES)- c1 = min(len(lines), last + CONTEXT_LINES)- return ok, lines[c0 - 1:c1], c0, c1+ return Truedef esc(s: str) -> str:diff --git a/tests/test_dashboard.py b/tests/test_dashboard.pyindex 0e32272..f13e0d6 100644--- a/tests/test_dashboard.py+++ b/tests/test_dashboard.py@@ -2,6 +2,7 @@import importlib.utilimport json+import osimport tempfileimport unittestfrom pathlib import Path@@ -13,6 +14,24 @@ spec = importlib.util.spec_from_file_location("dash", SCRIPTS / "dashboard.py")dash = importlib.util.module_from_spec(spec)spec.loader.exec_module(dash)+# Windows でシンボリックリンクを作る権限が無いときのエラー番号と、フォルダ名に使えない文字を含むときのエラー番号+WINERROR_PRIVILEGE_NOT_HELD = 1314+WINERROR_INVALID_NAME = 123+++def symlink_or_skip(test, link, target, **kwargs):+ """シンボリックリンクを作る。作れない環境(管理者でない Windows など)では、その試験を飛ばす。"""+ try:+ link.symlink_to(target, **kwargs)+ except NotImplementedError as exc:+ test.skipTest(f"Symlinks unavailable: {exc}")+ except OSError as exc:+ # 飛ばすのは権限が無いとき(WinError 1314)だけ。ほかの失敗は試験の準備の誤りなので落とす+ if getattr(exc, "winerror", None) != WINERROR_PRIVILEGE_NOT_HELD:+ raise+ test.skipTest(f"Symlinks unavailable: {exc}")++RUNS = """| 日付 | 話題 | 型 | 回した人 | 調査を区切った理由 | 周 | 原文 | 感覚と合った? ||---|---|---|---|---|---|---|---|| 2026-10-09 | 古い形(old-topic) | 掘り | モネ | 論点の被覆 | 2 | 3 | 「いいね」 |@@ -82,14 +101,14 @@ class DashboardTests(unittest.TestCase):with tempfile.TemporaryDirectory() as tmp:outside = Path(tmp)(outside / "map.md").write_text("問い: 外部の秘密\n", encoding="utf-8")- (self.root / "linked-topic").symlink_to(outside, target_is_directory=True)+ symlink_or_skip(self, self.root / "linked-topic", outside, target_is_directory=True)topics = dash.collect(self.root, [])self.assertNotIn("linked-topic", [t["slug"] for t in topics])self.assertEqual(self.request("/linked-topic/map.md?k=kk")[0], 404)for name in ("map.md", "log.md", "digest.html", "report.html", "queries.jsonl", "digest.json"):path = self.root / "new-topic" / namepath.unlink(missing_ok=True)- path.symlink_to(outside / "map.md")+ symlink_or_skip(self, path, outside / "map.md")topics = dash.collect(self.root, [])topic = next(t for t in topics if t["slug"] == "new-topic")self.assertEqual(topic["question"], "")@@ -117,7 +136,7 @@ class DashboardTests(unittest.TestCase):dest = Path(tmp) / "bundle"target = dest / relativetarget.parent.mkdir(parents=True, exist_ok=True)- target.symlink_to(outside if relative in (".", "new-topic") else marker)+ symlink_or_skip(self, target, outside if relative in (".", "new-topic") else marker)topics = dash.collect(self.root, [])with self.assertRaisesRegex(ValueError, "シンボリックリンク"):dash.write_bundle(topics, self.root, dest)@@ -136,7 +155,7 @@ class DashboardTests(unittest.TestCase):outside = Path(tmp) / "secret"outside.write_text("変えない", encoding="utf-8")old_tmp = self.root / ".index.html.tmp"- old_tmp.symlink_to(outside)+ symlink_or_skip(self, old_tmp, outside)with patch("sys.argv", ["dashboard.py", str(self.root)]), contextlib.redirect_stdout(io.StringIO()):self.assertEqual(dash.main(), 0)index = self.root / "index.html"@@ -214,7 +233,16 @@ class DashboardTests(unittest.TestCase):def test_unsafe_slugs_cannot_enter_current_item_css(self):import refor slug in ('bad"].on{color:red}', "<style>", "bad\\slug", "bad name"):- (self.root / slug).mkdir()+ # Windows ではフォルダ名に " や < を使えず、\ は区切りになる。その OS で作れない名前の調査は+ # 現れようがないので作らずに進む(\ を区切りとして作ると、安全な名前の bad ができてしまう)+ if os.sep in slug or (os.altsep and os.altsep in slug):+ continue+ try:+ (self.root / slug).mkdir()+ except OSError as exc:+ if getattr(exc, "winerror", None) != WINERROR_INVALID_NAME:+ raise+ continuetopics = dash.collect(self.root, [])self.assertEqual({t["slug"] for t in topics}, {"new-topic", "empty-topic"})malicious = 'x</style><script>alert(1)</script>"'diff --git a/tests/test_digest.py b/tests/test_digest.pyindex 07ca70d..ec9b9e3 100644--- a/tests/test_digest.py+++ b/tests/test_digest.py@@ -173,7 +173,13 @@ class DigestTests(unittest.TestCase):victim = self.topic.parent / f"keep-{name}.txt"victim.write_text("Keep", encoding="utf-8")planted = self.topic / f".{name}.html.tmp"- planted.symlink_to(victim)+ try:+ planted.symlink_to(victim)+ except OSError as exc:+ # 飛ばすのは、管理者でない Windows で権限が無いとき(WinError 1314)だけ。ほかの失敗は落とす+ if getattr(exc, "winerror", None) != 1314:+ raise+ self.skipTest(f"Symlinks unavailable: {exc}")build()self.assertEqual(victim.read_text(encoding="utf-8"), "Keep")self.assertTrue(planted.is_symlink())diff --git a/tests/test_file_boundaries.py b/tests/test_file_boundaries.pyindex 3360908..c95be1c 100644--- a/tests/test_file_boundaries.py+++ b/tests/test_file_boundaries.py@@ -94,6 +94,30 @@ class FileBoundaryTests(unittest.TestCase):self.assertTrue(ok)self.assertIn("Original sentence", context)+ def test_report_matches_extracts_across_bullet_lines(self):+ """箇条書きの何行かにまたがる抜き書きを、印を除いても、印ごと写しても通す。言い換えは通さない。"""+ (self.sources / "list.md").write_text(+ "# 手順\n\n- 一つ目の項目です\n- 二つ目の項目です\n* 三つ目の項目です\n", encoding="utf-8")+ cases = {+ "一つ目の項目です 二つ目の項目です": True,+ "一つ目の項目です\n二つ目の項目です\n三つ目の項目です": True,+ "一つ目の項目です - 二つ目の項目です": True,+ "一つ目の項目です 三つ目の項目です": False,+ "一つ目の項目でした 二つ目の項目です": False,+ }+ for text, expected in cases.items():+ with self.subTest(text=text):+ q = {"file": "list.md", "line": 3, "end": 5, "text": text}+ self.assertEqual(report.verify(self.sources, q)[0], expected)++ def test_report_keeps_line_start_minus_in_text_sources(self):+ """PDF から起こした .txt の行頭の「- 」は負号のことがある。負号を落とした抜き書きは通さない。"""+ (self.sources / "paper.txt").write_text("変化量は\n- 5 mgです。\n", encoding="utf-8")+ for text, expected in (("変化量は 5 mgです。", False), ("変化量は - 5 mgです。", True)):+ with self.subTest(text=text):+ q = {"file": "paper.txt", "line": 1, "end": 2, "text": text}+ self.assertEqual(report.verify(self.sources, q)[0], expected)+def test_failed_report_keeps_prior_content(self):(self.sources / "paper.md").write_text("Original sentence", encoding="utf-8")data = {"title": "Test", "question": "Q", "stopped": "Done", "claims": [diff --git a/tests/test_portability.py b/tests/test_portability.pyindex 87bacfb..63ceb7a 100644--- a/tests/test_portability.py+++ b/tests/test_portability.py@@ -5,6 +5,7 @@ import contextlibimport http.serverimport importlib.utilimport io+import localeimport subprocessimport sysimport tempfile@@ -62,10 +63,12 @@ class EncodingTests(unittest.TestCase):def test_report_check_runs_without_default_encoding(self):"""既定の文字コードに頼る箇所があれば、EncodingWarning をエラーにして落とす。"""+ # 子のプロセスは、パイプへの出力を手元の文字コード(Windows では cp932)で書き、出せない字だけを置き換える。+ # utf-8 で読むと Windows では読めずに stdout が None になっていた(2026-10-26)res = subprocess.run([sys.executable, "-I", "-X", "warn_default_encoding", "-W", "error::EncodingWarning",str(SCRIPTS / "report.py"), str(ROOT / "examples/demo"), "--check"],- capture_output=True, encoding="utf-8")+ capture_output=True, encoding=locale.getpreferredencoding(False), errors="replace")self.assertEqual(res.returncode, 0, res.stderr)self.assertIn("照合 OK", res.stdout)