claude-code-memory-setup

lucasrosatiMIT活跃维护

给 Claude Code 加持久记忆:用 Obsidian 和 Graphify 建代码库知识图谱,把每轮对话 token 消耗最多降 71.5 倍。

Up to 71.5x fewer tokens per session on Claude Code with Obsidian + Graphify. Persistent memory, codebase knowledge graphs, and chat import pipeline. 🇧🇷 PT-BR included.

v1.1.0发布于 2026-10-21 04:28 UTC1,061star94fork同步于 2026-11-10 11:50 UTC

怎么上手

由 README 提炼,执行前请确认
pip install graphifyy
graphify install --platform claude
硬件要求按 README 说明

README 未说明显存或 GPU 要求;代码图谱默认纯 AST 本地处理,不依赖 GPU。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 Obsidian 加 Graphify 给 Claude Code 装长期记忆和代码知识图谱,减少重复读文件

给 Claude Code 加持久记忆:用 Obsidian 和 Graphify 建代码库知识图谱,把每轮对话 token 消耗最多降 71.5 倍。

核心能力

  • 用 Obsidian Zettelkasten 单库跨会话保存决策与上下文
  • 用 tree-sitter AST 本地生成代码知识图谱供查询
  • SHA256 缓存只重跑改动文件,默认 AST 模式零 token
  • 提供 /save /resume /memorize /commit 会话命令
  • 含 Claude 聊天导出并打标签入库的导入流水线

容易踩的坑

Graphify 语义抽取需先导出 ANTHROPIC_API_KEY 或 MOONSHOT_API_KEY,否则只能用 AST 模式;--obsidian 与 --obsidian-dir 仅在 Claude Code 的 /graphify 技能里可用,终端 CLI 不支持需手动软链输出目录;需自行安装 Obsidian 并建好 vault 目录结构,命令文件要复制到 ~/.claude/commands/ 后重启生效。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

3 个版本v1.1.0
  1. v1.1.0v1.1.0: unified /save and shipped commands最新正式版2026-10-21 · 2026-10-21 04:28 UTC

    Added

    The new commands/ folder ships /save, /resume, /memorize and /commit as ready-to-install command files. /save now consolidates memory automatically in its Phase 2: explicit criteria decide what is worth keeping, a grep-based deduplication step runs before every write, each kind of knowledge has its own destination, and insights get one-line pointers in ## Permanent facts of <vault>/<project>/CLAUDE.md. Session logs also gain a "State for resume" section (task, branch, pending criteria, tests, blockers, next action).

    Changed

    /memorize is now an explicit mid-session trigger, since end-of-session consolidation is handled by /save. /commit runs /save after the push. Both READMEs organize the installation of the session commands around commands/, with skills kept as an alternative.

    Install with cp commands/*.md ~/.claude/commands/ and restart Claude Code. See the CHANGELOG for details.

    Thanks to everyone in the community who tried the setup, opened issues and sent PRs. Your feedback shaped this release.

  2. v1.0.0v1.0.0 — Auto-save hook and CLI corrections2026-09-11 · 2026-09-11 02:49 UTC
    查看更新说明

    The setup now covers the full memory lifecycle for Claude Code.

    Highlights

    Auto-save hook. A new SessionEnd hook (scripts/session_autosave.py) writes a session log to the vault automatically when a session closes. Zero LLM calls: facts are parsed mechanically from the transcript. It is a safety net for when /save is forgotten, not a replacement for it. Inspired by ai-memory (https://github.com/akitaonrails/ai-memory).

    Chat import scripts published. claude_to_obsidian.py and sync_claude_obsidian.sh are now real files in scripts/ instead of prose in the README.

    Graphify commands corrected. The packaged CLI is subcommand-based, so the old graphify . --flag form fails from the terminal. Both paths are now documented: the skill form inside Claude Code and the headless form for terminal and CI.

    Setup clarifications. Session commands as global skills, a warning about keeping code repositories out of the vault, and multi-repo guidance.

    Full details in CHANGELOG.md. Thanks to everyone who opened issues and pull requests.

  3. v0.1.0v0.1.0 — Initial guide2026-09-11 · 2026-09-11 02:49 UTC
    查看更新说明

    First public version of the guide.

    Covers the three original layers of the setup:

    • Obsidian vault as persistent memory (Zettelkasten, /save and /resume)
    • Chat import pipeline (Claude Code and Claude Web conversations into the vault)
    • Graphify codebase knowledge graph

    Includes the full Portuguese translation.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Claude Code + Obsidian + Graphify: The Definitive Guide to Token Savings & Persistent Memory

    Persistent memory across sessions with Obsidian Zettelkasten and selective code context with Graphify. Token savings depend on the task; the historical 71.5x/session and 499x/query claims are author-reported and not reproducible from published data.

    A complete setup to turn Claude Code into an agent with long-term memory and full codebase awareness — without wasting tokens re-reading files.

    🇧🇷 Leia em Português


    Table of Contents

    1. The Problem
    2. The Solution (Overview)
    3. Part 1 — Obsidian as Persistent Memory
    4. Part 2 — Chat Import Pipeline
    5. Part 3 — Graphify (Codebase Knowledge Graph)
    6. Part 4 — Complete Workflow
    7. Part 5 — Auto-Save Hook (Safety Net)
    8. Real Results
    9. Troubleshooting

    The Problem

    When working with Claude Code, two problems silently eat your tokens:

    Problem 1 — Amnesia between sessions. Every time you open a new session, you have to re-explain your project: stack, past decisions, current bugs, what's left to do. Claude Code remembers nothing from the previous session.

    Problem 2 — Codebase re-reading. Repeated source exploration can consume context tokens, but how much depends on the task and navigation tools. The historical illustration compares ~20,000 tokens of source context with ~280 tokens of graph query output: approximately 71.4x less retrieval context, not a measured reduction in complete session usage. It assumes the smaller output answers the same question; the original payloads and tokenizer were not published.


    The Solution (Overview)

    Two complementary systems, each solving a different problem:

    LayerToolProblem SolvedCost
    Project memoryObsidian ZettelkastenAmnesia between sessionsFree
    Code mapGraphifyCodebase re-readingFree (AST mode)
    Conversation historyImport pipelineLost chat insightsFree
    Continuity/resume and /save commandsPicking up where you left offFree

    Obsidian handles what was decided (declarative memory). Graphify handles how the code is structured (structural map). Together, they can help Claude Code recover relevant context. Source reads remain necessary when the graph or notes are incomplete or stale.


    Part 1 — Obsidian as Persistent Memory

    Concept

    A single, centralized Obsidian vault acts as Claude Code's "second brain." It stores decisions, context, progress, and knowledge for all your projects. Notes follow the Zettelkasten method: atomic (one idea per note), densely interlinked, with standardized metadata.

    Claude Code accesses the vault through CLAUDE.md and custom skills.

    Recommended Structure

    ~/vault/                              # SINGLE vault for all projects
    ├── CLAUDE.md                         # global instructions for Claude Code
    ├── permanent/                        # consolidated atomic notes
    ├── inbox/                            # raw capture (ideas, drafts)
    ├── fleeting/                         # quick temporary notes
    ├── templates/                        # note templates
    ├── logs/                             # global session logs
    ├── references/                       # reference material
    ├── my-project/                       # MOCs and notes for project X
    │   ├── architecture/                 #   architecture, decisions, conventions
    │   ├── pipeline/                     #   data flows, APIs
    │   ├── data/                         #   schema, data model
    │   ├── features/                     #   planned/implemented features
    │   └── logs/                         #   project session logs
    ├── another-project/                  # MOCs and notes for project Y
    │   └── ...
    ├── chats/                            # imported Claude chats
    │   ├── code/                         #   from Claude Code
    │   └── web/                          #   from Claude Web/App
    └── graphify/                         # codebase knowledge graphs
        ├── my-project/                   #   graph notes for project X
        └── another-project/              #   graph notes for project Y
    

    Why a single vault? Having one vault per project fragments knowledge. With a single vault, a note about "Supabase Auth" links to both project A and B. The graph view reveals cross-project connections you didn't expect.

    Step-by-Step Setup

    Prerequisites:

    • Claude Code installed and authenticated
    • Obsidian installed (free: obsidian.md)

    1. Create the vault:

    Obsidian → "Create new vault" → choose a name and location.

    2. Create the folder structure:

    cd ~/vault  # adjust to your path
    mkdir -p permanent inbox fleeting templates logs references
    mkdir -p my-project/{architecture,pipeline,data,features,logs}
    

    3. Create the CLAUDE.md:

    This is the file Claude Code reads automatically. Create CLAUDE.md at the vault root:

    # Vault — Instructions for Claude Code
    
    ## What is this vault
    Centralized knowledge base for all projects.
    Persistent memory across sessions.
    
    ## Project stacks
    - Project X: React + Supabase
    - Project Y: Python + FastAPI
    (adapt to your projects)
    
    ## Zettelkasten Rules
    
    ### Note creation
    - Use wikilinks: [[note-name]] (not markdown links)
    - Mandatory YAML frontmatter on every note
    - Filenames in kebab-case: `auth-flow.md`, not `Auth Flow.md`
    - 1 concept per permanent note (atomicity)
    - Minimum 2 wikilinks per note (dense linking)
    
    ### Standard frontmatter
    ---
    title: Note Name
    tags: [project, topic]
    created: YYYY-MM-DD
    updated: YYYY-MM-DD
    status: active
    type: permanent
    ---
    
    ### Never do
    - Don't delete notes without asking
    - Don't use markdown links for internal notes (use wikilinks)
    - Don't create notes without frontmatter
    - Don't change folder structure without documenting it
    
    ## Session Commands
    /resume, /save, /memorize and /commit are installed from the guide's
    commands/ folder into ~/.claude/commands/ (see step 6). Their full
    instructions live there; this file only holds the vault rules they follow.
    

    4. Create a note template:

    cat > templates/default-note.md << 'EOF'
    ---
    title: {{title}}
    tags: []
    created: {{date}}
    updated: {{date}}
    status: draft
    type: permanent
    ---
    
    # {{title}}
    
    ## Context
    
    ## Details
    
    ## Related links
    EOF
    

    5. Recommended Obsidian plugins:

    PluginPurposeInstall method
    BRATInstall beta pluginsCommunity Plugins → Browse
    3D Graph3D vault visualizationVia BRAT (v2.4.1)
    Folders to GraphFolders as graph nodesCommunity Plugins → Browse
    CalendarDaily note navigationCommunity Plugins → Browse

    6. Install the session commands:

    The commands/ folder ships /save, /resume, /memorize and /commit as ready-to-use command files. Copy them and restart Claude Code:

    cp commands/*.md ~/.claude/commands/
    rm ~/.claude/commands/README.md
    export VAULT_DIR=~/vault  # optional; ~/vault is the default
    

    See commands/README.md for what each command does.

    Alternatively, package the same instructions as global skills (~/.claude/skills/<name>/SKILL.md, one folder per command). Skills register as slash commands too and can carry extra reference files, but the plain command files are simpler to keep in sync with this repo.


    Part 2 — Chat Import Pipeline

    Concept

    Your Claude chats (both Code and Web) contain valuable decisions, insights, and context that get lost in the history. This pipeline exports, processes, and imports those conversations as vault notes — with frontmatter, automatic tags, and wikilinks to existing notes.

    Components

    ~/scripts/
    ├── claude_to_obsidian.py          # processor (frontmatter, tags, wikilinks)
    └── sync_claude_obsidian.sh        # automation (export + process)
    
    ~/claude-exports/                   # temporary staging area (outside vault)
    ├── code/                           # Claude Code exports
    └── web/                            # Claude Web exports
    

    Setup

    1. Install the Claude Code extractor:

    pip install claude-conversation-extractor
    

    2. Create staging directories:

    mkdir -p ~/claude-exports/code ~/claude-exports/web
    

    3. Create the post-processing script (~/scripts/claude_to_obsidian.py):

    The script should:

    • Read each exported .md file
    • Detect origin (Code vs Web)
    • Generate automatic tags based on content keywords
    • Add standardized YAML frontmatter
    • Insert [[wikilinks]] for notes that already exist in the vault
    • Copy to chats/code/ or chats/web/ inside the vault

    Example keyword-to-tag mapping:

    KEYWORD_TAG_MAP = {
        "python": "python",
        "react": "react",
        "supabase": "supabase",
        "deploy": "deploy",
        "bug": "debugging",
        "refactor": "refactoring",
        # add your own
    }
    

    4. Create the automation script (~/scripts/sync_claude_obsidian.sh):

    #!/bin/bash
    EXPORT_DIR="$HOME/claude-exports"
    VAULT_DIR="$HOME/vault"  # adjust to your path
    SCRIPT_DIR="$HOME/scripts"
    LOG="$SCRIPT_DIR/sync.log"
    
    echo "[$(date)] Sync started" >> "$LOG"
    
    # Export Claude Code chats
    claude-extract --all --output "$EXPORT_DIR/code" 2>> "$LOG"
    
    # Process and send to vault
    python3 "$SCRIPT_DIR/claude_to_obsidian.py" \
        --export-dir "$EXPORT_DIR" \
        --vault-dir "$VAULT_DIR" \
        --move 2>> "$LOG"
    
    echo "[$(date)] Sync completed" >> "$LOG"
    

    5. Schedule automatic execution:

    chmod +x ~/scripts/sync_claude_obsidian.sh
    
    # Run daily at 10 PM
    (crontab -l 2>/dev/null; echo "0 22 * * * $HOME/scripts/sync_claude_obsidian.sh") | crontab -
    

    6. For Claude Web chats:

    Install the "Export Claude Chat to Markdown" browser extension for Chrome/Edge. Do periodic bulk exports, save the .md files to ~/claude-exports/web/, and the cron job handles the rest.

    7. Add a section to the vault's CLAUDE.md:

    ## Chat Import Pipeline
    
    ### Structure
    - `chats/code/` → imported Claude Code conversations
    - `chats/web/` → imported Claude Web/App conversations
    - All chats get frontmatter with `type: chat` and `chat-import` tag
    
    ### Filter in Graph View
    - `tag:chat-import` → chats only
    - `-path:chats` → hide chats
    

    Part 3 — Graphify (Codebase Knowledge Graph)

    Concept

    Graphify transforms your codebase into a queryable knowledge graph. Instead of Claude Code re-reading every file, it queries the graph — which is persistent across sessions and costs a fraction of the tokens.

    • Code: processed 100% locally via tree-sitter AST. No code content leaves your machine.
    • Cache: SHA256 — re-runs only process modified files.
    • Cost: 0 tokens in default mode (pure AST). --deep mode uses LLM for semantic edges.
    • Languages: Python, JavaScript, TypeScript, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, and more (20 languages via tree-sitter).

    Setup

    1. Install:

    pip install graphifyy
    graphify install --platform claude
    

    graphify install --platform claude creates the skill at ~/.claude/skills/graphify/SKILL.md. Other platforms are also supported (cursor, codex, opencode, etc.).

    1.5. Set up API key (required for semantic extraction):

    Graphify needs an LLM API key from Anthropic or Moonshot (Kimi) for semantic extraction. Export one before running:

    export ANTHROPIC_API_KEY="your-key-here"
    # or
    export MOONSHOT_API_KEY="your-key-here"
    

    If you want to skip LLM costs entirely, use AST-only mode:

    graphify extract . --out ./graphify-out --no-cluster
    

    This generates a structural graph without semantic edges.

    2. Generate the graph:

    Graphify has two execution paths and the original --obsidian* flags only work on one of them. Pick the form that matches how you're invoking it:

    A. Inside Claude Code (skill — recommended for this guide):

    /graphify . --obsidian --obsidian-dir ~/vault/graphify/project-name
    

    This runs the /graphify slash command, which the skill at ~/.claude/skills/graphify/SKILL.md parses. The skill calls graphify.export.to_obsidian() in Python directly, so --obsidian and --obsidian-dir are recognized here — they're not part of the headless shell parser.

    B. From the terminal / CI (headless CLI):

    graphify extract . --out ./graphify-out
    

    The headless CLI uses subcommands (extract, update, watch, tree) and does not expose --obsidian / --obsidian-dir / --wiki / --mode deep. If you want Obsidian integration from the terminal, symlink the output directory into your vault after extraction:

    ln -s $(pwd)/graphify-out ~/vault/graphify/project-name/graphify-out
    

    Generated output (varies by path and flags):

    your-project/
    └── graphify-out/
        ├── graph.json          # queryable graph (always)
        ├── graph.html          # interactive viz (skill auto-generates; headless: see step 3)
        ├── GRAPH_REPORT.md     # god nodes, connections, metrics (always)
        ├── wiki/               # Wikipedia-style articles (skill form with --wiki only)
        └── cache/              # SHA256 cache
    
    ~/vault/graphify/project-name/    # only when skill form was given --obsidian
        └── (Obsidian notes)          # one note per function/module
    

    3. Generate interactive visualization (headless only):

    The skill auto-generates graph.html during extraction. For the headless path, run the visualization as a separate step:

    graphify tree --graph ./graphify-out/graph.json --output ./graphify-out/GRAPH_TREE.html
    

    Open the HTML file in a browser to explore the graph interactively.

    4. Update .gitignore:

    # Graphify
    graphify-out/cache/
    

    Keep graph.json and GRAPH_REPORT.md versioned — they're useful for the team.

    5. Add to the project's CLAUDE.md:

    Append to the CLAUDE.md at the repository root:

    ## Context Navigation (Graphify)
    
    ### 3-Layer Query Rule
    1. **First:** query `graphify-out/graph.json` or `graphify-out/wiki/index.md`
       to understand code structure and connections
    2. **Second:** query the Obsidian vault for decisions, progress, and project context
    3. **Third:** only read raw code files when editing
       or when the first two layers don't have the answer
    
    ### When to rebuild the graph
    - After structural changes (new modules, major refactors)
    - Headless: `graphify update .` (only processes modified files)
    - Skill: `/graphify . --update` (same behavior, runs through the skill — also accepts `--obsidian` to refresh the vault)
    - The graph is persistent — NO need to rebuild every session
    
    ### Do NOT
    - Don't manually modify files inside `graphify-out/`
    - Don't re-read the entire codebase if the graph already has the information
    

    6. Add to the vault's CLAUDE.md:

    ## Graphify (Codebase Maps)
    
    ### Structure
    - `graphify/project-x/` → knowledge graph for project X
    - Future projects get their own subfolders
    - Notes are auto-generated — do NOT edit manually
    
    ### In Graph View
    - Filter by `path:graphify` to see only code nodes
    - Filter by `-path:graphify` to hide code nodes
    

    7. Git Hook (optional):

    Automatically rebuilds the graph on every commit:

    graphify hook install
    

    8. Watch Mode (optional):

    Auto-rebuild on file save. Pick the form that matches how you invoke graphify.

    Headless (separate terminal):

    graphify watch .
    

    Skill (inside Claude Code):

    /graphify . --watch
    

    Useful Commands

    The table below lists the headless CLI subcommands you'd run in a terminal. Inside Claude Code, the same operations are available via the /graphify slash form documented in ~/.claude/skills/graphify/SKILL.md — that form additionally supports --obsidian, --obsidian-dir, --wiki, and --mode deep (which the headless parser doesn't expose).

    CommandDescription
    graphify extract .Full extraction on current directory
    graphify extract ./srcScan specific folder
    graphify update .Only process modified files
    graphify watch .Auto-rebuild on save
    graphify query "question"Query the graph directly
    graphify explain "NodeName"Plain-language explanation of a node
    graphify path "A" "B"Shortest path between two nodes
    graphify tree --graph ./graphify-out/graph.json --output ./graphify-out/GRAPH_TREE.htmlGenerate interactive visualization
    open graphify-out/graph.htmlOpen interactive visualization (skill-generated) or GRAPH_TREE.html (headless)

    Adding New Projects

    With a centralized vault, each project is just a subfolder. Same two paths as the initial setup.

    Skill (inside Claude Code):

    /graphify ~/another-project --obsidian --obsidian-dir ~/vault/graphify/another-project
    

    Headless (terminal):

    cd ~/another-project
    graphify extract . --out ./graphify-out
    ln -s $(pwd)/graphify-out ~/vault/graphify/another-project/graphify-out
    

    Drop the ln -s line if you don't need Obsidian to pick up the graph. Notes appear in Obsidian's graph view alongside everything else.


    Part 4 — Complete Workflow

    Typical session

    Open Claude Code session
        │
        ├── /resume                      ← loads vault context
        │                                   (recent logs, decisions, progress)
        │
        ├── Claude queries graph.json     ← understands code structure
        │                                   without re-reading all files
        │
        ├── Work on code                  ← features, bugs, refactors
        │
        ├── /memorize (optional)         ← explicit mid-session trigger:
        │                                   pins a decision or insight now
        │
        ├── /save                        ← session log + memory consolidation
        │                                   (decisions, insights, facts)
        │
        └── /commit                      ← commit + push, then runs /save
                                            (post-commit hook rebuilds graph)
    

    What /save memorizes

    After writing the session log, /save runs a consolidation phase. It writes only durable knowledge; when in doubt it writes nothing, because the log already preserves the context.

    Goes into memoryStays out
    Technical or architectural decision with a rationale (alternatives were considered)Progress, completed tasks, pending items (already in the log)
    Reusable insight: pattern, pitfall, non-obvious bug root cause, tool behaviorInvestigations without a conclusion
    Project convention created or changedImplementation details that don't generalize
    Durable project fact: schema, structure, pipeline, path, known bug with a causeItems already memorized with no change
    Correction of something memorized that turned out wrong

    Deduplication: before writing, each candidate is grepped in <vault>/permanent/, the project folder and the project CLAUDE.md. If an equivalent note exists, it is updated (content and updated field), never duplicated.

    Destinations:

    • Decision → appended to <vault>/<project>/architecture/decisions.md
    • Reusable insight → new note in <vault>/permanent/, plus a one-line pointer in ## Permanent facts of <vault>/<project>/CLAUDE.md
    • Project fact → the matching note in data/, architecture/, features/ or pipeline/, or a line in ## Permanent facts
    • Convention → proposed for ## Conventions in the project's CLAUDE.md, written only after you confirm (y/n)

    <vault>/<project>/CLAUDE.md is created only when the first line is written to it, and archives its oldest sections to architecture/claude-archive.md past 300 lines.

    Report format:

    Session log: <vault>/<project>/logs/2026-10-21-short-description.md
    Memory:
    - created: <vault>/permanent/some-insight.md (reason in one line)
    - updated: <vault>/<project>/architecture/decisions.md (reason in one line)
    

    When nothing qualifies, the second line reads Memory: nothing to consolidate this session.

    Savings per layer

    LayerWithout itWith it
    /resumeRe-explain project every sessionClaude already knows the context
    GraphifyHistorical illustration: ~40 files (~20k tokens)Selected graph query output (~280 tokens); unverified payload estimate, not session usage
    Chat pipelineInsights lost in chat historyEverything indexed and searchable
    /save + logsForget what was doneComplete history with wikilinks

    Graph View Filters

    FilterWhat it shows
    path:permanentOnly permanent notes (consolidated knowledge)
    path:graphifyOnly codebase nodes (functions, modules, imports)
    tag:chat-importOnly imported chats
    -path:graphify -path:chatsOnly manual notes (pure vault)

    Part 5 — Auto-Save Hook (Safety Net)

    Concept

    The /save command produces rich session logs, but it depends on you remembering to run it. Forget it once and the session vanishes. This hook fixes that: Claude Code fires a SessionEnd event when a session closes (exit, /clear, logout), and a small Python script mechanically extracts the session facts from the transcript and writes a minimal log to your vault.

    Design principles (inspired by ai-memory):

    • Zero LLM calls. Pure JSONL parsing. Runs in milliseconds, needs no API key.
    • Safety net, not replacement. /save remains the rich log (decisions, pending items, wikilinks). The auto-log guarantees forgotten sessions still leave a trace: objective (first prompt), files touched, commands executed, stats.
    • No memory consolidation. The hook is mechanical and never runs the consolidation phase of /save; only /save updates decisions, permanent notes and project facts.
    • Silent failure. A hook must never break your session. Errors go to ~/scripts/autosave.log and Claude Code never notices.
    • Noise filter. Sessions with fewer than 2 user messages are skipped.

    Setup

    1. Copy the script:

    The script lives in this repo at scripts/session_autosave.py.

    mkdir -p ~/scripts
    cp scripts/session_autosave.py ~/scripts/
    chmod +x ~/scripts/session_autosave.py
    

    2. Register the hook in ~/.claude/settings.json:

    If the file already exists, merge the hooks key without removing anything else:

    {
      "hooks": {
        "SessionEnd": [
          {
            "hooks": [
              {
                "type": "command",
                "command": "VAULT_DIR=$HOME/vault python3 $HOME/scripts/session_autosave.py"
              }
            ]
          }
        ]
      }
    }
    

    Adjust VAULT_DIR to your vault path.

    3. Test:

    Open a Claude Code session in any project, exchange 2-3 messages with a file edit, then exit. Check:

    tail -5 ~/scripts/autosave.log
    # should show: OK: wrote /path/to/vault/.../logs/YYYY-MM-DD-HHMM-auto-session.md
    

    How routing works

    The script derives the project name from the session's working directory (cwd basename):

    • If <vault>/<project>/ exists → log goes to <vault>/<project>/logs/
    • Otherwise → falls back to <vault>/logs/

    If your repo folder name differs from the vault folder name (e.g. repo my-app-monorepo, vault folder my-app), create a symlink:

    ln -s ~/vault/my-app ~/vault/my-app-monorepo
    

    Filtering auto-logs in Obsidian

    Auto-logs get the auto-log tag and status: imported frontmatter:

    FilterWhat it shows
    tag:auto-logOnly auto-generated session logs
    -tag:auto-logHide auto-logs (manual notes only)

    Updated workflow

    Open Claude Code session
        │
        ├── /resume                      ← loads vault context
        ├── Work on code
        ├── /save (optional)             ← rich log with decisions
        └── exit                         ← SessionEnd hook fires
                                            auto-log written even if
                                            you forgot /save
    

    Real Results

    Author-reported example from a React + Supabase project with 126 TypeScript files. The source snapshot, graph, prompts, tokenizer and usage logs were not published, so these inventory counts and the token ratio cannot currently be reproduced:

    MetricValue
    Graph nodes332
    Edges (connections)258
    Communities detected124
    graph.json size172 KB
    Obsidian notes generated456
    Historical token reduction per query499x, author-reported; baseline and query counts unavailable
    Reported LLM usage for graph generation0 tokens (AST mode); excludes agent reads, queries and session usage
    Imported chats in vault137
    Accumulated permanent notes65+
    Total vault notes780+

    Evidence and benchmark

    The historical 71.5x per session headline is not supported by a published session ledger. The ~20,000 / ~280 illustration gives ~71.4x for retrieval context (about 98.6% less), while 499x per query is a separate undocumented comparison. Neither establishes end-to-end session savings or dollar savings.

    Hlido reports 82/100 for its repository review; the accessible public evidence does not validate these token ratios. See issue #12 and the evidence audit and benchmark protocol for provenance, date discrepancies, assumptions and limitations.

    The protocol defines fixed inputs, paired source-navigation and memory arms, correctness criteria, cache accounting, graph construction costs, and separate query/session measurements. An offline usage summarizer is included. Its synthetic fixture checks arithmetic only; no new performance results or paid runs are claimed.


    Architecture

    ┌─────────────────────────────────────────────────────────────┐
    │                    OBSIDIAN VAULT (single)                   │
    │                                                             │
    │  permanent/  ← consolidated knowledge (Zettelkasten)        │
    │  logs/       ← session logs (/save)                         │
    │  chats/      ← imported conversations (cron pipeline)       │
    │  graphify/   ← codebase knowledge graphs                    │
    │  project-x/  ← MOCs, decisions, architecture                │
    │                                                             │
    │  CLAUDE.md   ← global instructions for Claude Code          │
    └─────────────────────────┬───────────────────────────────────┘
                              │
                        Claude Code reads/writes
                              │
    ┌─────────────────────────┴───────────────────────────────────┐
    │                   PROJECT REPOSITORY                         │
    │                                                             │
    │  src/            ← source code                              │
    │  CLAUDE.md       ← project instructions + Context Nav       │
    │  graphify-out/   ← graph.json, graph.html, report           │
    │  .git/hooks/     ← post-commit rebuilds the graph           │
    └─────────────────────────────────────────────────────────────┘
    

    Troubleshooting

    Graphify notes don't appear in Obsidian: Confirm the notes are inside the actual vault directory. Obsidian doesn't always point where you think — create a note in Obsidian and run find ~ -name "note-name.md" to discover the real path. Then move the notes there and Cmd+Q / reopen.

    Graph view empty with filter applied: Disable "Orphans" and "Existing files only" in the graph filters. Cmd+Q and reopen Obsidian to force reindexing.

    Claude Code doesn't query the graph: Check that the project's CLAUDE.md has the "Context Navigation" section and that graphify-out/graph.json exists at the repo root.

    Cron doesn't run (macOS): Grant Full Disk Access to your terminal in System Preferences → Privacy & Security.

    Graphify doesn't generate wiki: The wiki/ folder is only produced by the skill form with --wiki (/graphify . --wiki inside Claude Code). The headless graphify extract subcommand doesn't expose --wiki. From the terminal, use graphify query "question" against graph.json instead, or run the skill form if you need the Wikipedia-style articles.

    Files with parentheses in name: Graphify generates notes like myFunction().md. Obsidian may struggle indexing files with () in the name. If needed, batch rename:

    cd ~/vault/graphify/project
    for f in *"("*; do mv "$f" "$(echo "$f" | sed 's/[()]//g')"; done
    

    Unknown Command error in graphify: If graphify . errors with unknown command '.', you're running the headless CLI — which requires a subcommand (extract, update, watch, etc.) before the path. Either use the headless form:

    graphify extract . --out ./graphify-out
    # or, to refresh an existing graph:
    graphify update .
    

    Or, inside Claude Code, use the skill form with the leading slash — which routes through the /graphify skill rather than the shell parser and supports the full flag set (--obsidian, --obsidian-dir, --wiki, --mode deep, etc.):

    /graphify . --obsidian --obsidian-dir ~/vault/graphify/project-name
    

    /save memorized something irrelevant: The consolidation phase follows the criteria in step 2.1 of ~/.claude/commands/save.md. Tighten them: remove a criterion you don't want, or add the case to the "Not candidates" list. Then delete or edit the note it wrote.

    Duplicate notes in permanent/: Check step 2.2 of ~/.claude/commands/save.md: the grep must run before any write and must cover <vault>/permanent/. If your notes use different terms for the same concept, add aliases to their frontmatter or tags so the grep finds them, then merge the duplicates by hand.


    Credits & Links

    • Graphify — codebase knowledge graphs (MIT)
    • Obsidian — PKM and second brain (free)
    • Claude Code — Anthropic's coding agent
    • Inspired by Andrej Karpathy's system and the r/ClaudeAI community

    If this guide helped you, give the repo a ⭐ and share it with other devs using Claude Code.