from __future__ import annotations from copy import deepcopy import hashlib import json import sys from pathlib import Path import pytest import link_glossary_terms as linker from conftest import write_current_workflow from glossary_common import canonical_sha256, selection_sha256 from glossary_config import configure_terms_dir from link_glossary_terms import link_article_terms, main from write_glossary_terms import render_term_file def digest(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def _writer_mappings_sha256(payload: dict) -> str: mappings = [ { field: item[field] for field in ("name", "forms", "file", "link_stem") } for item in payload["results"] ] return canonical_sha256( { "provenance": payload["provenance"], "mappings": mappings, "context": payload["context"], "triage_sha256": payload["triage_sha256"], } ) def _triage_sha256(payload: dict) -> str: return canonical_sha256( { "paper_id": payload["paper_id"], "provenance": payload["provenance"], "terms": payload["terms"], } ) def test_linker_links_first_safe_alias_and_skips_all_protected_regions( tmp_path: Path, ) -> None: article = tmp_path / "Paper.md" article.write_text( "---\ntitle: ReAct\n---\n" "# ReAct heading\n\n" "`ReAct agent` and [ReAct](https://example.test/ReAct) are protected.\n" "ReAct https://example.test/ReAct [[Other|ReAct]]\n\n" "REACT combines reasoning and acting. ReAct appears again.\n\n" "```python\nReAct = 'code'\n```\n\n" "## References\nReAct paper\n", encoding="utf-8", ) result = link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct", "REACT"]}], digest(article), ) text = article.read_text(encoding="utf-8") assert "[[ReAct|REACT]] combines reasoning" in text assert "# ReAct heading" in text assert "`ReAct agent`" in text assert "[ReAct](https://example.test/ReAct)" in text assert "ReAct" in text assert "https://example.test/ReAct" in text assert "[[Other|ReAct]]" in text assert "```python\nReAct = 'code'\n```" in text assert "## References\nReAct paper" in text assert text.count("[[ReAct|REACT]]") == 1 assert result["summary"] == {"linked": 1, "already_linked": 0, "not_found": 0} def _link(tmp_path: Path, body: str, mappings: list[dict]) -> tuple[str, dict]: article = tmp_path / "Paper.md" article.write_text(body, encoding="utf-8") result = link_article_terms(article, mappings, digest(article)) return article.read_text(encoding="utf-8"), result def test_whole_inline_code_term_becomes_a_link_without_backticks(tmp_path: Path) -> None: text, result = _link(tmp_path, "本文提出 `DPO`,直接优化偏好。\n", [{"link_stem": "DPO", "forms": ["DPO"]}]) assert text == "本文提出 [[DPO]],直接优化偏好。\n" assert result["summary"] == {"linked": 1, "already_linked": 0, "not_found": 0} def test_inline_code_with_different_case_keeps_its_surface(tmp_path: Path) -> None: text, _ = _link(tmp_path, "we compare against `dpo` here.\n", [{"link_stem": "DPO", "forms": ["DPO"]}]) assert text == "we compare against [[DPO|dpo]] here.\n" @pytest.mark.parametrize("span", ["`` DPO ``", "``DPO``", "` DPO `"]) def test_padded_and_multi_backtick_spans_follow_commonmark(tmp_path: Path, span: str) -> None: text, _ = _link(tmp_path, f"方法 {span} 很简单。\n", [{"link_stem": "DPO", "forms": ["DPO"]}]) assert text == "方法 [[DPO]] 很简单。\n" @pytest.mark.parametrize("span", ["`Ego-R1 Bench`", "` DPO`", "`DPO `", "`DPO()`"]) def test_partial_inline_code_matches_stay_protected(tmp_path: Path, span: str) -> None: body = f"见 {span}。\n" text, result = _link( tmp_path, body, [{"link_stem": "Ego-R1", "forms": ["Ego-R1"]}, {"link_stem": "DPO", "forms": ["DPO"]}], ) assert text == body assert result["summary"]["linked"] == 0 def test_bare_text_before_inline_code_is_linked_first(tmp_path: Path) -> None: text, _ = _link(tmp_path, "DPO is simple. Later `DPO` again.\n", [{"link_stem": "DPO", "forms": ["DPO"]}]) assert text == "[[DPO]] is simple. Later `DPO` again.\n" @pytest.mark.parametrize( "body", [ "```text\n`DPO`\n```\n", " `DPO` in indented code\n", "## 使用 `DPO`\n", "[`DPO`](https://example.test/dpo)\n", "[[Other|`DPO`]]\n", "`DPO`\n", "## 参考文献\n\n`DPO` paper\n", "## 关联\n\n- `DPO`\n", ], ) def test_inline_code_inside_other_protected_regions_is_not_linked(tmp_path: Path, body: str) -> None: text, result = _link(tmp_path, body, [{"link_stem": "DPO", "forms": ["DPO"]}]) assert text == body assert result["summary"]["not_found"] == 1 def test_realistic_chinese_note_links_each_backticked_term_once(tmp_path: Path) -> None: body = ( "---\ntags: [papers/AI]\nmethods: [\"[[WorldMM]]\"]\n---\n\n" "# WorldMM\n\n" "## 核心结论\n\n" "- 作者在 `EgoLifeQA` 与 `LVBench` 上评测,`WorldMM` 比 `GPT-4o` 高 `8.4` 个点。\n" "- 在 `EgoLifeQA` 的长时问题上提升最明显。\n\n" "## 方法\n\n" "调用 `find_acoustic_hotspots` 工具定位声音片段,`Ego-R1 Bench` 用作补充。\n\n" "## 关联\n\n" "- [[Ego-R1.zh-CN|Ego-R1]]:同一基准。\n" ) mappings = [ {"link_stem": "EgoLifeQA", "forms": ["EgoLifeQA"]}, {"link_stem": "LVBench", "forms": ["LVBench"]}, {"link_stem": "GPT-4o", "forms": ["GPT-4o"]}, {"link_stem": "Ego-R1", "forms": ["Ego-R1"]}, ] text, result = _link(tmp_path, body, mappings) assert "作者在 [[EgoLifeQA]] 与 [[LVBench]] 上评测,`WorldMM` 比 [[GPT-4o]] 高 `8.4` 个点。" in text assert "在 `EgoLifeQA` 的长时问题上" in text assert "`find_acoustic_hotspots`" in text and "`Ego-R1 Bench`" in text assert text.count("[[EgoLifeQA]]") == 1 assert [item["status"] for item in result["results"]] == ["linked", "linked", "linked", "not_found"] def test_linker_uses_safe_stem_and_does_not_duplicate_link(tmp_path: Path) -> None: article = tmp_path / "Paper.md" article.write_text("C# is a programming language.\n", encoding="utf-8") mappings = [{"link_stem": "C#", "forms": ["C#"]}] first = link_article_terms(article, mappings, digest(article)) second = link_article_terms(article, mappings, digest(article)) assert article.read_text(encoding="utf-8") == ( "[[C#|C#]] is a programming language.\n" ) assert first["results"] == [{"link_stem": "C#", "status": "linked"}] assert second["results"] == [ {"link_stem": "C#", "status": "already_linked"} ] def test_linker_rejects_stale_article_hash_before_writing(tmp_path: Path) -> None: article = tmp_path / "Paper.md" original = b"ReAct text\n" article.write_bytes(original) with pytest.raises(SystemExit, match="changed since preview"): link_article_terms(article, [{"link_stem": "ReAct", "forms": ["ReAct"]}], "0" * 64) assert article.read_bytes() == original def test_linker_prefers_longer_forms_and_rejects_substrings(tmp_path: Path) -> None: article = tmp_path / "Paper.md" article.write_text("SerpApi is an API. XAPI and APIClient are not API terms.\n", encoding="utf-8") result = link_article_terms( article, [ {"link_stem": "API", "forms": ["API"]}, {"link_stem": "SerpApi", "forms": ["SerpApi"]}, ], digest(article), ) assert article.read_text(encoding="utf-8") == ( "[[SerpApi]] is an [[API]]. XAPI and APIClient are not API terms.\n" ) assert result["summary"] == {"linked": 2, "already_linked": 0, "not_found": 0} def test_linker_reports_existing_target_as_already_linked_without_rewriting( tmp_path: Path, ) -> None: article = tmp_path / "Paper.md" original = b"[[ReAct|REACT]] is already linked. ReAct remains plain.\n" article.write_bytes(original) result = link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct", "REACT"]}], digest(article), ) assert article.read_bytes() == original assert result["results"] == [{"link_stem": "ReAct", "status": "already_linked"}] assert result["summary"] == {"linked": 0, "already_linked": 1, "not_found": 0} def test_linker_preserves_utf8_bom_and_crlf_newlines(tmp_path: Path) -> None: article = tmp_path / "Paper.md" article.write_bytes(b"\xef\xbb\xbfReAct text\r\nSecond line\r\n") link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct"]}], digest(article), ) assert article.read_bytes() == b"\xef\xbb\xbf[[ReAct]] text\r\nSecond line\r\n" def test_linker_reports_not_found_and_leaves_bytes_unchanged(tmp_path: Path) -> None: article = tmp_path / "Paper.md" original = b"Only plain prose here.\n" article.write_bytes(original) result = link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct"]}], digest(article), ) assert article.read_bytes() == original assert result["results"] == [{"link_stem": "ReAct", "status": "not_found"}] assert result["summary"] == {"linked": 0, "already_linked": 0, "not_found": 1} def test_linker_is_idempotent(tmp_path: Path) -> None: article = tmp_path / "Paper.md" article.write_text("ReAct text\n", encoding="utf-8") mappings = [{"link_stem": "ReAct", "forms": ["ReAct"]}] link_article_terms(article, mappings, digest(article)) linked_bytes = article.read_bytes() result = link_article_terms(article, mappings, digest(article)) assert article.read_bytes() == linked_bytes assert result["summary"] == {"linked": 0, "already_linked": 1, "not_found": 0} def test_cli_rejects_article_outside_configured_vault_before_linking( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: configured_vault = tmp_path / "configured" other_vault = tmp_path / "other" (configured_vault / ".obsidian").mkdir(parents=True) (other_vault / ".obsidian").mkdir(parents=True) config_path = tmp_path / "device" / "config.json" configure_terms_dir(configured_vault / "Terms", config_path) article = other_vault / "Paper.md" original = b"ReAct text\n" article.write_bytes(original) writer_result = tmp_path / "writer-result.json" writer_result.write_text( json.dumps( { "status": "ok", "results": [{"link_stem": "ReAct", "forms": ["ReAct"]}], } ), encoding="utf-8", ) monkeypatch.setattr( sys, "argv", [ "link_glossary_terms.py", "--input", str(article), "--write-result", str(writer_result), "--expected-sha256", digest(article), "--config-path", str(config_path), "--source-manifest", str(tmp_path / "unused-manifest.json"), "--reviewed-shortlist", str(tmp_path / "unused-review.json"), "--triage", str(tmp_path / "unused-triage.json"), ], ) with pytest.raises(SystemExit, match="same Obsidian vault"): main() assert article.read_bytes() == original def test_cli_consumes_only_successful_writer_results( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: vault = tmp_path / "vault" (vault / ".obsidian").mkdir(parents=True) config_path = tmp_path / "device" / "config.json" configure_terms_dir(vault / "Terms", config_path) article = vault / "Paper.md" original = b"ReAct text\n" article.write_bytes(original) writer_result = tmp_path / "writer-result.json" writer_result.write_text( json.dumps({"status": "failed", "results": []}), encoding="utf-8" ) monkeypatch.setattr( sys, "argv", [ "link_glossary_terms.py", "--input", str(article), "--write-result", str(writer_result), "--expected-sha256", digest(article), "--config-path", str(config_path), "--source-manifest", str(tmp_path / "unused-manifest.json"), "--reviewed-shortlist", str(tmp_path / "unused-review.json"), "--triage", str(tmp_path / "unused-triage.json"), ], ) with pytest.raises(SystemExit, match="successful writer result"): main() assert article.read_bytes() == original @pytest.mark.parametrize( "original", [ b"---\ntitle: ReAct\nbody: ReAct\n", b"```python\nReAct = 'protected'\n", b"````python\nReAct = 'protected'\n```\nstill ReAct\n", ], ids=["unclosed-frontmatter", "unclosed-fence", "short-fence-closer"], ) def test_linker_protects_unclosed_frontmatter_and_fences_to_eof( tmp_path: Path, original: bytes ) -> None: article = tmp_path / "Paper.md" article.write_bytes(original) result = link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct"]}], digest(article), ) assert article.read_bytes() == original assert result["summary"] == {"linked": 0, "already_linked": 0, "not_found": 1} def test_linker_protects_nested_same_name_html_elements(tmp_path: Path) -> None: article = tmp_path / "Paper.md" article.write_text( "nested ReAct\nReAct prose\n", encoding="utf-8" ) link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct"]}], digest(article), ) assert article.read_text(encoding="utf-8") == ( "nested ReAct\n[[ReAct]] prose\n" ) @pytest.mark.parametrize("tag", ["strong", "b", "em", "i"]) def test_linker_links_visible_text_inside_simple_html_emphasis( tmp_path: Path, tag: str ) -> None: article = tmp_path / "Paper.md" article.write_text(f"<{tag}>ReAct{tag}> prose\n", encoding="utf-8") result = link_article_terms( article, [{"link_stem": "ReAct", "forms": ["ReAct"]}], digest(article), ) assert article.read_text(encoding="utf-8") == ( f"<{tag}>[[ReAct]]{tag}> prose\n" ) assert result["results"] == [{"link_stem": "ReAct", "status": "linked"}] def test_linker_keeps_emphasis_text_protected_inside_html_container( tmp_path: Path, ) -> None: article = tmp_path / "Paper.md" article.write_text( "