Giving Cursor and Claude Code a Shared Long-Term Memory with Obsidian

By | November 24, 2026

AI coding assistants are great inside a single chat, but the moment you open a new session, they forget everything: your infrastructure quirks, past architectural decisions, and the exact fix you found three days ago.

If you use both Claude Code and Cursor, the problem doubles—each tool lives in its own silo.

The solution? Point both of them at one shared Obsidian vault as their long-term memory, wired up with a single always-on rule and four lightweight Python hooks.

The Architecture: One Vault, Two Editors

Instead of letting Cursor and Claude Code maintain separate memory silos, both read from and write to the same Meta/ folder inside an Obsidian vault (~/ObsidianVault), mediated by a shared CLI script (~/scripts/obsidian_memory.py).

Because Cursor doesn’t read ~/.claude/settings.json, it gets its own ~/.cursor/hooks.json registry and ~/.cursor/rules/obsidian-memory.mdc rule to mirror Claude Code’s behavior:

Lifecycle Event Cursor Hook What It Does
Always-on Rule obsidian-memory.mdc Teaches the agent how to search and record facts.
Session Start obsidian-session-start.py Injects active state, user profile, durable facts, and recent logs (up to 9,000 chars).
Before Prompt obsidian-prompt-context.py Searches the vault for notes matching your prompt and injects relevant context.
Stop (Turn End) obsidian-memory-nudge.py Nudges the agent to save durable facts after 30 tool calls with no memory write.
Session End obsidian-session-archive.py Archives the chat transcript (with secrets redacted) into Meta/cursor-sessions/.

Hook Registry (~/.cursor/hooks.json)

{
  "version": 1,
  "hooks": {
    "sessionStart": [
      {
        "command": "./hooks/obsidian-session-start.py",
        "timeout": 10
      }
    ],
    "beforeSubmitPrompt": [
      {
        "command": "./hooks/obsidian-prompt-context.py",
        "timeout": 5
      }
    ],
    "stop": [
      {
        "command": "./hooks/obsidian-memory-nudge.py",
        "timeout": 10,
        "loop_limit": 1
      }
    ],
    "sessionEnd": [
      {
        "command": "./hooks/obsidian-session-archive.py",
        "timeout": 60
      }
    ]
  }
}

1. Context Injection at Start and Per-Prompt

When a new Cursor chat starts, sessionStart runs obsidian_memory.py context and passes the output as additional_context. That packet gives the agent immediate situational awareness:

  • Active task (Meta/states/claude.md)
  • User preferences (Meta/user-profile.md)
  • Durable facts (Meta/claude-memory.md)
  • Recent changes (Meta/agent-log.md)

Then, before each prompt is submitted (beforeSubmitPrompt), obsidian-prompt-context.py runs obsidian_memory.py prompt-context (skipping trivial prompts under 12 characters). If your prompt mentions something like “database migration connection pool retry”, it pulls matching vault notes under a Matching memory heading—and caches the lookup per conversation_id.

Key rule: Injected memory is treated as notes from earlier sessions, not blind instructions. The agent is explicitly told to verify facts against the live code or host before acting on them.

~/.cursor/hooks/obsidian-session-start.py

#!/usr/bin/env python3
"""Cursor sessionStart: inject the Obsidian long-term memory Claude loads."""
import json
import os
import subprocess
import sys

SCRIPT = "~/scripts/obsidian_memory.py"


def load_hook():
    raw = sys.stdin.read()
    if not raw.strip():
        return {}
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return {}


def main():
    hook = load_hook()
    roots = hook.get("workspace_roots") or []
    cwd = roots[0] if roots else hook.get("cwd") or os.getcwd()
    payload = {
        "cwd": cwd,
        "session_id": hook.get("session_id") or hook.get("conversation_id") or "",
    }
    proc = subprocess.run(
        ["python3", SCRIPT, "context"],
        input=json.dumps(payload),
        text=True,
        capture_output=True,
    )
    text = (proc.stdout or "").strip()
    if not text:
        print("{}")
        return
    print(json.dumps({"additional_context": text}))


if __name__ == "__main__":
    main()

~/.cursor/hooks/obsidian-prompt-context.py

#!/usr/bin/env python3
"""Cursor beforeSubmitPrompt: inject vault notes that match this prompt."""
import json
import os
import subprocess
import sys

SCRIPT = "~/scripts/obsidian_memory.py"


def load_hook():
    raw = sys.stdin.read()
    if not raw.strip():
        return {}
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return {}


def main():
    hook = load_hook()
    prompt = hook.get("prompt") or ""
    if len(prompt.strip()) < 12:
        print("{}")
        return
    roots = hook.get("workspace_roots") or []
    cwd = roots[0] if roots else hook.get("cwd") or os.getcwd()
    payload = {
        "cwd": cwd,
        "session_id": hook.get("session_id") or hook.get("conversation_id") or "",
        "prompt": prompt,
    }
    proc = subprocess.run(
        ["python3", SCRIPT, "prompt-context"],
        input=json.dumps(payload),
        text=True,
        capture_output=True,
    )
    text = (proc.stdout or "").strip()
    if not text:
        print("{}")
        return
    print(json.dumps({"additional_context": text}))


if __name__ == "__main__":
    main()

2. Recording Facts Without Friction

Agents don’t need to manually edit Markdown files to remember things. The always-on rule gives them a simple CLI interface:

# Save one distilled fact
python3 ~/scripts/obsidian_memory.py add-note --section infra "<one fact>"

# Save a reusable procedure
python3 ~/scripts/obsidian_memory.py write-note "<title>" --folder Knowledge --tags a,b

# Log a significant change
python3 ~/scripts/obsidian_memory.py log "<what changed>"

# Update the active task
python3 ~/scripts/obsidian_memory.py set-state

And before re-investigating a solved problem, the agent searches first:

python3 ~/scripts/search_vault.py "<2 to 5 keywords>" --folder Meta

3. The 30-Tool-Call “Stop Nudge”

During long debugging sessions, agents often forget to write down what they learned. The stop hook (obsidian-memory-nudge.py) solves this by counting tool_use blocks in the session transcript.

If the agent makes 30 tool calls without running a memory write (add-note, log, set-state, write-note) or editing a file inside the vault, the hook injects a single followup_message asking the agent to decide if anything worth keeping was discovered.

With loop_limit: 1 (and a check on loop_count > 0), it nudges once and never loops.

~/.cursor/hooks/obsidian-memory-nudge.py

#!/usr/bin/env python3
"""Cursor stop hook: ask the agent to record durable facts after real work.

Silent unless at least THRESHOLD tool calls happened since the last write to the
Obsidian vault and since the last nudge. Then it sends one follow-up. A second
stop in the same turn (loop_count > 0) stays silent.

Disable: set CURSOR_MEMORY_NUDGE=0, or remove the stop hook from ~/.cursor/hooks.json.
"""
import json
import os
import sys
from pathlib import Path

THRESHOLD = int(os.environ.get("CURSOR_MEMORY_NUDGE_THRESHOLD", "30"))
VAULT = str(Path(os.environ.get("OBSIDIAN_VAULT", Path.home() / "ObsidianVault")))
STATE_DIR = Path.home() / ".cursor" / "memory-nudge"
PROJECTS = Path.home() / ".cursor" / "projects"
WRITE_CMDS = ("add-note", " log ", "set-state", "write-note", "archive-log", "mark-curated")
WRITE_TOOLS = {"Write", "StrReplace", "Edit", "MultiEdit"}

REASON = (
    "Memory check: you have done {n} tool calls since anything was written to the Obsidian memory. "
    "Decide whether this work produced a fact that should survive the session. "
    "If it did, record it with python3 ~/scripts/obsidian_memory.py: "
    "add-note --section <env|infra|principles|projects|log> for one fact; "
    "write-note for a procedure; log for a significant change; "
    "set-state if the active task changed. "
    "Do not store secrets, client personal data, or trivia. "
    "If nothing is worth keeping, say so in one short line and stop. "
    "Do not repeat the previous answer."
)


def find_transcript(sid: str) -> Path | None:
    if not sid:
        return None
    matches = list(PROJECTS.glob(f"*/agent-transcripts/{sid}/{sid}.jsonl"))
    return matches[0] if matches else None


def is_memory_write(block: dict) -> bool:
    name = block.get("name") or ""
    inp = block.get("input") or {}
    if name in ("Shell", "Bash"):
        cmd = " " + (inp.get("command") or "") + " "
        return "obsidian_memory.py" in cmd and any(w in cmd for w in WRITE_CMDS)
    if name in WRITE_TOOLS:
        path = inp.get("path") or inp.get("file_path") or ""
        return path.startswith(VAULT)
    return False


def count_tools(path: Path) -> tuple[int, int]:
    total, last_write = 0, 0
    with path.open(encoding="utf-8", errors="replace") as fh:
        for line in fh:
            if '"tool_use"' not in line:
                continue
            try:
                obj = json.loads(line)
            except json.JSONDecodeError:
                continue
            if obj.get("role") != "assistant":
                continue
            for block in (obj.get("message") or {}).get("content") or []:
                if isinstance(block, dict) and block.get("type") == "tool_use":
                    total += 1
                    if is_memory_write(block):
                        last_write = total
    return total, last_write


def main():
    if os.environ.get("CURSOR_MEMORY_NUDGE", "1") == "0":
        print("{}")
        return
    hook = json.load(sys.stdin)
    if int(hook.get("loop_count") or 0) > 0:
        print("{}")
        return
    sid = hook.get("session_id") or hook.get("conversation_id") or ""
    transcript = find_transcript(sid)
    if transcript is None:
        print("{}")
        return
    total, last_write = count_tools(transcript)
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    state_file = STATE_DIR / f"{sid}.json"
    try:
        last_nudge = json.loads(state_file.read_text()).get("last_nudge", 0)
    except (OSError, ValueError):
        last_nudge = 0
    since = total - max(last_write, last_nudge)
    if since < THRESHOLD:
        print("{}")
        return
    state_file.write_text(json.dumps({"last_nudge": total}))
    print(json.dumps({"followup_message": REASON.format(n=since)}))


if __name__ == "__main__":
    try:
        main()
    except Exception:
        print("{}")

4. Automatic, Secret-Safe Session Archiving

When a chat ends (sessionEnd), obsidian-session-archive.py scans parent transcripts in ~/.cursor/projects/*/agent-transcripts/<id>/<id>.jsonl (skipping subagents) and writes clean Markdown summaries to:

  • Meta/cursor-sessions/YYYY-MM/<YYYY-MM-DD>_<id8>.md
  • Meta/cursor-session-history.md (a table of the 400 newest chats with [[wikilinks]])

Before writing, it redacts passwords, bearer tokens, sk- API keys, GitHub tokens, and private keys—and uses an index (~/.cursor/cursor-session-archive.json) so unchanged transcripts aren’t rewritten.

~/.cursor/hooks/obsidian-session-archive.py

#!/usr/bin/env python3
"""Cursor sessionEnd hook: archive agent chats into the Obsidian vault.

Source : ~/.cursor/projects/*/agent-transcripts/<id>/<id>.jsonl  (read-only)
Index  : ~/.cursor/cursor-session-archive.json                  (size and mtime)
Output : <VAULT>/Meta/cursor-session-history.md
         <VAULT>/Meta/cursor-sessions/YYYY-MM/<date>_<id8>.md

A transcript is rewritten only when its size or mtime changed.
Subagent transcripts are skipped. The archive stays on this machine, in the vault.
"""
import json
import os
import re
import sys
from datetime import datetime
from pathlib import Path

HOME = Path.home()
PROJECTS = HOME / ".cursor" / "projects"
INDEX_PATH = HOME / ".cursor" / "cursor-session-archive.json"
VAULT = Path(os.environ.get("OBSIDIAN_VAULT", HOME / "ObsidianVault"))
META = VAULT / "Meta"
HISTORY = META / "cursor-session-history.md"
SESSIONS = META / "cursor-sessions"

USER_QUERY = re.compile(r"<user_query>\s*(.*?)\s*</user_query>", re.S)
SECRET_PATTERNS = [
    (re.compile(r"(?i)\b(password|passwd|pwd|secret|token|api[_-]?key)\s*[:=]\s*\S+"), r"\1=[REDACTED]"),
    (re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._\-]{16,}"), "Bearer [REDACTED]"),
    (re.compile(r"\bsk-[A-Za-z0-9_\-]{20,}"), "[REDACTED-KEY]"),
    (re.compile(r"\bgh[pousr]_[A-Za-z0-9]{30,}"), "[REDACTED-GH]"),
    (re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S), "[REDACTED-PRIVATE-KEY]"),
]


def redact(text: str) -> str:
    for pat, repl in SECRET_PATTERNS:
        text = pat.sub(repl, text)
    return text


def one_line(text: str, n: int) -> str:
    text = " ".join((text or "").split())
    return text if len(text) <= n else text[: n - 1] + "…"


def user_prompt(obj: dict) -> str:
    parts = []
    for block in (obj.get("message") or {}).get("content") or []:
        if isinstance(block, dict) and block.get("type") == "text":
            parts.append(block.get("text") or "")
    raw = "\n".join(parts)
    match = USER_QUERY.search(raw)
    text = match.group(1) if match else raw
    text = redact(text).strip()
    if text.startswith("<") or "system_reminder" in text[:80]:
        return ""
    return text


def parse_transcript(path: Path) -> dict:
    prompts = []
    tools = 0
    last_assistant = ""
    with path.open(encoding="utf-8", errors="replace") as fh:
        for line in fh:
            try:
                obj = json.loads(line)
            except json.JSONDecodeError:
                continue
            role = obj.get("role")
            content = (obj.get("message") or {}).get("content") or []
            if role == "user":
                prompt = user_prompt(obj)
                if prompt:
                    prompts.append(prompt)
            elif role == "assistant":
                for block in content:
                    if not isinstance(block, dict):
                        continue
                    if block.get("type") == "tool_use":
                        tools += 1
                    elif block.get("type") == "text" and (block.get("text") or "").strip():
                        last_assistant = block.get("text") or ""
    stamp = datetime.fromtimestamp(path.stat().st_mtime)
    title = one_line(prompts[0], 80) if prompts else path.stem[:8]
    project = path.parents[2].name if len(path.parents) > 2 else ""
    return {
        "id": path.parent.name,
        "title": title,
        "project": project,
        "when": stamp.strftime("%Y-%m-%d %H:%M"),
        "month": stamp.strftime("%Y-%m"),
        "day": stamp.strftime("%Y-%m-%d"),
        "prompts": prompts[:40],
        "tools": tools,
        "last": redact(last_assistant).strip()[:4000],
        "path": str(path),
        "size": path.stat().st_size,
        "mtime": path.stat().st_mtime,
    }


def note_body(info: dict) -> str:
    lines = [
        "---",
        "type: cursor-session",
        f"session: {info['id']}",
        f"project: {info['project']}",
        f"updated: {info['when']}",
        "---",
        "",
        f"# {info['title']}",
        "",
        f"Tool calls: {info['tools']}. Transcript: `{info['path']}`.",
        "",
        "## Prompts",
        "",
    ]
    for prompt in info["prompts"]:
        lines.append(f"- {one_line(prompt, 400)}")
    if info["last"]:
        lines.extend(["", "## Last answer", "", info["last"], ""])
    return "\n".join(lines)


def transcripts():
    for path in PROJECTS.glob("*/agent-transcripts/*/*.jsonl"):
        if "subagents" in path.parts:
            continue
        if path.stem != path.parent.name:
            continue
        yield path


def load_index() -> dict:
    try:
        return json.loads(INDEX_PATH.read_text())
    except (OSError, ValueError):
        return {}


def write_note(info: dict) -> bool:
    folder = SESSIONS / info["month"]
    folder.mkdir(parents=True, exist_ok=True)
    dest = folder / f"{info['day']}_{info['id'][:8]}.md"
    body = note_body(info)
    old = dest.read_text(encoding="utf-8") if dest.exists() else ""
    if old == body:
        return False
    dest.write_text(body, encoding="utf-8")
    return True


def write_history(rows: list[dict]):
    rows = sorted(rows, key=lambda r: r["when"], reverse=True)
    lines = [
        "---",
        "type: cursor-session-history",
        "---",
        "",
        "# Cursor session history",
        "",
        "Local archive of Cursor agent chats. Each row links to a note under `cursor-sessions/`.",
        "",
        "| When | Project | Tools | Title |",
        "| --- | --- | --- | --- |",
    ]
    for row in rows[:400]:
        link = f"[[cursor-sessions/{row['month']}/{row['day']}_{row['id'][:8]}|{one_line(row['title'], 80)}]]"
        lines.append(f"| {row['when']} | {row['project']} | {row['tools']} | {link} |")
    lines.append("")
    HISTORY.write_text("\n".join(lines), encoding="utf-8")


def archive_all() -> int:
    index = load_index()
    rows = []
    changed = 0
    for path in transcripts():
        key = str(path)
        stat = path.stat()
        cached = index.get(key) or {}
        same = cached.get("size") == stat.st_size and cached.get("mtime") == stat.st_mtime
        if same and cached.get("row"):
            rows.append(cached["row"])
            continue
        info = parse_transcript(path)
        if write_note(info):
            changed += 1
        row = {k: info[k] for k in ("id", "title", "project", "when", "month", "day", "tools")}
        index[key] = {"size": info["size"], "mtime": info["mtime"], "row": row}
        rows.append(row)
    if rows:
        META.mkdir(parents=True, exist_ok=True)
        write_history(rows)
        INDEX_PATH.write_text(json.dumps(index))
    return changed


def main():
    try:
        json.load(sys.stdin)
    except json.JSONDecodeError:
        pass
    archive_all()
    print("{}")


if __name__ == "__main__":
    try:
        main()
    except Exception:
        print("{}")

Why This Works So Well

  1. Zero vendor lock-in: Your AI’s memory is plain Markdown in Obsidian—searchable, editable, and linkable by you at any time.
  2. Cross-tool continuity: Discover a quirk in Claude Code, and Cursor knows about it in your next chat (and vice versa).
  3. Local-first & private: Everything stays on your machine, with automatic secret redaction on archived transcripts.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.