Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: add vault primitives and o2b index command (#4)

Sol Aitkend534419374e5
diff --git a/src/open_second_brain/cli.py b/src/open_second_brain/cli.py
index 6a72f6aa..cc662da8 100644
--- a/src/open_second_brain/cli.py
+++ b/src/open_second_brain/cli.py
@@ -10,6 +10,7 @@ from open_second_brain.config import default_config_path, discover_config, redac
from open_second_brain.doctor import doctor
from open_second_brain.event_log import append_event
from open_second_brain.init import bootstrap_vault
+from open_second_brain.vault import list_vault_pages, write_frontmatter
def build_parser() -> argparse.ArgumentParser:
@@ -40,6 +41,9 @@ def build_parser() -> argparse.ArgumentParser:
export.add_argument("--config", type=Path, default=None, help="Config file path")
export.add_argument("--output", type=Path, required=True, help="Output JSON file")
+ index_cmd = subcommands.add_parser("index", help="Regenerate the vault index from discovered pages")
+ index_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
+
return parser
@@ -118,6 +122,40 @@ def command_export_config(args: argparse.Namespace) -> int:
return 0
+def command_index(args: argparse.Namespace) -> int:
+ vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))
+ try:
+ pages = list_vault_pages(vault)
+ except OSError as exc:
+ print(f"error: failed to list vault pages: {exc}", file=sys.stderr)
+ return 1
+
+ if not pages:
+ print(f"no markdown pages found in vault: {vault}")
+ return 0
+
+ lines: list[str] = [
+ f"# Vault Index",
+ "",
+ f"Auto-generated index of {len(pages)} pages.",
+ "",
+ ]
+ for title, path, _ in pages:
+ rel = path.relative_to(vault)
+ lines.append(f"- [[{title}]] `{rel}`")
+
+ index_path = vault / "AI Wiki" / "index.md"
+ try:
+ index_path.parent.mkdir(parents=True, exist_ok=True)
+ write_frontmatter(index_path, {"title": "Index", "type": "index"}, "\n".join(lines))
+ except OSError as exc:
+ print(f"error: failed to write index: {exc}", file=sys.stderr)
+ return 1
+
+ print(f"index regenerated: {index_path} ({len(pages)} pages)")
+ return 0
+
+
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
@@ -131,6 +169,8 @@ def main(argv: list[str] | None = None) -> int:
return command_append_event(args)
if args.command == "export-config":
return command_export_config(args)
+ if args.command == "index":
+ return command_index(args)
raise AssertionError(f"unhandled command: {args.command}")
diff --git a/src/open_second_brain/vault.py b/src/open_second_brain/vault.py
new file mode 100644
index 00000000..2b82faca
--- /dev/null
+++ b/src/open_second_brain/vault.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import Any
+
+# ── Frontmatter parsing ───────────────────────────────────────────────────────
+
+_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?", re.DOTALL)
+_KEY_VALUE_RE = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$")
+
+
+def parse_frontmatter(path: Path) -> tuple[dict[str, Any], str]:
+ """Return (metadata dict, body text) from a Markdown file with YAML-like frontmatter.
+
+ Handles the standard Obsidian format:
+ ---
+ key: value
+ ---
+ body text
+
+ Only simple key: value lines are supported (no nested YAML, no lists).
+ Returns (metadata dict, body text) from a Markdown file with YAML-like frontmatter.
+ """
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return {}, ""
+
+ match = _FRONTMATTER_RE.match(text)
+ if not match:
+ return {}, text.strip()
+
+ fm_block = match.group(1)
+ body = text[match.end():].strip()
+ metadata: dict[str, Any] = {}
+
+ for line in fm_block.splitlines():
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ kv = _KEY_VALUE_RE.match(line)
+ if kv:
+ key = kv.group(1)
+ value = kv.group(2)
+ metadata[key] = value.strip("'\"")
+
+ return metadata, body
+
+
+def write_frontmatter(path: Path, metadata: dict[str, Any], body: str) -> None:
+ """Write a Markdown file with YAML-like frontmatter and body text."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lines = ["---"]
+ for key, value in metadata.items():
+ lines.append(f"{key}: {value}")
+ lines.append("---")
+ if body:
+ lines.append("")
+ lines.append(body)
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+# ── Wikilink extraction ───────────────────────────────────────────────────────
+
+_WIKILINK_RE = re.compile(r"\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]")
+_MEDIA_EXTENSIONS = frozenset({
+ ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff", ".avif",
+ ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi",
+ ".mp3", ".wav", ".ogg", ".flac", ".m4a",
+ ".pdf",
+})
+
+
+def extract_wikilinks(content: str) -> list[str]:
+ """Return unique [[target]] titles from content, excluding media file targets.
+
+ Also skips targets inside fenced code blocks and inline code spans.
+ """
+ # Mask code blocks to avoid false positives inside code samples
+ code_blocks_re = re.compile(r"```[\s\S]*?```|`[^`]+`")
+ masked = code_blocks_re.sub(" ", content)
+ raw = _WIKILINK_RE.findall(masked)
+ seen: set[str] = set()
+ result: list[str] = []
+ for target in raw:
+ if any(target.lower().endswith(ext) for ext in _MEDIA_EXTENSIONS):
+ continue
+ if target not in seen:
+ seen.add(target)
+ result.append(target)
+ return result
+
+
+# ── Vault page listing ────────────────────────────────────────────────────────
+
+def list_vault_pages(
+ vault_dir: Path,
+ *,
+ skip_dirs: tuple[str, ...] = (".git", ".obsidian", ".trash", ".stversions"),
+ skip_files: tuple[str, ...] = ("index.md", "log.md"),
+) -> list[tuple[str, Path, dict[str, Any]]]:
+ """Walk a vault directory and return all Markdown pages with their metadata.
+
+ Returns list of (title, path, metadata) sorted by title (case-insensitive).
+ Title is resolved from frontmatter 'title' key, else filename stem.
+ """
+ pages: list[tuple[str, Path, dict[str, Any]]] = []
+
+ for md_path in sorted(vault_dir.rglob("*.md")):
+ # Skip excluded directories
+ parts = set(str(p) for p in md_path.relative_to(vault_dir).parts)
+ if parts & set(skip_dirs):
+ continue
+ # Skip excluded files (check filename only, case-insensitive)
+ if md_path.name.lower() in skip_files:
+ continue
+ try:
+ meta, body = parse_frontmatter(md_path)
+ except Exception:
+ continue
+ title = meta.get("title", md_path.stem)
+ pages.append((title, md_path, meta))
+
+ pages.sort(key=lambda t: t[0].lower())
+ return pages
diff --git a/tests/test_cli.py b/tests/test_cli.py
index f39be85c..0c6fa27c 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -156,6 +156,22 @@ class CliTests(unittest.TestCase):
daily = Path(tmp) / "Daily" / "2026.05.06.md"
self.assertIn("- 10:30 β€” @compat-agent β€” compat entry", daily.read_text(encoding="utf-8"))
+ def test_index_generates_wikilink_index(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp)
+ (vault / "AI Wiki").mkdir(parents=True)
+ (vault / "Concept.md").write_text(
+ "---\ntitle: Concept\n---\n\nBody.", encoding="utf-8"
+ )
+ (vault / "Other.md").write_text("No frontmatter.", encoding="utf-8")
+ result = run_cli("index", "--vault", str(vault))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ index_path = vault / "AI Wiki" / "index.md"
+ self.assertTrue(index_path.is_file())
+ content = index_path.read_text(encoding="utf-8")
+ self.assertIn("[[Concept]]", content)
+ self.assertIn("[[Other]]", content)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_vault.py b/tests/test_vault.py
new file mode 100644
index 00000000..c3c1dace
--- /dev/null
+++ b/tests/test_vault.py
@@ -0,0 +1,98 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from open_second_brain.vault import (
+ extract_wikilinks,
+ list_vault_pages,
+ parse_frontmatter,
+ write_frontmatter,
+)
+
+
+class VaultTests(unittest.TestCase):
+ def test_parse_frontmatter_extracts_fields(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ path.write_text(
+ "---\ntitle: Hello World\ntags: test, example\n---\n\nBody text.\n",
+ encoding="utf-8",
+ )
+ meta, body = parse_frontmatter(path)
+ self.assertEqual(meta["title"], "Hello World")
+ self.assertEqual(meta["tags"], "test, example")
+ self.assertEqual(body, "Body text.")
+
+ def test_parse_frontmatter_no_frontmatter(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ path.write_text("Just a note.", encoding="utf-8")
+ meta, body = parse_frontmatter(path)
+ self.assertEqual(meta, {})
+ self.assertEqual(body, "Just a note.")
+
+ def test_parse_frontmatter_missing_file(self):
+ meta, body = parse_frontmatter(Path("/nonexistent/file.md"))
+ self.assertEqual(meta, {})
+ self.assertEqual(body, "")
+
+ def test_write_frontmatter_roundtrip(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ write_frontmatter(path, {"title": "Roundtrip"}, "The body.")
+ meta, body = parse_frontmatter(path)
+ self.assertEqual(meta["title"], "Roundtrip")
+ self.assertEqual(body, "The body.")
+
+ def test_extract_wikilinks_simple(self):
+ content = "See [[Target]] and [[Other]] for details."
+ links = extract_wikilinks(content)
+ self.assertEqual(links, ["Target", "Other"])
+
+ def test_extract_wikilinks_ignores_media(self):
+ content = "Look at ![[photo.png]] and [[concept]]."
+ links = extract_wikilinks(content)
+ self.assertEqual(links, ["concept"])
+
+ def test_extract_wikilinks_ignores_code_blocks(self):
+ content = "```\n[[not-a-link]]\n```\nReal: [[real-link]]"
+ links = extract_wikilinks(content)
+ self.assertEqual(links, ["real-link"])
+
+ def test_extract_wikilinks_deduplicates(self):
+ content = "[[A]] [[A]] [[B]]"
+ links = extract_wikilinks(content)
+ self.assertEqual(links, ["A", "B"])
+
+ def test_list_vault_pages_discovers_markdown(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp)
+ (vault / "page1.md").write_text("---\ntitle: Alpha\n---\n\nContent.", encoding="utf-8")
+ (vault / "page2.md").write_text("Beta content without frontmatter.", encoding="utf-8")
+ pages = list_vault_pages(vault)
+ self.assertEqual(len(pages), 2)
+ titles = [t for t, _, _ in pages]
+ self.assertIn("Alpha", titles)
+ self.assertIn("page2", titles) # stem, no frontmatter title
+
+ def test_list_vault_pages_skips_excluded_dirs(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp)
+ (vault / "page.md").write_text("Content.", encoding="utf-8")
+ (vault / ".obsidian").mkdir()
+ (vault / ".obsidian" / "hidden.md").write_text("Hidden.", encoding="utf-8")
+ pages = list_vault_pages(vault)
+ self.assertEqual(len(pages), 1)
+
+ def test_list_vault_pages_skips_excluded_files(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp)
+ (vault / "page.md").write_text("Content.", encoding="utf-8")
+ (vault / "index.md").write_text("Index.", encoding="utf-8")
+ pages = list_vault_pages(vault)
+ self.assertEqual(len(pages), 1)
+ self.assertEqual(pages[0][0], "page")
+
+
+if __name__ == "__main__":
+ unittest.main()