Skip to content

gerodp/hermes-productivity-skills / notes/obsidian-notes

obsidian-notes

Verified

Read and write notes in an Obsidian vault — list notes (all or modified in a window), show a note, and save the current chat as a note.

FileKindSize
SKILL.mdskill md11.4 KB
scripts/obsidian_notes.pyscript24.3 KB
scripts/test_obsidian_notes.pyscript11.7 KB

scripts/test_obsidian_notes.py

View on GitHub
#!/usr/bin/env python3
"""Offline unit tests for obsidian_notes — no network.

Filesystem is exercised against a temporary vault (created/removed per test),
so these stay hermetic and fast.

Run:  python3 test_obsidian_notes.py
"""
import io
import json
import os
import tempfile
import time
import unittest
from contextlib import redirect_stderr, redirect_stdout
from datetime import date
from unittest import mock

import obsidian_notes as ob


def _write(path, text):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as fh:
        fh.write(text)


class TempVault:
    """Context manager that builds a small vault and yields its path."""
    def __enter__(self):
        self.dir = tempfile.mkdtemp(prefix="vault-")
        _write(os.path.join(self.dir, "Daily", "2026-06-24.md"),
               "---\ntitle: Wednesday\ntags: [daily, work]\n---\n\nDid things.\n")
        _write(os.path.join(self.dir, "Ideas.md"), "# Ideas\n\nA loose idea.\n")
        # An internal Obsidian folder that must be ignored by the scan.
        _write(os.path.join(self.dir, ".obsidian", "workspace.json"), "{}")
        _write(os.path.join(self.dir, ".trash", "Old.md"), "trashed\n")
        return self.dir

    def __exit__(self, *exc):
        import shutil
        shutil.rmtree(self.dir, ignore_errors=True)


class TestScan(unittest.TestCase):
    def test_finds_md_skips_internal(self):
        with TempVault() as v:
            rels = {n["rel"] for n in ob.scan_notes(v)}
            self.assertEqual(rels, {os.path.join("Daily", "2026-06-24.md"),
                                    "Ideas.md"})

    def test_note_fields(self):
        with TempVault() as v:
            ideas = next(n for n in ob.scan_notes(v) if n["name"] == "Ideas")
            self.assertEqual(ideas["name"], "Ideas")
            self.assertTrue(ideas["size"] > 0)
            self.assertRegex(ideas["modified"], r"\d{4}-\d{2}-\d{2}")

    def test_sort_by_name(self):
        with TempVault() as v:
            rels = [n["rel"] for n in ob.sort_notes(ob.scan_notes(v), "name")]
            self.assertEqual(rels[0], os.path.join("Daily", "2026-06-24.md"))


class TestWindows(unittest.TestCase):
    TODAY = date(2026, 6, 24)  # Wednesday

    def test_this_week_capped(self):
        s, e = ob.compute_range(self.TODAY, period="this-week")
        self.assertEqual((s, e), (date(2026, 6, 22), date(2026, 6, 24)))

    def test_last_week(self):
        s, e = ob.compute_range(self.TODAY, period="last-week")
        self.assertEqual((s, e), (date(2026, 6, 15), date(2026, 6, 21)))

    def test_days(self):
        s, e = ob.compute_range(self.TODAY, days=3)
        self.assertEqual((s, e), (date(2026, 6, 22), date(2026, 6, 24)))

    def test_explicit(self):
        s, e = ob.compute_range(self.TODAY, start="2026-01-01", end="2026-01-31")
        self.assertEqual((s, e), (date(2026, 1, 1), date(2026, 1, 31)))

    def test_half_open_dates(self):
        with self.assertRaises(ob.ObsidianError):
            ob.compute_range(self.TODAY, start="2026-01-01")

    def test_bad_days(self):
        with self.assertRaises(ob.ObsidianError):
            ob.compute_range(self.TODAY, days=0)


class TestWindowFilter(unittest.TestCase):
    def test_filter_by_modified(self):
        now = time.time()
        old = now - 40 * 86400
        notes = [
            {"rel": "new.md", "mtime": now, "btime": now},
            {"rel": "old.md", "mtime": old, "btime": old},
        ]
        today = date.today()
        s, e = ob.compute_range(today, days=7)
        kept = ob.filter_by_window(notes, s, e, which="modified")
        self.assertEqual([n["rel"] for n in kept], ["new.md"])


class TestFrontmatter(unittest.TestCase):
    def test_inline_tags(self):
        meta, body = ob.split_frontmatter(
            "---\ntitle: T\ntags: [a, b]\n---\n\nBody here\n")
        self.assertEqual(meta["title"], "T")
        self.assertEqual(meta["tags"], ["a", "b"])
        self.assertEqual(body.strip(), "Body here")

    def test_block_list_tags(self):
        meta, _ = ob.split_frontmatter(
            "---\ntags:\n  - x\n  - y\n---\nbody\n")
        self.assertEqual(meta["tags"], ["x", "y"])

    def test_no_frontmatter(self):
        meta, body = ob.split_frontmatter("# Just a heading\n")
        self.assertEqual(meta, {})
        self.assertEqual(body, "# Just a heading\n")

    def test_unterminated_block_is_safe(self):
        meta, body = ob.split_frontmatter("---\ntitle: T\nno end here\n")
        self.assertEqual(meta, {})


class TestFilenames(unittest.TestCase):
    def test_keeps_spaces_strips_illegal(self):
        self.assertEqual(ob.safe_filename("My: Chat/Log?"), "My Chat Log.md")

    def test_empty_becomes_note(self):
        self.assertEqual(ob.safe_filename("///"), "note.md")

    def test_truncates_long(self):
        self.assertTrue(len(ob.safe_filename("x" * 300)) <= 124)


class TestBuildNote(unittest.TestCase):
    def test_frontmatter_and_body(self):
        out = ob.build_note("Hello\n", title="My Note", created="2026-06-24",
                            tags=["chat", "a:b"], source="hermes")
        self.assertIn("title: My Note", out)
        self.assertIn("created: 2026-06-24", out)
        self.assertIn('"a:b"', out)          # colon forces quoting
        self.assertIn("source: hermes", out)
        self.assertTrue(out.rstrip().endswith("Hello"))

    def test_title_with_colon_quoted(self):
        out = ob.build_note("x", title="A: B")
        self.assertIn('title: "A: B"', out)


class TestSaveResolve(unittest.TestCase):
    def test_traversal_blocked(self):
        with TempVault() as v:
            with self.assertRaises(ob.ObsidianError):
                ob.resolve_save_path(v, "../../etc", "passwd.md")

    def test_subfolder_ok(self):
        with TempVault() as v:
            p = ob.resolve_save_path(v, "Chats", "Hi.md")
            self.assertTrue(p.startswith(os.path.realpath(v)))
            self.assertTrue(p.endswith(os.path.join("Chats", "Hi.md")))


class TestSaveAndShow(unittest.TestCase):
    def test_save_creates_note(self):
        with TempVault() as v:
            path, action, n = ob.save_note(
                v, "Chat transcript body", title="Session 1",
                folder="Chats", tags=["chat"], created="2026-06-24")
            self.assertEqual(action, "created")
            self.assertTrue(n > 0)
            text = ob.read_note(path)
            self.assertIn("title: Session 1", text)
            self.assertIn("Chat transcript body", text)

    def test_save_refuses_overwrite_by_default(self):
        with TempVault() as v:
            ob.save_note(v, "a", title="Dup", created="2026-06-24")
            with self.assertRaises(ob.ObsidianError):
                ob.save_note(v, "b", title="Dup", created="2026-06-24")

    def test_save_append(self):
        with TempVault() as v:
            ob.save_note(v, "first", title="Log", created="2026-06-24")
            path, action, _ = ob.save_note(
                v, "second", title="Log", created="2026-06-25", append=True)
            self.assertEqual(action, "appended")
            text = ob.read_note(path)
            self.assertIn("first", text)
            self.assertIn("second", text)
            self.assertIn("Added 2026-06-25", text)

    def test_save_empty_rejected(self):
        with TempVault() as v:
            with self.assertRaises(ob.ObsidianError):
                ob.save_note(v, "   ", title="Empty")

    def test_resolve_note_by_name(self):
        with TempVault() as v:
            p = ob.resolve_note(v, "Ideas")
            self.assertTrue(p.endswith("Ideas.md"))

    def test_resolve_note_by_relpath(self):
        with TempVault() as v:
            p = ob.resolve_note(v, os.path.join("Daily", "2026-06-24.md"))
            self.assertTrue(p.endswith("2026-06-24.md"))

    def test_resolve_note_missing(self):
        with TempVault() as v:
            with self.assertRaises(ob.ObsidianError):
                ob.resolve_note(v, "Nope")


class TestRender(unittest.TestCase):
    def test_render_list_smoke(self):
        notes = [{"rel": "A.md", "modified": "2026-06-24",
                  "created": "2026-06-01", "size": 1200}]
        out = ob.render_list(notes)
        self.assertIn("All notes", out)
        self.assertIn("A.md", out)
        self.assertIn("1 note(s)", out)

    def test_render_list_empty(self):
        self.assertIn("no notes match", ob.render_list([]))

    def test_fmt_size(self):
        self.assertEqual(ob.fmt_size(512), "512B")
        self.assertEqual(ob.fmt_size(2048), "2K")


class TestCheckSmoke(unittest.TestCase):
    """Smoke-test the documented `check` subcommand contract, hermetically.

    `check` for obsidian-notes has NO --json flag (it only prints a text summary
    and returns 0), so we exercise the text path only. Unconfigured must degrade
    gracefully to a non-zero int (never a raised traceback).
    """

    def test_unconfigured_returns_one_gracefully(self):
        # No OBSIDIAN_VAULT in the environment and no --vault → must return 1,
        # not raise. Clear the env so we never read the developer's config.
        with mock.patch.dict(os.environ, {}, clear=True):
            out, err = io.StringIO(), io.StringIO()
            with redirect_stdout(out), redirect_stderr(err):
                rc = ob.main(["check"])
        self.assertIsInstance(rc, int)
        self.assertEqual(rc, 1)
        # A user-facing error on stderr, and no leaked Python traceback.
        self.assertIn("error:", err.getvalue())
        combined = out.getvalue() + err.getvalue()
        self.assertNotIn("Traceback (most recent call last)", combined)

    def test_configured_vault_returns_zero(self):
        # A real (temp) vault with notes → check loads it and returns 0.
        with TempVault() as v:
            with mock.patch.dict(os.environ, {}, clear=True):
                out, err = io.StringIO(), io.StringIO()
                with redirect_stdout(out), redirect_stderr(err):
                    rc = ob.main(["check", "--vault", v])
        self.assertEqual(rc, 0)
        text = out.getvalue()
        self.assertIn("OK", text)
        self.assertIn(v, text)
        self.assertNotIn("Traceback (most recent call last)", text + err.getvalue())

    def test_env_vault_returns_zero(self):
        # The documented OBSIDIAN_VAULT env var path also resolves and returns 0.
        with TempVault() as v:
            with mock.patch.dict(os.environ, {ob.ENV_VAULT: v}, clear=True):
                out, err = io.StringIO(), io.StringIO()
                with redirect_stdout(out), redirect_stderr(err):
                    rc = ob.main(["check"])
        self.assertEqual(rc, 0)
        self.assertIn("OK", out.getvalue())


class TestSecurity(unittest.TestCase):
    def test_bare_name_symlink_outside_vault_rejected(self):
        # A synced vault can carry a symlink pointing at e.g. a key file —
        # bare-name resolution must apply the same containment check as paths.
        with TempVault() as v:
            fd, outside = tempfile.mkstemp(suffix=".md")
            os.close(fd)
            _write(outside, "SECRET")
            try:
                os.symlink(outside, os.path.join(v, "sneaky.md"))
                with self.assertRaises(ob.ObsidianError):
                    ob.resolve_note(v, "sneaky")
            finally:
                os.unlink(outside)

    def test_symlink_inside_vault_still_resolves(self):
        with TempVault() as v:
            os.symlink(os.path.join(v, "Ideas.md"), os.path.join(v, "Alias.md"))
            self.assertEqual(ob.resolve_note(v, "Alias"),
                             os.path.realpath(os.path.join(v, "Ideas.md")))

    def test_sanitize_text_strips_terminal_escapes(self):
        self.assertEqual(ob.sanitize_text("a\x1b[2Jb\nkeep\ttab"),
                         "a[2Jb\nkeep\ttab")


if __name__ == "__main__":
    unittest.main(verbosity=2)
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall