Skip to content

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.

fix(knowledge): resolve title-case infra files and article-root-prefixed wiki links

Lum1104e3bc337d92ef
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 968f417d..c3105ab7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -58,4 +58,4 @@ jobs:
run: pnpm test
- name: Test Python skill helpers
- run: python -m unittest tests.skill.understand.test_merge_batch_graphs tests.skill.understand.test_merge_subdomain_graphs -v
+ run: python -m unittest tests.skill.understand.test_merge_batch_graphs tests.skill.understand.test_merge_subdomain_graphs tests.skill.knowledge.test_parse_knowledge_base -v
diff --git a/tests/skill/knowledge/test_parse_knowledge_base.py b/tests/skill/knowledge/test_parse_knowledge_base.py
new file mode 100644
index 00000000..2628978f
--- /dev/null
+++ b/tests/skill/knowledge/test_parse_knowledge_base.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""
+test_parse_knowledge_base.py — Tests for title-case infra file detection and
+article-root-prefixed wiki links in the Karpathy wiki parser (issue #342).
+
+Run from the repo root:
+ python -m unittest tests.skill.knowledge.test_parse_knowledge_base -v
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import shutil
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from typing import Any
+
+
+# ── Module loaders ────────────────────────────────────────────────────────
+# The scripts have hyphens in their names, so we cannot `import` them
+# directly. Load them via importlib so we can call module-level helpers.
+
+_HERE = Path(__file__).resolve().parent
+_REPO_ROOT = _HERE.parent.parent.parent
+_SKILL_DIR = _REPO_ROOT / "understand-anything-plugin" / "skills" / "understand-knowledge"
+
+
+def _load(script: str, alias: str) -> Any:
+ spec = importlib.util.spec_from_file_location(alias, _SKILL_DIR / script)
+ if spec is None or spec.loader is None:
+ raise RuntimeError(f"Could not load {script}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[alias] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+pkb = _load("parse-knowledge-base.py", "parse_knowledge_base")
+mkg = _load("merge-knowledge-graph.py", "merge_knowledge_graph")
+
+
+def _fs_is_case_sensitive(tmp: Path) -> bool:
+ probe = tmp / "CaseProbe.md"
+ probe.write_text("x", encoding="utf-8")
+ try:
+ return not (tmp / "caseprobe.md").is_file()
+ finally:
+ probe.unlink()
+
+
+class TestFindMarkdownCaseInsensitive(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = Path(tempfile.mkdtemp(prefix="ua-pkb-"))
+
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_title_case_file_is_found(self) -> None:
+ (self.tmp / "Index.md").write_text("# Wiki", encoding="utf-8")
+ found = pkb.find_markdown_case_insensitive(self.tmp, "index.md")
+ self.assertTrue(found.is_file())
+ self.assertEqual(found.name.lower(), "index.md")
+
+ def test_exact_lowercase_wins_when_both_exist(self) -> None:
+ if not _fs_is_case_sensitive(self.tmp):
+ self.skipTest("filesystem is case-insensitive; both casings collide")
+ (self.tmp / "Index.md").write_text("# Title", encoding="utf-8")
+ (self.tmp / "index.md").write_text("# lower", encoding="utf-8")
+ found = pkb.find_markdown_case_insensitive(self.tmp, "index.md")
+ self.assertEqual(found.name, "index.md")
+
+ def test_missing_parent_returns_candidate(self) -> None:
+ found = pkb.find_markdown_case_insensitive(self.tmp / "nope", "index.md")
+ self.assertFalse(found.is_file())
+
+ def test_merge_script_helper_matches(self) -> None:
+ (self.tmp / "Index.md").write_text("# Wiki", encoding="utf-8")
+ found = mkg._find_markdown_case_insensitive(self.tmp, "index.md")
+ self.assertTrue(found.is_file())
+
+
+class TestTitleCaseWiki(unittest.TestCase):
+ """A wiki using Index.md / Log.md must parse the same as index.md / log.md."""
+
+ def setUp(self) -> None:
+ self.tmp = Path(tempfile.mkdtemp(prefix="ua-pkb-wiki-"))
+ wiki = self.tmp / "wiki"
+ (wiki / "concepts").mkdir(parents=True)
+ (wiki / "projects").mkdir(parents=True)
+ (wiki / "Index.md").write_text(
+ "# Hermes\n\n## Concepts\n\n- [[wiki/concepts/Index]]\n\n"
+ "## Projects\n\n- [[wiki/projects/Personal Wiki Second Brain]]\n",
+ encoding="utf-8",
+ )
+ (wiki / "Log.md").write_text(
+ "# Log\n\n## [2026-05-01] CREATE | Seeded wiki\n", encoding="utf-8"
+ )
+ (wiki / "concepts" / "Index.md").write_text(
+ "# Concepts Index\n\nOverview of concepts.\n", encoding="utf-8"
+ )
+ (wiki / "projects" / "Personal Wiki Second Brain.md").write_text(
+ "# Personal Wiki Second Brain\n\nPilot project.\n", encoding="utf-8"
+ )
+
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_detect_format_sees_title_case_infra(self) -> None:
+ signals = pkb.detect_format(self.tmp)
+ self.assertTrue(signals["has_index"])
+ self.assertTrue(signals["has_log"])
+ self.assertTrue(signals["detected"])
+
+ def test_title_case_root_infra_is_not_an_article(self) -> None:
+ manifest = pkb.parse_wiki(self.tmp)
+ article_ids = {n["id"] for n in manifest["nodes"] if n["type"] == "article"}
+ self.assertNotIn("article:Index", article_ids)
+ self.assertNotIn("article:Log", article_ids)
+ # Nested Index.md IS content
+ self.assertIn("article:concepts/Index", article_ids)
+
+ def test_root_prefixed_category_links_resolve(self) -> None:
+ """[[wiki/concepts/Index]] must map to article:concepts/Index when
+ wiki/ is the detected article root (the #342 pilot saw every node
+ land in "Other" because this lookup missed)."""
+ manifest = pkb.parse_wiki(self.tmp)
+ cat_edges = {
+ (e["source"], e["target"])
+ for e in manifest["edges"]
+ if e["type"] == "categorized_under"
+ }
+ self.assertIn(("article:concepts/Index", "topic:concepts"), cat_edges)
+ self.assertIn(
+ ("article:projects/Personal Wiki Second Brain", "topic:projects"),
+ cat_edges,
+ )
+ by_id = {n["id"]: n for n in manifest["nodes"]}
+ self.assertEqual(
+ by_id["article:concepts/Index"]["knowledgeMeta"].get("category"),
+ "Concepts",
+ )
+
+ def test_links_outside_article_root_stay_unresolved(self) -> None:
+ """maps/*, SCHEMA etc. must not be forced into article layers."""
+ wiki = self.tmp / "wiki"
+ (wiki / "concepts" / "Index.md").write_text(
+ "# Concepts Index\n\nSee [[maps/overview]] and [[SCHEMA]].\n",
+ encoding="utf-8",
+ )
+ manifest = pkb.parse_wiki(self.tmp)
+ related = {
+ e["target"] for e in manifest["edges"] if e["source"] == "article:concepts/Index"
+ }
+ self.assertNotIn("article:maps/overview", related)
+ self.assertTrue(any("maps/overview" in w for w in manifest["warnings"]))
+
+
+class TestLowercaseWikiStillWorks(unittest.TestCase):
+ """Regression guard: the original all-lowercase layout keeps parsing."""
+
+ def setUp(self) -> None:
+ self.tmp = Path(tempfile.mkdtemp(prefix="ua-pkb-lower-"))
+ (self.tmp / "concepts").mkdir(parents=True)
+ (self.tmp / "index.md").write_text(
+ "# Wiki\n\n## Concepts\n\n- [[concepts/attention]]\n", encoding="utf-8"
+ )
+ (self.tmp / "log.md").write_text("# Log\n", encoding="utf-8")
+ (self.tmp / "concepts" / "attention.md").write_text(
+ "# Attention\n\nAll you need.\n", encoding="utf-8"
+ )
+ (self.tmp / "concepts" / "transformer.md").write_text(
+ "# Transformer\n\nSee [[attention]].\n", encoding="utf-8"
+ )
+
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_lowercase_layout_parses_with_categories_and_edges(self) -> None:
+ signals = pkb.detect_format(self.tmp)
+ self.assertTrue(signals["detected"])
+ manifest = pkb.parse_wiki(self.tmp)
+ by_id = {n["id"]: n for n in manifest["nodes"]}
+ self.assertIn("article:concepts/attention", by_id)
+ self.assertEqual(
+ by_id["article:concepts/attention"]["knowledgeMeta"].get("category"),
+ "Concepts",
+ )
+ edge_keys = {(e["source"], e["target"], e["type"]) for e in manifest["edges"]}
+ self.assertIn(
+ ("article:concepts/transformer", "article:concepts/attention", "related"),
+ edge_keys,
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/understand-anything-plugin/skills/understand-knowledge/merge-knowledge-graph.py b/understand-anything-plugin/skills/understand-knowledge/merge-knowledge-graph.py
index 1ef224e3..73805055 100644
--- a/understand-anything-plugin/skills/understand-knowledge/merge-knowledge-graph.py
+++ b/understand-anything-plugin/skills/understand-knowledge/merge-knowledge-graph.py
@@ -22,6 +22,26 @@ import sys
from datetime import datetime, timezone
from pathlib import Path
+
+def _find_markdown_case_insensitive(parent: Path, name: str) -> Path:
+ """Resolve a known markdown filename case-insensitively within one directory.
+
+ Mirrors find_markdown_case_insensitive in parse-knowledge-base.py (the
+ scripts are standalone, so the helper is duplicated): an exact match
+ always wins; otherwise the first case-insensitive sibling is returned.
+ """
+ candidate = parent / name
+ if candidate.is_file():
+ return candidate
+ if not parent.is_dir():
+ return candidate
+ wanted = name.lower()
+ for child in sorted(parent.iterdir()):
+ if child.is_file() and child.name.lower() == wanted:
+ return child
+ return candidate
+
+
# ---------------------------------------------------------------------------
# Canonical type sets (must match core/src/types.ts)
# ---------------------------------------------------------------------------
@@ -321,10 +341,11 @@ def merge(root: Path) -> dict:
# --- Detect project name ---
project_name = root.name
- # Try to find a better name from index.md H1
- index_path = root / "wiki" / "index.md"
+ # Try to find a better name from index.md H1 (case-insensitively —
+ # Index.md is a reasonable convention; exact lowercase wins if both exist)
+ index_path = _find_markdown_case_insensitive(root / "wiki", "index.md")
if not index_path.is_file():
- index_path = root / "index.md"
+ index_path = _find_markdown_case_insensitive(root, "index.md")
if index_path.is_file():
text = index_path.read_text(encoding="utf-8", errors="replace")
h1_match = re.search(r"^#\s+(.+)$", text, re.MULTILINE)
diff --git a/understand-anything-plugin/skills/understand-knowledge/parse-knowledge-base.py b/understand-anything-plugin/skills/understand-knowledge/parse-knowledge-base.py
index d6070512..c4161851 100644
--- a/understand-anything-plugin/skills/understand-knowledge/parse-knowledge-base.py
+++ b/understand-anything-plugin/skills/understand-knowledge/parse-knowledge-base.py
@@ -31,6 +31,27 @@ INDEX_SECTION_RE = re.compile(r"^##\s+(.+)$", re.MULTILINE)
# Files that are part of wiki infrastructure, not content articles
INFRA_FILES = {"index.md", "log.md", "claude.md", "agents.md", "soul.md"}
+
+def find_markdown_case_insensitive(parent: Path, name: str) -> Path:
+ """Resolve a known markdown filename case-insensitively within one directory.
+
+ An exact match always wins (so `index.md` beats `Index.md` when both
+ exist); otherwise the first case-insensitive sibling is returned. The
+ unmatched candidate comes back as-is so callers can keep using
+ `.is_file()` checks. Deliberately single-directory — no recursive fuzzy
+ matching (see #342 non-goals).
+ """
+ candidate = parent / name
+ if candidate.is_file():
+ return candidate
+ if not parent.is_dir():
+ return candidate
+ wanted = name.lower()
+ for child in sorted(parent.iterdir()):
+ if child.is_file() and child.name.lower() == wanted:
+ return child
+ return candidate
+
# ---------------------------------------------------------------------------
# Detection: is this a Karpathy-pattern wiki?
# ---------------------------------------------------------------------------
@@ -38,8 +59,10 @@ INFRA_FILES = {"index.md", "log.md", "claude.md", "agents.md", "soul.md"}
def detect_format(root: Path) -> dict:
"""Detect if directory follows the Karpathy LLM wiki three-layer pattern."""
signals = {
- "has_index": (root / "index.md").is_file() or (root / "wiki" / "index.md").is_file(),
- "has_log": (root / "log.md").is_file() or (root / "wiki" / "log.md").is_file(),
+ "has_index": find_markdown_case_insensitive(root, "index.md").is_file()
+ or find_markdown_case_insensitive(root / "wiki", "index.md").is_file(),
+ "has_log": find_markdown_case_insensitive(root, "log.md").is_file()
+ or find_markdown_case_insensitive(root / "wiki", "log.md").is_file(),
"has_raw": (root / "raw").is_dir(),
"has_schema": any(
(root / f).is_file() or (root / "wiki" / f).is_file()
@@ -249,29 +272,43 @@ def build_name_to_stem_map(wiki_root: Path) -> dict[str, str]:
return name_map
-def resolve_wikilink(target: str, name_map: dict[str, str], node_ids: set[str] | None = None) -> str | None:
+def resolve_wikilink(
+ target: str,
+ name_map: dict[str, str],
+ node_ids: set[str] | None = None,
+ root_prefix: str | None = None,
+) -> str | None:
"""Resolve a wikilink target to an article node ID.
If node_ids is provided, only resolve to IDs that exist in the set.
+ root_prefix is the article-root directory name (e.g. "wiki") — links
+ written from the repository root include it ([[wiki/concepts/Index]])
+ while name_map keys are relative to the article root, so such targets
+ are tried both as written and with the prefix stripped.
"""
key = target.lower().strip()
# Skip targets that are clearly not page names (shell flags, etc.)
if key.startswith("-"):
return None
- stem = name_map.get(key)
- if stem:
- candidate = f"article:{stem}"
- # If we have a node set, verify the target exists
- if node_ids is not None and candidate not in node_ids:
- return None
- return candidate
- # Try without directory prefix
- for stored_key, stored_stem in name_map.items():
- if stored_key.endswith("/" + key) or stored_key == key:
- candidate = f"article:{stored_stem}"
+ keys = [key]
+ if root_prefix and key.startswith(root_prefix + "/"):
+ keys.append(key[len(root_prefix) + 1:])
+ for k in keys:
+ stem = name_map.get(k)
+ if stem:
+ candidate = f"article:{stem}"
+ # If we have a node set, verify the target exists
if node_ids is not None and candidate not in node_ids:
return None
return candidate
+ # Try without directory prefix
+ for k in keys:
+ for stored_key, stored_stem in name_map.items():
+ if stored_key.endswith("/" + k) or stored_key == k:
+ candidate = f"article:{stored_stem}"
+ if node_ids is not None and candidate not in node_ids:
+ return None
+ return candidate
return None
@@ -289,23 +326,32 @@ def parse_wiki(root: Path) -> dict:
# Build name resolution map
name_map = build_name_to_stem_map(wiki_root)
- # Find index.md and log.md
- index_path = wiki_root / "index.md"
+ # Find index.md and log.md (case-insensitively — Index.md/Log.md are a
+ # reasonable convention on case-sensitive filesystems)
+ index_path = find_markdown_case_insensitive(wiki_root, "index.md")
if not index_path.is_file():
- index_path = root / "index.md"
- log_path = wiki_root / "log.md"
+ index_path = find_markdown_case_insensitive(root, "index.md")
+ log_path = find_markdown_case_insensitive(wiki_root, "log.md")
if not log_path.is_file():
- log_path = root / "log.md"
+ log_path = find_markdown_case_insensitive(root, "log.md")
# Parse index for categories
categories = parse_index(index_path)
log_entries = parse_log(log_path)
+ # Article ids are relative to wiki_root, but a root index.md commonly
+ # links with the article-root prefix included ([[wiki/concepts/Index]]).
+ # Register/resolve such targets both as written and prefix-stripped.
+ root_prefix = wiki_root.name.lower() if wiki_root != root else None
+
# Build category lookup: wikilink target → category name
category_lookup: dict[str, str] = {}
for cat in categories:
for article_target in cat["articles"]:
- category_lookup[article_target.lower()] = cat["name"]
+ t = article_target.lower()
+ category_lookup[t] = cat["name"]
+ if root_prefix and t.startswith(root_prefix + "/"):
+ category_lookup[t[len(root_prefix) + 1:]] = cat["name"]
# --- Pre-compute article IDs (for edge resolution validation) ---
# Only skip infra files at the wiki root level, not in subdirectories
@@ -390,7 +436,7 @@ def parse_wiki(root: Path) -> dict:
# Build edges from wikilinks (resolve against known article IDs)
for wl in wikilinks:
- target_id = resolve_wikilink(wl["target"], name_map, article_ids)
+ target_id = resolve_wikilink(wl["target"], name_map, article_ids, root_prefix)
if target_id and target_id != node_id:
edges.append({
"source": node_id,
@@ -418,7 +464,7 @@ def parse_wiki(root: Path) -> dict:
# categorized_under edges (only resolve to known article nodes)
for article_target in cat["articles"]:
- article_id = resolve_wikilink(article_target, name_map, article_ids)
+ article_id = resolve_wikilink(article_target, name_map, article_ids, root_prefix)
if article_id:
edges.append({
"source": article_id,