Skip to content

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

Python

report: 引用に元のページへのリンクを付ける(#16)

MaryCachec4cd5602d1b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 605303f..9b14e3b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ mainにコミットが入るたびに、使っている人へ更新が届きま
- 文書を開けなかったときは、札に理由と次の行動を出します。理由は「サーバーが止まっている」「PCに届かない」「合言葉を確かめられない」「文書が見つからない」に分けます。札のボタンで読み直せます。
- 10秒を超えても読み終わらないときは、サーバーが動いているかを確かめてから、まだ読み込んでいるのか止まっているのかを札に出します。
- サーバーに届かないときの代わりの画面を、端末に置くようにしました。配信した画面(`--serve`)を一度開くとservice workerが入り、次からはサーバーが止まっていても白い画面にならず、理由の札を出します。札は5秒ごとにサーバーを確かめ、戻ったら自動で開き直します。端末に置くのは代わりの画面だけで、調査の中身は置きません。
+- 抜き書きと詳細レポートの引用に、元のページへのリンク「元のページを開く」を付けるようにしました(#16、yuki-kogetsuさんの報告と案)。URLはmap.mdの「原文(sources/)」の表の「元の URL」の列から引き、`http://`か`https://`で始まる完全なURLだけをリンクにします。「ファイル」の列は、読点・カンマ・中黒・全角の「/」で並べた書き方、`a.pdf/.txt`のようにPDFとその文字起こしを1つに書いた書き方、括弧の注記、`sources/`付きの書き方を読み分けます。1行にURLが複数あってファイルの数と合わないときは、リンクを付けません。抜き書きの`url`で、表に無い原文にもリンクを付けられます。
### 修正
diff --git a/skills/imozuru/SKILL.md b/skills/imozuru/SKILL.md
index b56ecd6..ab376e5 100644
--- a/skills/imozuru/SKILL.md
+++ b/skills/imozuru/SKILL.md
@@ -153,12 +153,12 @@ map.md を下の書式で作り、**問い**と、答えるのに要る**論点*
原文を何十本も保存しただけでは読まれない(英語の PDF や1時間の字幕のまま)。かといって要約すると、早すぎる結論を招く。だから止めたら、**抜き書き**(Ellis の extracting)でページを作り、それを最初に渡す。
-1. `<topic_dir>/extracts.json` を書く。調査の論点ごとに節を立て、原文から**そのまま切り出した文**を並べる(ファイル・行・必要なら `end`)。英語には `ja` に訳を添える(訳だと分かる印がページに付く)。印(〔本人〕自動字幕 など)は `mark` に。2段組の PDF のように左右の段が1行に混ざる所は、抜き書きを「…」で区切ると区切りごとに順に照合される(省いたことはページにも「…」で見える)。食い違いは `disagreements` に並べるだけで、どれが正しいかは書かない。届かなかったものは `unreached` に。形の手本はリポジトリの `examples/demo/extracts.json`
+1. `<topic_dir>/extracts.json` を書く。調査の論点ごとに節を立て、原文から**そのまま切り出した文**を並べる(ファイル・行・必要なら `end`)。英語には `ja` に訳を添える(訳だと分かる印がページに付く)。印(〔本人〕自動字幕 など)は `mark` に。元のページへのリンクは、map.md の「原文(sources/)」の表の「元の URL」から自動で付く(http(s) の完全な URL だけ)。表に無い原文に付けたいときだけ `url` に書く。2段組の PDF のように左右の段が1行に混ざる所は、抜き書きを「…」で区切ると区切りごとに順に照合される(省いたことはページにも「…」で見える)。食い違いは `disagreements` に並べるだけで、どれが正しいかは書かない。届かなかったものは `unreached` に。形の手本はリポジトリの `examples/demo/extracts.json`
形は report.py の冒頭と同じ(`?` は省いてよい)。
```
{"title", "question", "stopped",
"claims": [{"claim", "status": "根拠あり|一部のみ|根拠なし", "note"?,
- "quotes": [{"file", "line", "end"?, "text", "ja"?, "mark"?}]}],
+ "quotes": [{"file", "line", "end"?, "text", "ja"?, "mark"?, "url"?}]}],
"disagreements"?: [{"topic", "quotes": [{"file", "line", "text", "who", ...}]}],
"unreached"?: ["..."]}
```
diff --git a/skills/imozuru/scripts/report.py b/skills/imozuru/scripts/report.py
index c6ec5bc..bdf5bce 100644
--- a/skills/imozuru/scripts/report.py
+++ b/skills/imozuru/scripts/report.py
@@ -16,18 +16,22 @@ extracting=抜き書き。論点ごとに原文をそのまま切り出して
extracts.json の形(例はリポジトリの examples/demo/extracts.json):
{"title", "question", "stopped",
"claims": [{"claim", "status": "根拠あり|一部のみ|根拠なし", "note"?,
- "quotes": [{"file", "line", "end"?, "text", "ja"?, "mark"?, "context_note"?}]}],
+ "quotes": [{"file", "line", "end"?, "text", "ja"?, "mark"?, "context_note"?, "url"?}]}],
"disagreements"?: [{"topic", "quotes": [{..., "who"}]}],
"unreached"?: ["..."]}
+引用の元のページへのリンクは "url" か、無ければ map.md の「原文(sources/)」の表の「元の URL」から付ける。
"""
+import fnmatch
import html
import json
import os
import re
import sys
import tempfile
+from functools import lru_cache
from pathlib import Path, PureWindowsPath
+from urllib.parse import urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parent))
import skin # noqa: E402 見た目(コルク板と象牙の紙)と色は skin.py・palette.py の1か所に置く
@@ -93,6 +97,118 @@ def esc(s: str) -> str:
return html.escape(s, quote=True)
+# 引用に、元のページへのリンクを付ける(#16・2026-10-25)。元の URL は map.md の「原文(sources/)」の表の「元の URL」の列にある。
+# 「ファイル」の列は1つの名前とは限らない。手元の 46 件の調査の map.md には、読点・カンマ・中黒・全角の「/」で並べた行、
+# PDF とその文字起こしを a.pdf/.txt や a.pdf / .txt(a.pdf と a.txt の2本)と1つの表記で書いた行、(未読)のような注記、
+# sources/ 付き、ワイルドカード(ms-learn-*.md)、ファイル名そのものに入った半角の丸括弧(-r)があった
+SOURCE_URL = re.compile(r"https?://[^\s\"'<>|`()「」、。]+")
+NAME_SEP = re.compile(r"[、,,・/]+|\s+")
+EXT_ALT = re.compile(r"^(.+?)\.(\w+)((?:/\.\w+)+)$")
+
+
+def link_url(url) -> str:
+ """リンクにしてよい URL だけを返す。http(s) で、ホストがあり、空白・引用符・<> を含まないもの。javascript: などは捨てる"""
+ if not isinstance(url, str) or not re.fullmatch(r"https?://[^\s\"'<>]+", url):
+ return ""
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return ""
+ return url if parts.scheme in ("http", "https") and parts.netloc else ""
+
+
+def file_groups(cell: str) -> list[list[str]]:
+ """「ファイル」の列の1行を、元の URL と組にする単位(並べた1つ1つ)ごとのファイル名の並びにする。
+ a.pdf/.txt は1つの単位で a.pdf と a.txt の2本。/ を含む名前は、下のフォルダの名前かもしれないので全体も残す"""
+ s = cell.replace("`", "")
+ # 全角の括弧は注記(未読 など)。半角の丸括弧はファイル名に入ることがあるので外さない
+ s = re.sub(r"([^)]*)", " ", s)
+ s = re.sub(r"(?<![\w.-])sources/", "", s)
+ # 拡張子だけが続く書き方(a.pdf/.txt・a.pdf / .txt・a.pdf・.txt)は、どれも同じ名前の別の拡張子
+ s = re.sub(r"\s*[/・、,,]\s*(?=\.\w+(?![\w.]))", "/", s)
+ groups = []
+ for token in NAME_SEP.split(s):
+ m = EXT_ALT.match(token)
+ if m:
+ names = [f"{m.group(1)}.{m.group(2)}"] + [m.group(1) + e for e in re.findall(r"/(\.\w+)", m.group(3))]
+ else:
+ names = [token] + (token.split("/") if "/" in token else [])
+ names = [n for n in names if re.search(r"\.\w+$", n)]
+ if names:
+ groups.append(names)
+ return groups
+
+
+def cell_urls(cell: str) -> list[str]:
+ urls = []
+ for u in SOURCE_URL.findall(cell):
+ u = u.rstrip(".,;:")
+ while u.endswith(")") and u.count(")") > u.count("("):
+ u = u[:-1]
+ if link_url(u):
+ urls.append(u)
+ return urls
+
+
+@lru_cache(maxsize=64)
+def _source_rows(map_path: str, _mtime: int) -> tuple:
+ try:
+ text = Path(map_path).read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return ()
+ rows = []
+ for head in re.finditer(r"^\|[^\n]*\|[ \t]*$", text, re.M):
+ cols = [c.strip() for c in head.group(0).strip().strip("|").split("|")]
+ if "ファイル" not in cols or "元の URL" not in cols:
+ continue
+ fi, ui = cols.index("ファイル"), cols.index("元の URL")
+ # 見出しの次の行は区切り(|---|)。表が終わる(| で始まらない行)まで読む。
+ # 区切りの行と最初の行のあいだに空行を挟んだ map.md があったので、空行は飛ばす
+ for line in text[head.end():].lstrip("\n").split("\n")[1:]:
+ if not line.strip():
+ continue
+ if not line.startswith("|"):
+ break
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
+ if len(cells) <= max(fi, ui):
+ continue
+ groups = file_groups(cells[fi])
+ # 「同上」は前の行の URL を引き継がない。手元では、別々の論文が並ぶ行で「URL は log 参照」の注記を繰り返す意味だった
+ urls = cell_urls(cells[ui])
+ # URL が1つなら、その行のファイル全部の元。ファイルの単位と同じ数なら順に組にする。
+ # 数が合わないときは付けない(違うページへのリンクは、リンクが無いより悪い)
+ if len(urls) == 1:
+ rows += [(tuple(g), urls[0]) for g in groups]
+ elif urls and len(urls) == len(groups):
+ rows += [(tuple(g), u) for g, u in zip(groups, urls)]
+ return tuple(rows)
+
+
+def source_url(src_dir: Path, file: str) -> str:
+ """引用の原文(sources/ からの相対)の元の URL を、map.md の「原文(sources/)」の表から引く。見つからなければ空"""
+ map_path = Path(src_dir).parent / "map.md"
+ try:
+ mtime = map_path.stat().st_mtime_ns
+ except OSError:
+ return ""
+ rows = _source_rows(str(map_path), mtime)
+ wanted = {file, Path(file).name}
+ for names, url in rows:
+ if any(n in wanted or ("*" in n and fnmatch.fnmatchcase(Path(file).name, n)) for n in names):
+ return url
+ # 名前が合う行が無いときだけ、拡張子を除いた名前で照合する。表に a.md と書いて、実物は文字起こしの a.txt という行があった
+ stem = Path(file).stem
+ for names, url in rows:
+ if any("*" not in n and Path(n).stem == stem for n in names):
+ return url
+ return ""
+
+
+# 外へ出るリンクの印。ほかの印と同じく文字ではなく線の絵にする
+OUT_ICON = ('<svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true" fill="none" stroke="currentColor" '
+ 'stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></svg>')
+
+
def quote_html(src_dir: Path, q: dict, ctx: list[str], c0: int) -> str:
loc = f"{q['file']}:{q['line']}" + (f"-{q['end']}" if q.get("end") else "")
hit = range(q["line"], (q.get("end") or q["line"]) + 1)
@@ -108,6 +224,9 @@ def quote_html(src_dir: Path, q: dict, ctx: list[str], c0: int) -> str:
if q.get("ja"):
parts.append(f'<p class="ja"><span class="tag">訳</span>{esc(q["ja"])}</p>')
meta = [f'<code>{esc(loc)}</code>']
+ url = link_url(q.get("url")) or source_url(src_dir, q["file"])
+ if url:
+ meta.append(f'<a class="src" href="{esc(url)}" target="_blank" rel="noopener noreferrer">元のページを開く{OUT_ICON}</a>')
if q.get("mark"):
meta.append(f'<span class="mark">{esc(q["mark"])}</span>')
if q.get("context_note"):
@@ -132,6 +251,8 @@ blockquote{margin:0;padding-left:.9rem;border-left:3px solid var(--accent);white
.ja{margin:.6rem 0 0;color:var(--sub)}
.tag{font-size:.75rem;border:1px solid var(--sub);border-radius:4px;padding:0 .3rem;margin-right:.4rem}
figcaption{margin-top:.6rem;font-size:.8rem;color:var(--sub);display:flex;flex-wrap:wrap;gap:.5rem}
+figcaption a.src{display:inline-flex;align-items:center;gap:.25rem;color:inherit;white-space:nowrap}
+figcaption a.src svg{flex:none}
code{font-family:ui-monospace,"Cascadia Code",monospace;font-size:.78rem}
.mark{color:var(--accent)}
details{margin-top:.5rem;font-size:.8rem}
diff --git a/tests/test_report_links.py b/tests/test_report_links.py
new file mode 100644
index 0000000..33c8bc1
--- /dev/null
+++ b/tests/test_report_links.py
@@ -0,0 +1,132 @@
+"""引用に元のページへのリンクを付ける(#16)検査。map.md の「原文(sources/)」の表の「ファイル」の列の書き方を読み分けること、
+リンクにするのが http(s) の URL だけであること、数の合わない行や「同上」で別の原文へリンクしないことを見る。"""
+
+import importlib.util
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SCRIPTS = Path(__file__).resolve().parents[1] / "skills/imozuru/scripts"
+sys.path.insert(0, str(SCRIPTS))
+spec = importlib.util.spec_from_file_location("report_links", SCRIPTS / "report.py")
+report = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(report)
+
+# 手元の map.md にあった書き方を1行ずつ並べた表。区切りの行と最初の行のあいだの空行も、手元にあった形
+MAP = """# 調査
+## 原文(sources/)
+| 論文・資料 | ファイル | 元の URL | どこから来たか |
+|---|---|---|---|
+
+| 論文 A | a-paper.pdf/.txt | https://example.org/a.pdf | 1周目 |
+| 論文 B | b-paper.pdf / .txt | https://example.org/b.pdf | 1周目 |
+| 論文 C | c-paper.pdf・.txt | https://example.org/c.pdf | 1周目 |
+| 記事 D と E | d-post.md・e-post.md | https://example.org/d https://example.org/e | 1周目 |
+| 記事 F | `sources/f-post.md`(未読) | https://example.org/f | 1周目 |
+| 記事 G | g-post(-r).md | https://example.org/g | 1周目 |
+| 記事 H と I | h.md, i.md, j.md | https://example.org/h https://example.org/i | 数が合わない |
+| 記事 K | k-post.md | 同上 | 前の行の注記の繰り返し |
+| 記事 L | l-post.md | learn.example.org/…/l | 省略した URL |
+| 記事 M | m-post.md | javascript:alert(1) | 悪い URL |
+| 資料 N | n-note.md | https://example.org/n | 表は .md、実物は .txt |
+| 資料 O | ms-learn-*.md ほか | https://example.org/o | ワイルドカード |
+
+## 次の手がかり
+| 語 | ファイル | 元の URL | 備考 |
+|---|---|---|---|
+"""
+
+
+class FileGroupTests(unittest.TestCase):
+ def test_issue_examples_split_on_separators_and_drop_notes(self):
+ # Issue に書かれた形: 読点・カンマで分け、括弧の注記を外す
+ self.assertEqual(report.file_groups("a.md, a.txt(未読)"), [["a.md"], ["a.txt"]])
+ self.assertEqual(report.file_groups("a.md、b.md"), [["a.md"], ["b.md"]])
+
+ def test_extension_alternates_are_one_source_with_two_files(self):
+ for cell in ("a.pdf/.txt", "a.pdf / .txt", "a.pdf・.txt", "`sources/a.pdf/.txt`"):
+ self.assertEqual(report.file_groups(cell), [["a.pdf", "a.txt"]], cell)
+
+ def test_other_separators_and_kept_parentheses(self):
+ self.assertEqual(report.file_groups("a.md・b.md"), [["a.md"], ["b.md"]])
+ self.assertEqual(report.file_groups("a.md/b.md"), [["a.md"], ["b.md"]])
+ # 半角の丸括弧はファイル名の一部
+ self.assertEqual(report.file_groups("g-post(-r).md"), [["g-post(-r).md"]])
+ # 下のフォルダの名前は全体も残す
+ self.assertEqual(report.file_groups("deepseek/x.md"), [["deepseek/x.md", "x.md"]])
+ # 名前でない語(ほか)は捨てる
+ self.assertEqual(report.file_groups("ms-learn-*.md ほか"), [["ms-learn-*.md"]])
+
+
+class LinkUrlTests(unittest.TestCase):
+ def test_only_http_urls_without_spaces_or_quotes(self):
+ self.assertEqual(report.link_url("https://example.org/a?b=1"), "https://example.org/a?b=1")
+ for bad in ("javascript:alert(1)", "data:text/html,x", "https://", "https://a b", 'https://a"b', "https://a<b", "", None, 3):
+ self.assertEqual(report.link_url(bad), "", bad)
+
+
+class SourceUrlTests(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.topic = Path(tmp.name)
+ (self.topic / "sources").mkdir()
+ (self.topic / "map.md").write_text(MAP, encoding="utf-8")
+ self.src = self.topic / "sources"
+
+ def url(self, file):
+ return report.source_url(self.src, file)
+
+ def test_quotes_point_at_the_text_file_of_a_pdf(self):
+ self.assertEqual(self.url("a-paper.txt"), "https://example.org/a.pdf")
+ self.assertEqual(self.url("b-paper.txt"), "https://example.org/b.pdf")
+ self.assertEqual(self.url("c-paper.txt"), "https://example.org/c.pdf")
+
+ def test_urls_pair_with_sources_in_order_only_when_counts_match(self):
+ self.assertEqual(self.url("d-post.md"), "https://example.org/d")
+ self.assertEqual(self.url("e-post.md"), "https://example.org/e")
+ # 3本に URL が2つ。どれがどれか決まらないので付けない
+ for f in ("h.md", "i.md", "j.md"):
+ self.assertEqual(self.url(f), "", f)
+
+ def test_notes_prefix_parentheses_and_wildcards(self):
+ self.assertEqual(self.url("f-post.md"), "https://example.org/f")
+ self.assertEqual(self.url("g-post(-r).md"), "https://example.org/g")
+ self.assertEqual(self.url("ms-learn-adds-overview.md"), "https://example.org/o")
+
+ def test_no_link_for_same_as_above_shortened_or_unsafe_urls(self):
+ self.assertEqual(self.url("k-post.md"), "")
+ self.assertEqual(self.url("l-post.md"), "")
+ self.assertEqual(self.url("m-post.md"), "")
+
+ def test_extension_only_mismatch_falls_back_to_the_stem(self):
+ self.assertEqual(self.url("n-note.txt"), "https://example.org/n")
+
+ def test_unknown_source_or_missing_map_gives_no_link(self):
+ self.assertEqual(self.url("nowhere.md"), "")
+ (self.topic / "map.md").unlink()
+ self.assertEqual(self.url("a-paper.txt"), "")
+
+
+class QuoteHtmlTests(SourceUrlTests):
+ def quote(self, **q):
+ q = {"file": "a-paper.txt", "line": 1, "text": "x", **q}
+ return report.quote_html(self.src, q, ["x"], 1)
+
+ def test_link_opens_a_new_tab_without_referrer(self):
+ page = self.quote()
+ self.assertIn('<a class="src" href="https://example.org/a.pdf" target="_blank" rel="noopener noreferrer">', page)
+
+ def test_url_in_the_quote_wins_and_unsafe_ones_fall_back_to_the_map(self):
+ self.assertIn('href="https://example.org/own"', self.quote(url="https://example.org/own"))
+ page = self.quote(url="javascript:alert(1)")
+ self.assertNotIn("javascript:", page)
+ self.assertIn('href="https://example.org/a.pdf"', page)
+
+ def test_no_link_when_nothing_is_found(self):
+ self.assertNotIn('class="src"', self.quote(file="nowhere.md"))
+
+
+if __name__ == "__main__":
+ unittest.main()