obsidian-mind
Vault template
First committed by breferrari
Published in breferrari/obsidian-mind. Publisher page
5,527 GitHub stars
What it is
A self-organizing Obsidian vault that gives AI coding agents persistent memory.
AutoGineer overview, from the brain’s own files
Obsidian Mind transforms an Obsidian vault into a persistent, structured brain for AI coding agents like Claude Code, Codex, and Gemini CLI. It solves the problem of agent amnesia by maintaining a hybrid memory model that combines file-based storage with semantic search capabilities. The system uses a set of lifecycle hooks to manage agent context, including project status, meeting notes, decisions, and performance tracking. By leveraging a structured folder hierarchy and automated indexing, it ensures that agents can recall past decisions, track project progress, and maintain context across sessions. The vault is designed to be self-maintaining, with automated hygiene checks and routing logic that keeps the knowledge base organized as it grows.
How it works
Memory model: Hybrid
AutoGineer overview, from the brain’s own files
The system uses a combination of Obsidian markdown files for storage and procedural hooks for management. Lifecycle hooks handle tasks like session initialization, content classification, and vault hygiene. The vault is organized into specific folders for work, performance, organizational data, and agent-specific knowledge. Semantic search is provided via an optional QMD integration, which uses local models to index and retrieve information. Agents interact with the vault through commands and MCP tools, allowing them to read, write, and update notes while the underlying scripts ensure that the vault remains structured and linked.
| Folder | Role | Files |
|---|---|---|
| .claude | agent-config | 230 |
| .codex | agent-config | 1 |
| .gemini | agent-config | 21 |
| .github | agent-config | 11 |
| .obsidian | obsidian-config | 1 |
| brain | memory | 6 |
| templates | templates | 5 |
| .claude-plugin | folder | 2 |
| .scripts | folder | 3 |
| .shardmind | folder | 6 |
| bases | folder | 9 |
| org | folder | 3 |
| perf | folder | 4 |
| reference | folder | 1 |
| thinking | folder | 1 |
| work | folder | 6 |
The agent reads
- .claude/rules/thinking.md evidence: AGENTS.md
- work/active/ evidence: AGENTS.md
- .claude/rules/brain-topics.md evidence: AGENTS.md
- .claude/rules/vault-from-another-repo.md evidence: AGENTS.md
- perf/evidence/ evidence: AGENTS.md
- perf/ evidence: AGENTS.md
- work/ evidence: AGENTS.md
- brain/ evidence: README.md
- AGENTS.md evidence: README.md
- .gemini/commands/ evidence: README.md
- .gemini/settings.json evidence: README.md
The agent writes
- work/ evidence: AGENTS.md
- work/Index.md evidence: AGENTS.md
- perf/Brag Doc.md evidence: AGENTS.md
- brain/ evidence: AGENTS.md
- brain/Memories.md evidence: AGENTS.md
- .shardmind/ evidence: README.md
- vault-manifest.json evidence: README.md
- AGENTS.md evidence: README.md
- record_work evidence: README.md
- perf/evidence/ evidence: README.md
- .claude/agents/ evidence: README.md
- .claude/scripts/ evidence: README.md
Requirements
Apps: Obsidian
Databases: Redis, SQLite
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)
Set it up
This brain runs code automatically: 14 hooks (claude-code, codex, gemini-cli). Review .claude/settings.json, .codex/hooks.json, .gemini/settings.json before opening the folder in Claude Code. No step below turns a hook on for you.
.claude/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+17 chars].claude/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+20 chars].claude/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+18 chars].claude/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+15 chars].claude/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+18 chars].codex/hooks.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/session-start.ts".codex/hooks.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/classify-message.ts".codex/hooks.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts".codex/hooks.json:node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/stop-checklist.ts".gemini/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/session-start.ts.gemini/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/classify-message.ts.gemini/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/validate-write.ts.gemini/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/pre-compact.ts.gemini/settings.json:node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/stop-checklist.ts
Clone the repository at the commit AutoGineer scanned:
git clone https://github.com/breferrari/obsidian-mind.git && cd obsidian-mind && git checkout fae7be467fc5e23bf9d51df7207d41f0c07e2754In Obsidian, choose “Open folder as vault” and pick the folder.
Point Claude Code at .claude-plugin/marketplace.json: it does not read that file on its own.
cd obsidian-mind && claude
AutoGineer scanned these files at commit fae7be4.
- Not scanned by AutoGineerThe author’s MCP configuration (README.md) also starts it in a way AutoGineer does not offer. Read that file: AutoGineer did not scan that path; what it runs is listed under “This brain runs”. https://github.com/breferrari/obsidian-mind/blob/fae7be467fc5e23bf9d51df7207d41f0c07e2754/README.md
- Not scanned by AutoGineerThe author’s README also describes installing it from a clone of its repository. Read its install section: AutoGineer did not scan that path. https://github.com/breferrari/obsidian-mind/blob/fae7be467fc5e23bf9d51df7207d41f0c07e2754/README.md#-install-via-shardmind-recommended
- Not scanned by AutoGineerThe author also offers https://github.com/breferrari/obsidian-mind/tree/fae7be467fc5e23bf9d51df7207d41f0c07e2754. https://github.com/breferrari/obsidian-mind/tree/fae7be467fc5e23bf9d51df7207d41f0c07e2754
First committed by breferrari. Published in breferrari/obsidian-mind. Licence: MIT License.
Usage
AutoGineer overview, from the brain’s own files
- Start a new session to load project context and North Star goals.
- Capture meeting takeaways and decisions using automated commands.
- Query the vault for past decisions or project history using semantic search.
- Perform end-of-day wrap-ups to index new notes and identify uncaptured wins.
- Manage incident response and documentation within the vault structure.
- Maintain performance records and brag documents for review cycles.
- “/om-standup”
- The agent loads the North Star goals, active projects, and recent tasks to provide a summary of current work status.
- “/om-dump Just had a 1:1 with Sarah. She wants error monitoring added before release.”
- The agent updates the person note for Sarah, creates a meeting record, and adds an error monitoring task to the active project note.
- “What did we decide about caching?”
- The agent uses semantic search to retrieve the specific decision record regarding the Redis migration.
- “wrap up”
- The agent verifies note links, updates indexes, and identifies uncaptured wins for the brag document.
Documentation by breferrari
<p align="center"> <img src="obsidian-mind-logo.png" alt="Obsidian Mind" width="120"> </p>
<h1 align="center">Obsidian Mind</h1>
Image: Claude Code Image: Codex CLI Image: Gemini CLI Image: Obsidian Image: Obsidian CLI Image: Obsidian Skills Image: QMD Image: Node Image: License
An Obsidian vault that gives AI coding agents persistent memory. Built for Claude Code, with working hooks for Codex CLI and Gemini CLI. Start a session, talk about your day, and the agent handles the rest — notes, links, indexes, performance tracking. Every conversation builds on the last.
🔴 The Problem
AI coding agents are powerful, but they forget. Every session starts from zero — no context on your goals, your team, your patterns, your wins. You re-explain the same things. You lose decisions made three conversations ago. The knowledge never compounds.
🟢 The Solution
Give your agent a brain.
You: "start session"
Agent: *reads North Star, checks active projects, scans recent memories*
Agent: "You're working on Project Alpha, blocked on the BE contract.
Last session you decided to split the coordinator. Your 1:1
with your manager is tomorrow — review brief is ready."Works with Claude Code (full support), Codex CLI, and Gemini CLI — same hooks, same commands, same vault.
Install via shardmind install or git clone — same vault either way.
⚡ See It In Action
<p align="center"> <img src="obsidian-mind-demo.gif" alt="Obsidian Mind demo — standup and dump commands" width="800"> </p>
Morning kickoff:
/om-standup
# → loads North Star, active projects, open tasks, recent git changes
# → "You have 2 active projects. The auth refactor is blocked on API contract.
# Your 1:1 with Sarah is at 2pm — last time she flagged observability."Brain dump after a meeting:
/om-dump Just had a 1:1 with Sarah. She's happy with the auth work but wants
us to add error monitoring before release. Also, Tom mentioned the cache
migration is deferred to Q2 — we decided to focus on the API contract first.
Decision: defer Redis migration. Win: Sarah praised the auth architecture.→ Updated org/people/Sarah Chen.md with meeting context
→ Created work/1-1/Sarah 2026-03-26.md with key takeaways
→ Created Decision Record: "Defer Redis migration to Q2"
→ Added to perf/Brag Doc.md: "Auth architecture praised by manager"
→ Updated work/active/Auth Refactor.md with error monitoring taskIncident response:
/om-incident-capture https://slack.com/archives/C0INCIDENT/p123456
# → slack-archaeologist reads every message, thread, and profile
# → people-profiler creates notes for new people involved
# → Full timeline, root cause analysis, brag doc entryEnd of day:
You: "wrap up"
# → verifies all notes have links
# → updates indexes
# → brag-spotter finds uncaptured wins
# → suggests improvements🚀 Quick Start
📦 Install via ShardMind (recommended)
npm install -g shardmind
mkdir my-vault && cd my-vault
shardmind install github:breferrari/obsidian-mindshardmind install writes into the current directory, so create and enter a fresh folder first. The wizard collects your name, organization, vault purpose, agents to include, and whether to enable QMD; ShardMind then initializes git, optionally bootstraps QMD, and personalizes brain/North Star.md with your answers. Then:
Open the installed folder as an Obsidian vault
Enable the Obsidian CLI in Settings → General (requires Obsidian 1.12+)
Run your agent in the vault directory:
claude,codex, orgemini. Codex runs the vault's hooks only once the folder is trusted and each hook approved: see Using with Other Agents.Start talking about work
ShardMind is the package manager for Obsidian vault templates. The install adds a .shardmind/ sidecar that powers the wizard, optional modules (skip what you don't use), and three-way-merge upgrades. With every value at its default the install is byte-equivalent to git clone — clone-UX is preserved exactly. Delete .shardmind/ and shard-values.yaml from the installed vault and it keeps working: ShardMind is additive, not load-bearing.
Or clone directly
git clone https://github.com/breferrari/obsidian-mind.gitOr use it as a GitHub template. Skip the wizard, get the bare template. Then run through the same 4 steps above, plus fill in brain/North Star.md with your goals (the ShardMind wizard does this for you).
🔍 Recommended: QMD Semantic Search
QMD is where most of the agent's retrieval intelligence comes from. Optional in the strict sense — the vault falls back to grep + the Obsidian CLI — but the experience is meaningfully better with it:
Semantic recall. Find "what did we decide about caching" even when the note is titled "Redis Migration ADR."
Brain topics available on demand. Your agent is instructed (via
AGENTS.md, which points to.claude/rules/brain-topics.md) to consultbrain/guidance through QMD when the conversation touches a listed topic.Subagents get sharper context.
context-loader,review-prep,brag-spotter, and friends consult QMD first, then fall back to grep.Native agent tools via MCP. Registered as a Model Context Protocol server in
.mcp.json— when QMD is installed,mcp__qmd__query,mcp__qmd__get, andmcp__qmd__multi_getappear in the agent's tool menu alongside Read and Edit. Subagents, slash commands, and the main conversation all call the same typed contract. Add another MCP-aware tool later (a database, a ticketing system, a calendar) and it plugs in the same way.
npm install -g @tobilu/qmd
node --experimental-strip-types .scripts/qmd-bootstrap.tsThe bootstrap is idempotent — safe to re-run. It resolves this vault's index name — the qmd_index field from vault-manifest.json when set, otherwise the vault folder name slugified — reads qmd_context, registers the collection, attaches the context, and builds the index + embeddings. The SessionStart hook and .mcp.json wrapper both read the same manifest field, so CLI queries, the MCP server, and the re-index all scope to the same named SQLite store. This isolates the vault from any other QMD-using vault on the same machine.
If you want to use a different index name (for example, one vault per engineer on a shared workstation), edit qmd_index in vault-manifest.json before running the bootstrap. Once the store is populated, always pass --index <name> to the CLI:
qmd --index obsidian-mind query "what did we decide about caching"
qmd --index obsidian-mind update # after bulk edits
qmd --index obsidian-mind embed # after many new notesHow it works under the hood
QMD runs three small models locally, so there is no API key to set up, no per-query cost, and it works offline:
| model | size | job |
|---|---|---|
embeddinggemma-300M | ~328MB | turns notes and queries into vectors |
qmd-query-expansion-1.7B | ~1.28GB | rewrites your query into better search terms |
Qwen3-Reranker-0.6B | ~640MB | reorders the shortlist by actual relevance |
They download on first use and are cached. QMD offloads to the GPU when it finds one — CUDA on a discrete card, Metal on Apple Silicon — and falls back to CPU otherwise. Check what yours is doing with qmd doctor.
Use qmd 2.5.1 or later. In 2.1, qmd status probes the GPU, and on a machine without one that can take several seconds (4 to 37 s on CI runners, measured 2026-10-13, #349). SessionStart's self-heal reads qmd status under a 5-second limit, so a status that times out leaves it unable to see a broken install.
The three CLI verbs map onto that stack, cheapest first: qmd search is BM25 keywords with no model at all, qmd vsearch is vector-only, and qmd query is the full hybrid. If you want to avoid the larger downloads, search alone is genuinely useful.
What that means for the MCP server
The om server sends a lexical and a vector sub-query, so retrieval finds the note that answers your question even when it shares no keywords with it. Practical consequences worth knowing:
Reads are the expensive side, not writes. A query embeds locally before it can search, so
recallwith a query takes a couple of seconds whilerecallwithout one is near-instant.searchover notes is fast — it is the vector step that costs.Writing a memory does not wait for the model. The index update is synchronous, so a new memory is immediately retrievable; generating its vector happens in the background, because that only affects where it ranks, not whether it is found.
No index, no problem. Without QMD the server falls back to lexical matching. Ordering gets worse; nothing disappears.
NOTE
If QMD isn't installed, everything still works — the agent falls back to grep and the Obsidian CLI, and the MCP server entry is skipped with a harmless warning.
📋 Requirements
Obsidian 1.12+ (for CLI support)
An AI coding agent: Claude Code (full support), Codex CLI, or Gemini CLI
Node 22+ LTS (for hook scripts — typically already installed alongside Claude Code / Codex / Gemini CLI)
Git (for version history)
QMD (optional, for semantic search)
Note on the Node flag. Hook scripts execute TypeScript directly via Node's
--experimental-strip-typesflag, stable in Node 22.6+ (Aug 2024) and the default behaviour in Node 23.6+. The flag is marked experimental but has been unchanged across 22 LTS and 24 LTS; if a future Node release retires or renames it, hook commands in.claude/settings.json,.codex/hooks.json, and.gemini/settings.jsonneed a one-line update.
⚙️ How It Works
Procedural code owns the environment. The agent owns content. The hooks in .claude/scripts/ handle classification, validation, indexing, and lifecycle injection — deterministic, testable, runs the same for every agent. Writing notes, filing them, linking them, drafting briefs — those are judgments, and they stay with the agent. The two halves meet at small handoffs (hooks inject context, agent reads the vault) so neither has to do the other's job.
Folders group by purpose. Links group by meaning. A note lives in one folder (its home) but links to many notes (its context). Your agent maintains this graph — linking work notes to people, decisions, and competencies automatically. When review season arrives, the backlinks on each competency note are already the evidence trail. A note without links is a bug.
Vault-first memory keeps context across sessions and machines. All durable knowledge lives in brain/ topic notes (git-tracked, Obsidian-browsable, linked). Claude Code's MEMORY.md (~/.claude/) is an auto-loaded index that points to vault locations — never the storage itself. This means memories survive machine changes and are part of the graph.
Sessions have a designed lifecycle. The SessionStart hook auto-injects your North Star goals, active projects, recent changes, open tasks, and the full vault file listing — your agent starts every session with context, not a blank slate. At the end, say "wrap up" and the agent runs /om-wrap-up — verifying notes, updating indexes, and spotting uncaptured wins. The AGENTS.md operating manual governs everything in between: where to file things, how to link, when to split a note, what to do with decisions and incidents.
🔗 Hooks
The lifecycle hooks handle routing automatically:
| Hook | When | What |
|---|---|---|
| 🚀 SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star focus, active work, recent changes, tasks, file listing, vault-hygiene drift flags — held under a byte budget that fits Claude Code's hook output cap, ending with an injection-size meter |
| 💬 UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints; also hands the agent the Stop report from the previous turn |
| ✍️ PostToolUse | After writing .md | Validates frontmatter + wikilinks, blocks misplaced memory files, flags oversized notes (split, don't trim) and write-time topic clusters |
| 💾 PreCompact | Before context compaction | Backs up session transcript to thinking/session-logs/ |
| 🏁 Stop | After every response | Checklist + concrete drift findings (same hygiene scan as SessionStart), shown once per session and again only when they change: you see a short summary, one line per section, and the agent gets the full report with your next message and decides whether to act; hands drift to om-tidy |
TIP
You just talk. The hooks handle the routing.
🧩 The Claude Code mod
On Claude Code 2.1.287 or later, the vault also ships a mod: .claude/skills/obsidian-mind/, a plugin whose code runs inside Claude Code. It runs the vault's own hook scripts and changes only how their output reaches the session:
Session context arrives as an instruction file, the way
AGENTS.mddoes. It is re-read whole after compaction and/clear(as hook output it shrinks to a pointer), it reaches general-purpose subagents (hook output never does), and it is not cut at Claude Code's 10,000-character hook limit. Its budget iseager_layer_instruction_budget_bytesinvault-manifest.json; sections that never shrink, such as open tasks, can still take it past that./memorylists it as.claude/session-context.md.The Stop report becomes one line under the answer. When the findings change you see a line beneath Claude's reply, starting with the mod's name —
obsidian-mind: vault check: …. Claude Code joins the names of the plugins that answered on Stop with+, so when another plugin also answers, the label readsobsidian-mind+<plugin>: vault check: …. Claude gets the full report with your next message, unseen. A finding marked urgent gets Claude's attention at once instead, once per message you send (a second one waits inside the report); the template's own report has none.
For each event it handles, the mod tells the matching hook to stand down. Wherever the mod does not load, the hooks run exactly as before: Codex and Gemini, older Claude Code, a session started in a vault subfolder (launch from the vault root, or /cd there and /clear), or a folder you have not trusted. It loads only after you accept Claude Code's trust prompt for the vault.
A mod is unsandboxed code that runs with your permissions, so check what it does before trusting the folder: claude plugin validate .claude/skills/obsidian-mind lists every event it hooks and every call it makes (it runs the vault's own scripts, writes the context file, remembers in its own store which report each session was shown, and can submit a prompt for an urgent finding, nothing else). To turn it off, add "enabledPlugins": { "obsidian-mind@skills-dir": false } to .claude/settings.local.json.
<!-- mod-validate:start -->
The two lines that matter in its output, for this version of the mod:
❯ ./register.ts hooks: classic.SessionStart, prompt.context, classic.Stop, turn.complete, prompt.submit, turn.start
❯ ./register.ts calls: $.fs.write, $.process.run (via runScript), $.prompt.submit, $.session.root, $.state.get, $.state.set, $.store.get (via setShown, shownFor), $.store.set (via setShown), $.ui.invalidate<!-- mod-validate:end -->
⚡ Token Efficiency
obsidian-mind does not dump your entire vault into context. It uses tiered loading to keep token costs low:
| Tier | What | When | Cost |
|---|---|---|---|
| Always | AGENTS.md (plus .claude/rules/ on Claude Code) + SessionStart context (North Star excerpt, git summary, tasks, vault file listing) | Session start | capped by the manifest budget, itself held under Claude Code's 10,000-character hook output cap; the meter reports the real size every session |
| On-demand | QMD semantic search results | When the agent needs specific context | Targeted |
| Triggered | Classification routing hints | Every message | ~100 tokens |
| Triggered | PostToolUse validation | After .md writes | ~200 tokens |
| Rare | Full file reads | Only when explicitly needed | Variable |
SessionStart loads lightweight context — small excerpts from key files, filenames, and git summary — not full note contents. Five mechanisms keep the eager layer honest as the vault grows: source-aware injection (resume/compact re-inject only volatile sections — the static bulk is already in-conversation), an injection-size meter as the last line of every injection (you always see what context costs), an injection budget that enforces what the meter measures (over the ceiling, the cheapest-to-lose sections degrade to pointers — and the meter names every one it dropped, because a silent loss is worse than the bloat), a single hook spawn per write (the QMD refresh rides the validation hook), and listing collapse (any folder past a note-count threshold folds to one count line, so a vault can't outgrow the ceiling through whichever folder nobody thought to configure). Both the budget and the threshold are tunable in vault-manifest.json, and the budget is held under Claude Code's 10,000-character hook output cap whatever it is set to, because past the cap a session receives only a 2,000-character preview. The agent queries by meaning via QMD before reading files, so it pulls only what's relevant. The classification hook is one lightweight Node call per message. The validation hook only fires on markdown writes and skips excluded paths.
🌐 Using with Other Agents
obsidian-mind works with Claude Code, Codex CLI, Gemini CLI, Antigravity and Grok. Every agent reads one instruction file, AGENTS.md. The hook scripts in .claude/scripts/ and the commands in .claude/commands/ are agent-agnostic — pure Markdown, TypeScript, and shell with no SDK dependencies. .claude/rules/ holds guidance only Claude Code can use (its skills, subagents, auto-memory index, hooks and mod), and the sections AGENTS.md moved out to stay under its size cap. Claude Code and Grok load every file there at session start, so Claude keeps the whole manual; the other agents read a moved section when AGENTS.md points them to it.
| Agent | Reads AGENTS.md | From a vault subfolder | Also loads | Known gaps |
|---|---|---|---|---|
| Claude Code | Natively, when no CLAUDE.md is present | Yes, but @ imports are dropped (upstream) | .claude/rules/*.md | A CLAUDE.md beside or above AGENTS.md is read instead, silently: see Troubleshooting |
| Codex CLI | Natively | Yes (walks up to the git root) | — | Stops reading past ~32 KiB, silently |
| Gemini CLI | Through .gemini/settings.json (context.fileName) | No: see Troubleshooting | — | What a live session does with it is not yet observed (TBC) |
| Antigravity | Natively | Yes | — (not .claude/rules/, not CLAUDE.md) | Stops reading past ~24,000 bytes, silently. Has a workspace-trust dialog; whether it gates AGENTS.md is TBC (a headless -p run loaded it in a never-opened folder). Its .agents/ manifests are not exercised here (TBC) |
| Grok | Once the folder is trusted | Yes, once trusted | .claude/rules/*.md and CLAUDE.md, plus project .claude/settings.json hooks and user-level ~/.claude skills, permissions and hooks | An untrusted folder gets no project instructions at all: see Troubleshooting |
Observed with scratch vaults as of 2026-10-06 (Claude Code 2.1.291, Codex CLI 0.160.0, Gemini CLI 0.37.1 discovery log, Antigravity 1.3.0, Grok 1.0.46); the measurements are in #321. A test keeps AGENTS.md under 22,000 bytes, so no agent cuts it off.
Claude Code — full support. Hooks, commands, subagents, and the memory system all work out of the box.
Codex CLI — hook config at .codex/hooks.json wires the same hook scripts Claude Code uses — session context, message classification, and write validation work automatically. Commands work as regular prompts (e.g. type om-standup without the / prefix).
Codex runs a project's hooks only once two kinds of trust are in place (observed with Codex CLI 0.160.0 as of 2026-10-13, #345):
The vault folder is trusted. Codex records this in
~/.codex/config.tomlunder[projects.'<path>']. On Windows the key is the\\?\-prefixed path, e.g.[projects.'\\?\C:\path\to\vault'].Each hook is approved. Codex stores each approval as a
trusted_hashunder[hooks.state]. Approving them in an interactivecodexsession is expected to write these (inferred: the #345 check stood in for them with--dangerously-bypass-hook-trust, a flag for one non-interactive run).
Until both are in place, Codex runs no hook, and the session gets no vault context.
Gemini CLI — hook config at .gemini/settings.json maps Gemini's event names to the shared hook scripts, and its context.fileName setting points Gemini at AGENTS.md. Gemini reads custom commands only as TOML, so .gemini/commands/ holds a generated wrapper per command that injects the command's .md (node --experimental-strip-types .scripts/gemini-commands.ts regenerates them).
Antigravity and Grok — read AGENTS.md for vault conventions. Their hook, skill and command layers are tracked in #322 and #323.
Other agents (Cursor, Windsurf, GitHub Copilot, JetBrains AI) — read AGENTS.md for vault conventions. Hook support varies by agent.
NOTE
Hooks, commands, subagent prompts, and vault memory (brain/) are all agent-agnostic. Only the~/.claude/auto-memory loader and theobsidian-mindmod are Claude Code-specific..claude/rules/hooks-per-agent.mdmaps each hook to each agent's event.
🧠 Reach Your Vault From Any Repo
Your vault normally only helps while you are sitting in it. The om MCP server changes that: a coding session in any other repository can search your notes, read them, follow the graph, and record what it learned back into the vault.
Step 1 — register the server once, for every repo
claude mcp add --scope user om node "/absolute/path/to/your-vault/.claude/scripts/om-mcp.mjs"User scope is the right default here: it registers in your own config, so the server is available in every directory on the machine with nothing added to any repository. No env var is needed either, because the launcher resolves the vault from its own location.
<details> <summary>Per-repo alternative, and one trap to avoid</summary>
If you would rather a specific repo carry the wiring (so a teammate gets it on clone), put it in that project's .mcp.json:
{
"mcpServers": {
"om": {
"command": "node",
"args": ["/absolute/path/to/your-vault/.claude/scripts/om-mcp.mjs"]
}
}
}Note the cost: that path is absolute and machine-specific, so committing it breaks every collaborator and every other machine of yours.
Use an absolute path, and do not copy the relative one. This vault's own .mcp.json registers qmd with a relative path (.claude/scripts/qmd-mcp.mjs). That is correct there, because a relative path resolves against the current working directory and a session in the vault is already in it. Reused for om in a consuming project, the same shape silently resolves against that project instead, and the server never starts.
</details>
Step 2 — point the consuming project at the vault
Add this to that project's own instruction file (CLAUDE.md or AGENTS.md), filling in the triggers:
## Where design decisions live
Design rationale for this project is recorded outside this repo, reachable
through the `om` MCP server.
- **`search`** reaches the written record: why a choice was made, what was
rejected, what a constraint was set against. **Start here.**
- **`expand`** shows a known note's links and backlinks, which is cheaper than
searching again for its neighbourhood.
- **`recall`** returns short durable lessons scoped to this project. It is empty
until sessions put things in it, so early on it returns nothing, and that is
*not* evidence the record is missing.
- **`health`** when something that should be there cannot be found. Every failure
in this layer looks identical from outside (no results), and this tells them
apart.
Consult the record before changing:
- <the storage format or schema>
- <the ID or key semantics>
- <the public surface: CLI flags, API shape, exported names>
If that record and this repo disagree, the record holds the *why*. Reconcile
before changing behaviour.
**Say what came back, in whatever you write before implementing:** a plan, a
design note, an issue comment. Name the recorded decisions the work rests on,
anything you found that argues *against* the approach, and an explicit "nothing
recorded on this" when the record is empty, which is a finding rather than a
blank to skip. Consulting once at the start of a task is consulting at the
moment you know least about what you will need; writing the result down moves it
to the moment you commit, while a contradiction is still free to fix.
## Recording what you learn
Two tools, and picking the wrong one is the common mistake. The test is whether
it would help someone working on a **different** project.
- **`remember`** stores a durable lesson: a constraint you discovered, a gotcha
that cost time, a rule that generalises. Set `confidence`
(`verified` / `inferred` / `unverified`) honestly and supply `verification`
when you claim `verified`. For something specific to this project use
`scope: "project"` with `projects: ["<this-repo>"]`. Reach for
`scope: "platform"` before `"general"`: a dependency's quirk or a language's
rule is platform-level however hard-won, and `general` claims it would help
someone whose stack shares nothing with yours. When you do claim `general`,
supply `generality` saying why, the same way `verification` backs `verified`.
- **`record_work`** files what happened *here*: changes, decisions and the
alternatives rejected, what was learned, what is still open, how it was
verified.
A dependency limitation that would bite any project is a `remember`. "Landed the
watch engine and here is what it cost" is a `record_work`. Do both when both are
true.Three to five triggers, and name specific nouns. Consult it before changing the storage format, ID semantics, or the CLI surface works. Check the vault for context is exactly the advisory phrasing that gets skipped, because it gives the model nothing to match against the task in front of it.
Anchor the consultation to an artifact, not to a moment. "Consult before changing X" fires once, at the start of a task, which is when the session knows least about what it will need. Requiring the result to appear in whatever the project writes before implementing turns consultation from something a session intends to do into something an artifact is incomplete without. Measured across a day of real use: captures ran roughly four times heavier than consultations, because remember fires on an event (you just learned something) while consulting fires on intention. Event-triggered behaviour happens; intention-triggered behaviour decays.
TIP
Do not lead withrecall. It returns memories, and the store is empty on a project's first session by construction:rememberrefuses when called from inside the vault, since a memory written there would be scoped to the vault and reach nobody. So memories only ever arrive from outside. A snippet that promisesrecallwill return this project's decisions therefore returns nothing on the first run, and fails silently as "no results" rather than as an error.
IMPORTANT
Both steps are required, and the second is not paperwork. Measured: with the server wired and no repo-side instruction, a session made zero vault calls and implemented a design the vault had recorded as explicitly rejected. With the instruction present, it refused and cited the note.A prohibition in the MCP
instructionsfield propagates into the calling session reliably. A positive "go consult the vault" is advisory and gets skipped whenever a nearer source exists. The server can stop a session doing something; only the project's own law makes one go looking.That asymmetry decides which side a rule belongs on, and it matters most for anything you would rather not advertise. Writing "this repo deliberately excludes X" into a public repo announces the withholding and points at exactly what is being withheld. The same rule as a prohibition in
instructionsreaches every session invisibly, and the repo says nothing at all. Routing belongs repo-side because it has to; constraints belong server-side because they can.
What the session gets: search (semantic + keyword), expand (a note's links and backlinks), recall (durable lessons scoped to that repo), remember (record a lesson), record_work (file what happened), reason (judgement across several notes), and health (is the wiring intact?). Plus your notes as readable resources.
reason is the one that thinks. The others retrieve; this one reads the vault with a second Claude session and answers questions that need judgement across notes — is what I am about to do consistent with what these six notes decided? It seeds itself from search, so you never have to search first. It runs on your own CLI default model, so the vault answers at the level you are already working at, and nothing about it is capped: it is Claude, on your machine, under your auth. Every call is logged with its cost, turns, model and wall time. Its answers are marked confidence: inferred and are never recorded as memories on their own — your session decides whether any of it is worth keeping.
Repos are identified by folder name, which is right until it isn't — two repos both called api share one identity and therefore each other's memories. Drop a .om-project file with a distinct name at the repo root to separate them; health tells you which repo it thinks is calling and where that name came from.
Cross-repo memory with an epistemic contract. A lesson learned in one repo reaches the repos it was scoped to and no others. Reach is declared at write time, never guessed at read time, so a sibling project does not inherit another's constraints. Everything recorded carries confidence: verified | inferred | unverified, dated volatile facts, and provenance derived server-side — a session cannot claim to be a project it is not. Corrections supersede rather than overwrite, so the store gets more trustworthy as it grows instead of accumulating contradictions.
Which notes it serves. Your vault, your notes, your session — the default is simply what your vault already declares as your content (user_content_roots), at the granularity you wrote it (work/active/, not all of work/). Set mcp_exposed_roots in vault-manifest.json only if this vault holds material that is not yours to share — employer-confidential notes, a client's data. A note tagged private is never served, and memories are never served as ordinary notes, since they carry their own scope. One case reads across the two: when a capture's promoted: marker carries an anchor, recall serves that block out of brain/ so a foreign repo gets the corrected version rather than the capture as first written — bounded by this same policy, so a private or withheld note is refused there too.
Every read is logged with the calling repo, so "what did that session actually see" is answerable afterwards.
NOTE
Keeping vault material out of a public PR is the contract's job, not the exposure list's — a session can read your vault directly regardless. The prohibition injected into the calling session is the part that measurably holds.
Want the mechanics? ARCHITECTURE.md → Reaching the Vault From Another Repo walks the whole layer with diagrams: the four MCP surfaces and why the non-tool ones matter, the identity handshake, a search call traced end to end, how each memory's reach is evaluated, the write path, and every failure mode against the signal that reveals it.
📅 Daily Workflow
Morning: Run /om-standup. Your agent loads your North Star, active projects, open tasks, and recent changes. You get a structured summary and suggested priorities.
Throughout the day: Talk naturally. Mention a decision you made, an incident that happened, a 1:1 you just had, a win you want to remember. The classification hook nudges the agent to file each piece correctly. For bigger brain dumps, use /om-dump and narrate everything at once.
End of day: Say "wrap up" and the agent invokes /om-wrap-up — verifies notes, updates indexes, checks links, spots uncaptured wins.
Weekly: Run /om-weekly for cross-session synthesis — North Star alignment, patterns, uncaptured wins, and next-week priorities. Run /om-vault-audit to catch orphan notes, broken links, and stale content.
Review season: Run /om-review-brief manager and get a structured review prep document with all the evidence already linked.
🛠️ Commands
Defined in .claude/commands/. Run them in Claude Code, Codex CLI, or Gemini CLI.
| Command | What It Does |
|---|---|
/om-standup | Morning kickoff — loads context, reviews yesterday, surfaces tasks, suggests priorities |
/om-dump | Freeform capture — talk naturally about anything, routes it all to the right notes |
/om-wrap-up | Full session review — verify notes, indexes, links, suggest improvements |
/om-humanize | Voice-calibrated editing — makes Claude-drafted text sound like you wrote it |
/om-weekly | Weekly synthesis — cross-session patterns, North Star alignment, uncaptured wins |
/om-capture-1on1 | Capture a 1:1 meeting transcript into a structured vault note |
/om-incident-capture | Capture an incident from Slack/channels into structured notes |
/om-slack-scan | Deep scan Slack channels/DMs for evidence |
/om-peer-scan | Deep scan a peer's GitHub PRs for review prep |
/om-review-brief | Generate a review brief (manager or peer version) |
/om-self-review | Write your self-assessment for review season — projects, competencies, principles |
/om-review-peer | Write a peer review — projects, principles, performance summary |
/om-tidy | Self-maintenance — acts on every hygiene flag: archive, group, split. Never deletes, never commits |
/om-correct | Sweep a corrected fact — applies it at the single source, links restatements, preserves dated records |
/om-vault-audit | Audit indexes, links, orphans, stale context |
/om-vault-upgrade | Upgrade this vault through ShardMind (keeps your local improvements), or import content from an existing vault — version detection, classification, migration |
/om-prep-1on1 | Prep for an upcoming 1:1 — load person context, open items, suggested agenda |
/om-meeting | Prep for any meeting by topic — subject-forward briefing with open items and considerations |
/om-intake | Process meeting notes inbox — classify and route to the right vault notes |
/om-project-archive | Move a completed project from active/ to archive/, update indexes |
🤖 Subagents
Specialized agents that run in isolated context windows. They handle heavy operations without polluting your main conversation.
| Agent | Purpose | Invoked by |
|---|---|---|
brag-spotter | Finds uncaptured wins and competency gaps | /om-wrap-up, /om-weekly |
context-loader | Loads all vault context about a person, project, or concept | Direct |
cross-linker | Finds missing wikilinks, orphans, broken backlinks | /om-vault-audit |
people-profiler | Bulk creates/updates person notes from Slack profiles | /om-incident-capture |
review-prep | Aggregates all performance evidence for a review period | /om-review-brief |
slack-archaeologist | Full Slack reconstruction — every message, thread, profile | /om-incident-capture |
vault-librarian | Deep vault maintenance — orphans, broken links, stale notes | /om-vault-audit |
review-fact-checker | Verify every claim in a review draft against vault sources | /om-self-review, /om-review-peer |
vault-migrator | Classify, transform, and migrate content from a source vault | /om-vault-upgrade |
NOTE
Subagents are defined in.claude/agents/. You can add your own for domain-specific workflows.
📊 Performance Graph
The vault doubles as a performance tracking system:
Competency notes in
perf/competencies/define your org's competency framework — one note per competencyWork notes link to competencies in their
## Relatedsection, annotated with what was demonstratedBacklinks accumulate automatically — review prep becomes reading the backlinks panel on each competency note
Brag Doc aggregates wins per quarter with links to evidence notes
/om-peer-scandeep-scans a colleague's GitHub PRs and writes structured evidence toperf/evidence//om-review-briefgenerates a full review brief by aggregating everything: brag entries, decisions, incidents, competency evidence, and 1:1 feedback
TIP
To get started: create competency notes from the template, then link your work notes to them as you go. The graph does the rest.
📋 Bases
The bases/ folder contains database views that query your notes' frontmatter properties. They update automatically as notes change.
| Base | Shows |
|---|---|
| Work Dashboard | Active projects filtered by quarter, grouped by status — plus a Stale Actives view (active but untouched 14+ days) |
| Recently Touched | Every note by real modified time — the correct answer to "what did I work on recently" (filename dates lie for living notes) |
| Incidents | All incidents sorted by severity and date |
| People Directory | Everyone in org/people/ with role, team |
| 1:1 History | All 1:1 notes sortable by person and date |
| Review Evidence | PR scans and evidence grouped by person and cycle |
| Competency Map | Competencies with evidence counts from backlinks |
| Templates | Quick access to all templates |
Home.md embeds these views, making it the vault's dashboard.
📁 Vault Structure
Home.md Vault entry point — embedded Base views, quick links
AGENTS.md Operating manual — read by every agent, every session
vault-manifest.json Template metadata — version, structure, schemas
.shardmindignore Files excluded from `shardmind install` (CONTRIBUTING, translations, marketing media)
CHANGELOG.md Version history
CONTRIBUTING.md Template development checklist
README.md Product documentation
LICENSE MIT license
bases/ Dynamic database views (Work Dashboard, Incidents, People, etc.)
work/
active/ Current projects (1–3 files at a time)
archive/YYYY/ Completed work, organized by year
incidents/ Incident docs (main note + RCA + deep dive)
1-1/ 1:1 meeting notes — named <Person> YYYY-MM-DD.md
Index.md Map of Content for all work
org/
people/ One note per person — role, team, relationship, key moments
teams/ One note per team — members, scope, interactions
People & Context.md MOC for organizational knowledge
perf/
Brag Doc.md Running log of wins, linked to evidence
brag/ Quarterly brag notes (one per quarter)
competencies/ One note per competency (link targets)
evidence/ PR deep scans, data extracts for reviews
<cycle>/ Review cycle briefs and artifacts
brain/
North Star.md Goals and focus areas — read every session
Memories.md Index of memory topics
Key Decisions.md Significant decisions and their reasoning
Patterns.md Recurring patterns observed across work
Gotchas.md Things that have gone wrong and why
Skills.md Custom workflows and slash commands
reference/ Codebase knowledge, architecture maps, flow docs
thinking/ Scratchpad for drafts — promote findings, then delete
templates/ Obsidian templates with YAML frontmatter
.claude/
rules/ Claude Code-only guidance, loaded beside AGENTS.md
commands/ 20 slash commands
agents/ 10 subagents
scripts/ Hook scripts + charcount.ts utility
skills/ Obsidian + QMD skills, and the obsidian-mind mod
settings.json 5 hooks configuration
.scripts/ Vault-level tooling — QMD bootstrap (run once on a fresh clone)
.shardmind/ ShardMind sidecar — only used if installed via `shardmind install`
shard.yaml Manifest (name, version, modules, hooks)
shard-schema.yaml Wizard values + module gating
hooks/ bootstrap (git init + QMD), personalize (North Star), post-updateNOTE
.shardmind/is additive, not load-bearing. A clone-and-open vault never reads it; only theshardmindCLI does. Delete it and the vault keeps working. See the v6 layout contract in shardmind/docs/SHARD-LAYOUT.md.
📝 Templates
Templates with YAML frontmatter, each including a description field for progressive disclosure:
Work Note — date, description, project, status, quarter, tags
Decision Record — date, description, status (proposed/accepted/deprecated), owner, context
Thinking Note — date, description, context, tags (scratchpad — delete after promoting)
Competency Note — date, description, current-level, target-level, proficiency table
1:1 Note — date, person, key takeaways, action items, quotes
Incident Note — date, ticket, severity, role, timeline, root cause, impact
🔧 What's Included
🧩 Obsidian Skills
kepano/obsidian-skills pre-installed in .claude/skills/:
obsidian-markdown — Obsidian-flavored markdown (wikilinks, embeds, callouts, properties)
obsidian-cli — CLI commands for vault operations
obsidian-bases — Database-style
.basefilesjson-canvas — Visual
.canvasfile creationdefuddle — Web page to markdown extraction
🔍 QMD Skill
A custom skill in .claude/skills/qmd/ that teaches the agent to use QMD semantic search proactively — before reading files, before creating notes (to check for duplicates), and after creating notes (to find related content that should link to it).
🎨 Customize It
This is a starting point. Adapt it to how you work:
| What | Where |
|---|---|
| Your goals | brain/North Star.md — grounds every session |
| Your org | org/ — add your manager, team, key collaborators |
| Your competencies | perf/competencies/ — match your org's framework |
| Your tools | .claude/commands/ — edit for your GitHub org, Slack workspace |
| Your conventions | AGENTS.md — the operating manual, evolve it as you go (.claude/rules/ for Claude Code-only additions) |
| Your domain | Add folders, subagents in .claude/agents/, or classification rules in .claude/scripts/ |
IMPORTANT
AGENTS.mdis the operating manual. When you change conventions, update it — your agent reads it every session.
🔄 Upgrading
Ask your agent
The easiest way — just tell your agent:
Update this vault to the latest obsidian-mind from https://github.com/breferrari/obsidian-mindThe agent will pull the latest changes, resolve conflicts, and update infrastructure files. Works with Claude Code, Codex CLI, or Gemini CLI.
Updating an existing clone
If you cloned the repo directly:
cd your-vault
git pull origin mainNew files appear automatically and hook scripts are updated in place. If you edited CLAUDE.md, the pull stops on it, because you changed a file the template deleted: move your additions out as Troubleshooting describes, then delete it.
Updating a fork
If you forked the repo:
git remote add upstream https://github.com/breferrari/obsidian-mind.git
git fetch upstream
git merge upstream/mainResolve any conflicts in files you customized (typically AGENTS.md, brain/ notes; a CLAUDE.md you edited conflicts with its deletion, see Troubleshooting). Infrastructure files (.claude/scripts/, .codex/, .gemini/) should merge cleanly.
Adopting an existing clone into ShardMind (v5.x → v6)
Already cloned obsidian-mind and want the wizard, optional modules, and three-way-merge upgrades without losing your customizations? shardmind adopt reconciles your existing vault into a managed v6 install — keeping every byte of your edits and only adding the .shardmind/ sidecar + shard-values.yaml:
npm install -g shardmind
shardmind adopt github:breferrari/obsidian-mindThe 2-way diff UI walks you through any local changes, asks per-file what to keep, then writes the engine metadata. Result: a v6-managed vault with your existing content intact, ready for shardmind update from there forward. No re-cloning.
Migrating from an older vault (or any other vault)
Using a pre-v5 obsidian-mind, or migrating from a totally different Obsidian vault? The /om-vault-upgrade command migrates your content into the latest template:
# 1. Clone the latest obsidian-mind
git clone https://github.com/breferrari/obsidian-mind.git ~/new-vault
# 2. Open it in your agent
cd ~/new-vault && claude # or codex, or gemini
# 3. Run the upgrade pointing to your old vault
/om-vault-upgrade ~/my-old-vaultThe agent will:
Detect your vault version (v1–v3.x, or identify it as a non-obsidian-mind vault)
Inventory every file — classify as user content, scaffold, infrastructure, or uncategorized
Present a migration plan — you see exactly what will be copied, transformed, and skipped
Execute after your approval — transforms frontmatter, fixes wikilinks, rebuilds indexes
Validate — checks for orphans, broken links, missing frontmatter
Your old vault is never modified. Use --dry-run to preview the plan without executing.
NOTE
Works with any Obsidian vault, not just obsidian-mind. For non-obsidian-mind vaults, the agent reads each note and classifies it semantically — routing work notes, people, incidents, 1:1s, and decisions to the right folders.
🩺 Troubleshooting
Claude Code ignores the vault's conventions. Claude Code reads a CLAUDE.md in place of AGENTS.md and skips AGENTS.md without saying so. Two ways that happens:
A leftover
CLAUDE.mdin the vault. An update keeps aCLAUDE.mdyou edited. The session hygiene flags sayCLAUDE.md present beside AGENTS.md, and/om-vault-upgradelists it under Move out. Move what you added to.claude/rules/local.md(or intoAGENTS.mdif every agent needs it, keepingAGENTS.mdunder 23 KB, where the hygiene flags start: Antigravity stops reading it at ~24,000 bytes), then deleteCLAUDE.md. Nothing is merged automatically.A
CLAUDE.mdin a folder above the vault. Claude Code reads that one too, andAGENTS.mdis skipped. The hygiene flag cannot see it, because it checks the vault root only. Move the vault out from under that folder, or move that file's content somewhere it applies only where you want it.
Gemini CLI loads no instructions when started in a vault subfolder. Gemini's context search walks up the folders, but its settings lookup does not, so a session started in a subfolder never reads the vault's .gemini/settings.json and never learns to look for AGENTS.md. Start Gemini from the vault root.
Gemini ignores what you added to GEMINI.md. Gemini now reads AGENTS.md (through .gemini/settings.json), so a leftover GEMINI.md is never loaded. The hygiene flags say GEMINI.md present beside AGENTS.md, and /om-vault-upgrade lists it under Move out. Move your additions to AGENTS.md, then delete it.
Grok reads nothing from the vault. Grok loads project instructions only from a trusted folder. Trust the vault once: run /hooks-trust in a Grok session, or launch with --trust. One grant covers MCP, LSP, hooks, project instructions and project skills.
🗺️ Roadmap
Issues and bug reports welcome. Code contributions go through assignment: comment on an issue to ask for it, and open a PR once it's assigned to you. A PR for an issue not assigned to you is closed without review. See CONTRIBUTING.md.
🙏 Design Influences
kepano/obsidian-skills — Official Obsidian agent skills
James Bedford — Vault structure philosophy, separation of AI-generated content
arscontexta — Progressive disclosure via description fields, session hooks
👤 Author
Created by Brenno Ferrari — Senior iOS Engineer in Berlin, building developer tools with Claude Code.
📄 License
MIT
.claude/scripts/tests/session-start.test.ts
Shown as plain text.
/**
* Unit tests for session-start pure helpers.
* The entry point itself (fs walk, git log, Obsidian CLI probe) is exercised
* live when the hook fires; these tests lock the deterministic formatting
* logic that doesn't need a real environment.
*/
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { join, dirname } from "node:path";
import { readFileSync, writeFileSync, mkdtempSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
import { spawnSync } from "node:child_process";
import {
take,
formatDateHeader,
quoteForPosixShell,
formatEnvExport,
formatInjectionSize,
injectionMode,
applyInjectionBudget,
shouldCollapseDir,
formatCollapsedDir,
parseInjectionBudget,
parseInstructionBudget,
DEFAULT_INSTRUCTION_BUDGET_BYTES,
effectiveInjectionBudget,
INJECTION_CEILING_BYTES,
METER_HEADROOM,
parseListingCollapseThreshold,
DEFAULT_LISTING_COLLAPSE_THRESHOLD,
type BudgetSection,
formatActiveWork,
formatRecentChanges,
isSkippedPath,
MACHINERY_DIRS,
extractFrontmatterField,
formatBrainIndex,
stripFrontmatter,
hasBrainContent,
parseQmdIndex,
parseQmdMinVersion,
isQmdNativeAbiMismatch,
qmdPackageRootFromEntry,
resolveIndexStorePath,
qmdArgsWithIndex,
isValidQmdIndex,
parseInfraRootFilenames,
isInfraFilename,
isMarkdownFilename,
collectOpenTasks,
} from "../lib/session-start.ts";
import { cutLine, envelopedLimit, fitEncoded, fitWithMeter, HOOK_OUTPUT_LIMIT, HOOK_OUTPUT_MAX_CHARS, type OutputLimit } from "../lib/hook-io.ts";
const CUT_LINE = cutLine(HOOK_OUTPUT_LIMIT);
import { rmTemp } from "./_helpers.ts";
describe("take", () => {
test("keeps first N lines", () => {
assert.equal(take("a\nb\nc\nd", 2), "a\nb");
});
test("N >= line count is a pass-through", () => {
assert.equal(take("a\nb", 10), "a\nb");
});
test("empty string stays empty", () => {
assert.equal(take("", 5), "");
});
});
describe("formatDateHeader", () => {
test("pads single-digit month and day; includes weekday", () => {
const d = new Date(2026, 3, 5, 12, 0, 0); // April 5, 2026 (Sunday)
assert.equal(formatDateHeader(d), "2026-04-05 (Sunday)");
});
test("double-digit components pass through", () => {
const d = new Date(2026, 11, 25, 12, 0, 0); // December 25, 2026 (Friday)
assert.equal(formatDateHeader(d), "2026-12-25 (Friday)");
});
});
describe("quoteForPosixShell", () => {
// One row per hazard, so a failure names the case that broke instead of
// pointing at a single combined string.
const cases: ReadonlyArray<readonly [string, string, string]> = [
["plain path", "/home/me/vault", "'/home/me/vault'"],
["variable expansion", "/a/$HOME/b", "'/a/$HOME/b'"],
["command substitution", "/a/$(id)/b", "'/a/$(id)/b'"],
["backtick substitution", "/a/`id`/b", "'/a/`id`/b'"],
["double quote", '/a/"q"/b', "'/a/\"q\"/b'"],
["command separator", "/a/;rm -rf x/b", "'/a/;rm -rf x/b'"],
// Windows paths are the common real-world case for this template, and
// backslash is literal inside single quotes.
["windows path", "C:\\Users\\me\\vault", "'C:\\Users\\me\\vault'"],
["trailing backslash", "/a/b\\", "'/a/b\\'"],
["apostrophe", "/it's/vault", "'/it'\\''s/vault'"],
["only an apostrophe", "'", "''\\'''"],
["embedded newline", "a\nb", "'a\nb'"],
["empty string", "", "''"],
];
for (const [label, input, expected] of cases) {
test(label, () => {
assert.equal(quoteForPosixShell(input), expected);
});
}
});
describe("formatEnvExport", () => {
test("emits a complete, newline-terminated export line", () => {
assert.equal(
formatEnvExport("VAULT_PATH", "/home/me/vault"),
"export VAULT_PATH='/home/me/vault'\n",
);
});
test("quoting is applied without the caller asking for it", () => {
assert.equal(
formatEnvExport("VAULT_PATH", "/a/$(id)/b"),
"export VAULT_PATH='/a/$(id)/b'\n",
);
});
test("rejects names the shell could not accept", () => {
for (const bad of ["", "1ABC", "A-B", "A B", "A;rm -rf /", "A=B", "$A"]) {
assert.throws(
() => formatEnvExport(bad, "x"),
/unsafe env var name/,
`should reject ${JSON.stringify(bad)}`,
);
}
});
test("accepts the portable name shapes", () => {
for (const ok of ["A", "_A", "VAULT_PATH", "_x9"]) {
assert.doesNotThrow(() => formatEnvExport(ok, "v"));
}
});
});
describe("session-start entry — env export cannot be hand-rolled", () => {
// A source-level guard. The safe helper only helps if it is the thing the
// entry actually calls; nothing in the type system stops someone writing
// `export FOO="${bar}"` again, which is precisely the bug #145 fixed.
const entry = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "..", "session-start.ts"),
"utf-8",
);
test("writes the env file through formatEnvExport", () => {
assert.match(entry, /appendFileSync\(\s*envFile,\s*formatEnvExport\(/);
});
// Catches a hand-rolled line in any quoting style, not just backticks.
const HANDROLLED = /["'`]export\s/;
test("contains no hand-rolled `export ...=` literal", () => {
assert.doesNotMatch(
entry,
HANDROLLED,
"build the line with formatEnvExport instead of a string literal",
);
});
test("does not reach past the helper to the raw quoter", () => {
assert.doesNotMatch(
entry,
/quoteForPosixShell\(/,
"the entry should call formatEnvExport, which quotes internally",
);
});
// SKIP_PREFIXES is module-private and the entry runs on import, so the
// wiring can only be pinned at the source level. Without this, #156
// regresses silently: MACHINERY_DIRS keeps its entries and its own tests
// keep passing while the listing walks a hardcoded list again.
const SKIP_DEF = /const SKIP_PREFIXES[^=]*=\s*\[\s*\.\.\.MACHINERY_DIRS\s*,/;
test("builds SKIP_PREFIXES from the shared machinery list (#156)", () => {
assert.match(
entry,
SKIP_DEF,
"the listing walk must spread MACHINERY_DIRS, not re-list dirs by hand",
);
});
test("GUARD IS NOT VACUOUS — the pattern rejects a hand-listed set", () => {
// The exact pre-#156 definition, which is what let .shardmind through.
const regression =
'const SKIP_PREFIXES: readonly string[] = [\n\t".git",\n\t".obsidian",\n\t"thinking",\n\t".claude",\n];';
assert.doesNotMatch(regression, SKIP_DEF, "guard must reject the old literal");
});
// A guard that cannot fail is worse than no guard: it reads as coverage
// while proving nothing. These assert the patterns above actually fire on
// the regressions they exist to catch, including the exact pre-#145 line.
test("GUARD IS NOT VACUOUS — the pattern catches every hand-rolled form", () => {
const regressions = [
'appendFileSync(envFile, `export VAULT_PATH="${cwd}"\\n`);', // the pre-#145 bug
"appendFileSync(envFile, `export VAULT_PATH=${quoteForPosixShell(cwd)}\\n`);",
'appendFileSync(envFile, "export FOO=" + bar);',
"appendFileSync(envFile, 'export FOO=' + bar);",
];
for (const bad of regressions) {
assert.match(bad, HANDROLLED, `guard must reject: ${bad}`);
}
});
test("GUARD IS NOT VACUOUS — the raw-quoter pattern catches a direct call", () => {
assert.match("const x = quoteForPosixShell(cwd);", /quoteForPosixShell\(/);
});
test("GUARD IS NOT VACUOUS — the required-call pattern rejects a missing call", () => {
const required = /appendFileSync\(\s*envFile,\s*formatEnvExport\(/;
assert.doesNotMatch("appendFileSync(envFile, someOtherThing());", required);
assert.match("appendFileSync(envFile, formatEnvExport('A', b));", required);
});
});
/**
* The quoting contract is a claim about how a real POSIX shell parses the
* output, so assert it against a real POSIX shell rather than against our own
* idea of one. Runs on Linux/macOS CI and on Windows runners that ship Git
* Bash; skips cleanly where no shell exists, so it can never be the reason
* the suite fails on an exotic platform.
*/
const posixShell = (() => {
for (const candidate of ["sh", "bash"]) {
try {
const r = spawnSync(candidate, ["-c", "printf ok"], { encoding: "utf-8" });
if (r.status === 0 && r.stdout === "ok") return candidate;
} catch {
/* not available */
}
}
return null;
})();
describe("quoteForPosixShell — verified against a real POSIX shell", () => {
const skip = posixShell === null ? "no POSIX shell on this platform" : false;
/** Round-trip every value in one shell invocation, NUL-delimited. */
function roundTrip(values: readonly string[]): string[] {
const dir = mkdtempSync(join(tmpdir(), "quote-roundtrip-"));
try {
const script = join(dir, "rt.sh");
writeFileSync(
script,
values
.map((v) => `V=${quoteForPosixShell(v)}\nprintf '%s\\0' "$V"`)
.join("\n") + "\n",
);
const r = spawnSync(posixShell as string, [script], { encoding: "utf-8" });
assert.equal(r.status, 0, `shell exited ${r.status}: ${r.stderr}`);
const parts = (r.stdout ?? "").split("\0");
parts.pop(); // trailing empty after the final delimiter
return parts;
} finally {
rmTemp(dir);
}
}
test("adversarial paths round-trip byte-exact", { skip }, () => {
const values = [
"/home/me/vault",
"/a/$HOME/b",
"/a/$(id)/b",
"/a/`id`/b",
'/a/"q"/b',
"/a/;rm -rf x/b",
"/a/&& touch x/b",
"/a/| tee x/b",
"/it's/vault",
"'",
"''",
"C:\\Users\\me\\vault",
"/a/b\\",
"/a/ spaces /b",
"/a/\t tab/b",
"/ünïcodé/路径/vault",
"/a/*/b",
"/a/~root/b",
"/a/!history/b",
"/a/#comment/b",
"/a/${IFS}/b",
"",
];
assert.deepEqual(roundTrip(values), values);
});
test("no adversarial value can execute anything", { skip }, () => {
// If substitution leaked, the marker file would exist afterwards.
const dir = mkdtempSync(join(tmpdir(), "quote-exec-"));
try {
const marker = join(dir, "EXECUTED").replaceAll("\\", "/");
roundTrip([`/a/$(touch ${marker})/b`, `/a/\`touch ${marker}\`/b`]);
assert.throws(
() => readFileSync(marker),
"quoting leaked — a command substitution executed",
);
} finally {
rmTemp(dir);
}
});
test("fuzz: generated hostile strings round-trip", { skip }, () => {
// Deterministic LCG — a flaky fuzz test is worse than none.
let seed = 0x2026_0724;
const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
const alphabet = [..."abc/ '\"`$(){}[]|&;<>*?!#~\\\t=+:,.^%@-", "\n", "é", "路"];
const values: string[] = [];
for (let i = 0; i < 120; i++) {
const len = 1 + Math.floor(rnd() * 24);
let s = "";
for (let j = 0; j < len; j++) {
s += alphabet[Math.floor(rnd() * alphabet.length)] ?? "x";
}
values.push(s);
}
assert.deepEqual(roundTrip(values), values);
});
test("formatEnvExport output is a sourceable export", { skip }, () => {
const dir = mkdtempSync(join(tmpdir(), "envexport-"));
try {
const envFile = join(dir, "env.sh");
const value = "/a/$(id)/it's \"weird\"/b";
writeFileSync(envFile, formatEnvExport("VAULT_PATH", value));
const r = spawnSync(
posixShell as string,
["-c", `. "$1"; printf '%s' "$VAULT_PATH"`, "sh", envFile],
{ encoding: "utf-8" },
);
assert.equal(r.status, 0, r.stderr);
assert.equal(r.stdout, value, "sourcing the file must restore the exact path");
} finally {
rmTemp(dir);
}
});
});
describe("formatActiveWork", () => {
test("strips .md, respects limit, returns sorted input order", () => {
const out = formatActiveWork(
["project-a.md", "project-b.md", "project-c.md"],
2,
);
assert.equal(out, "project-a\nproject-b");
});
test("filters out non-.md files", () => {
const out = formatActiveWork(
["a.md", "b.txt", "c.md", ".DS_Store"],
10,
);
assert.equal(out, "a\nc");
});
test("empty input → '(none)'", () => {
assert.equal(formatActiveWork([], 10), "(none)");
});
test("all-filtered-out → '(none)'", () => {
assert.equal(formatActiveWork(["not-markdown.txt"], 10), "(none)");
});
test("preserves `.MD` and `.Md` files (case-insensitive matching)", () => {
const out = formatActiveWork(
["Note.md", "Note.MD", "Note.Md", "notes.txt"],
10,
);
assert.equal(out, "Note\nNote\nNote");
});
});
describe("formatRecentChanges", () => {
test("filters blank lines, respects limit", () => {
const out = formatRecentChanges("abc123 one\n\ndef456 two\n\nghi789 three", 2);
assert.equal(out, "abc123 one\ndef456 two");
});
test("empty git output → '(no git history)'", () => {
assert.equal(formatRecentChanges("", 15), "(no git history)");
});
test("whitespace-only git output → '(no git history)'", () => {
assert.equal(formatRecentChanges("\n\n\n", 15), "(no git history)");
});
});
describe("isSkippedPath", () => {
const PREFIXES = [".git", ".obsidian", "thinking", ".claude"];
test("exact prefix match is skipped", () => {
assert.equal(isSkippedPath(".git", PREFIXES), true);
});
test("child of prefix is skipped", () => {
assert.equal(isSkippedPath(".claude/commands/foo.md", PREFIXES), true);
});
test("segment-boundary enforcement — .github is NOT skipped under .git", () => {
assert.equal(isSkippedPath(".github/workflow.md", PREFIXES), false);
});
test("unrelated path is not skipped", () => {
assert.equal(isSkippedPath("work/active/note.md", PREFIXES), false);
});
test("empty prefix list never skips", () => {
assert.equal(isSkippedPath(".git/foo", []), false);
});
});
describe("MACHINERY_DIRS", () => {
// The listing walk is filesystem-level and does not read .gitignore, so
// the engine's own tree has to be skipped by name.
test("skips the ShardMind engine tree an installed vault carries (#156)", () => {
// The cached template copy and every pre-update backup snapshot —
// engine artifacts that outnumbered real notes 3:1 on a v7.0.1 install.
assert.equal(
isSkippedPath(".shardmind/templates/AGENTS.md", MACHINERY_DIRS),
true,
);
assert.equal(
isSkippedPath(
".shardmind/backups/update-2026-07-01T00:00:00Z/work/Index.md",
MACHINERY_DIRS,
),
true,
);
assert.equal(isSkippedPath(".shardmind", MACHINERY_DIRS), true);
});
test("skips .github, which the segment boundary excludes from .git", () => {
assert.equal(
isSkippedPath(".github/pull_request_template.md", MACHINERY_DIRS),
true,
);
});
test("leaves user content alone", () => {
for (const p of [
"work/active/Note.md",
"brain/Patterns.md",
"templates/Work Note.md", // scaffold, but the listing does show it
]) {
assert.equal(isSkippedPath(p, MACHINERY_DIRS), false);
}
});
test("holds only what is machinery for BOTH consumers", () => {
// `thinking/` and `templates/` are each skipped by exactly one
// consumer, so neither belongs in the shared list.
assert.equal(MACHINERY_DIRS.includes("thinking"), false);
assert.equal(MACHINERY_DIRS.includes("templates"), false);
});
});
describe("extractFrontmatterField", () => {
test("extracts double-quoted string value", () => {
const content = '---\ndescription: "hello world"\ntags:\n - brain\n---\n\n# body';
assert.equal(extractFrontmatterField(content, "description"), "hello world");
});
test("extracts single-quoted string value", () => {
const content = "---\ndescription: 'hi there'\n---\n";
assert.equal(extractFrontmatterField(content, "description"), "hi there");
});
test("extracts bare value", () => {
const content = "---\ndescription: bare text here\ntags:\n - brain\n---\n";
assert.equal(extractFrontmatterField(content, "description"), "bare text here");
});
test("returns null when field is present but empty", () => {
const content = "---\ndate:\ndescription: \"x\"\n---\n";
assert.equal(extractFrontmatterField(content, "date"), null);
});
test("returns null when field is absent", () => {
const content = "---\ntags:\n - brain\n---\n";
assert.equal(extractFrontmatterField(content, "description"), null);
});
test("returns null when content has no frontmatter", () => {
assert.equal(extractFrontmatterField("# just a heading\n\nbody", "description"), null);
});
test("returns null when frontmatter is unterminated", () => {
assert.equal(extractFrontmatterField("---\ndescription: \"x\"\n", "description"), null);
});
test("ignores matches that appear only in the body", () => {
const content = "---\ntags: []\n---\n\ndescription: not frontmatter\n";
assert.equal(extractFrontmatterField(content, "description"), null);
});
test("handles CRLF line endings (Windows)", () => {
const content = '---\r\ndescription: "hello"\r\ntags: []\r\n---\r\n# body';
assert.equal(extractFrontmatterField(content, "description"), "hello");
});
test("does not mistake body line starting with --- for frontmatter terminator", () => {
const content =
'---\ndescription: "real"\n---\n\n---this-is-not-a-delimiter\n';
assert.equal(extractFrontmatterField(content, "description"), "real");
});
test("escapes regex metacharacters in field name", () => {
const content = "---\nfoo.bar: actual-value\n---\n";
assert.equal(extractFrontmatterField(content, "foo.bar"), "actual-value");
// An unescaped `.` would have matched `fooxbar:` — confirm it doesn't.
const decoy = "---\nfooxbar: decoy\n---\n";
assert.equal(extractFrontmatterField(decoy, "foo.bar"), null);
});
});
describe("stripFrontmatter", () => {
test("removes a complete frontmatter block", () => {
const out = stripFrontmatter("---\ntags: []\n---\n\n# body\n");
assert.equal(out, "\n# body\n");
});
test("leaves content without frontmatter unchanged", () => {
assert.equal(stripFrontmatter("# just a heading\n"), "# just a heading\n");
});
test("leaves unterminated frontmatter unchanged", () => {
const content = "---\ntags: []\n# never closed\n";
assert.equal(stripFrontmatter(content), content);
});
test("handles CRLF line endings", () => {
const out = stripFrontmatter("---\r\ntags: []\r\n---\r\n# body\r\n");
assert.equal(out, "# body\r\n");
});
test("does not mistake body line starting with --- for terminator", () => {
const content = "---\ntags: []\n---\n\n---this-is-body\n";
assert.equal(stripFrontmatter(content), "\n---this-is-body\n");
});
});
describe("hasBrainContent", () => {
test("false when only a bare-hyphen placeholder exists", () => {
assert.equal(hasBrainContent("\n# Gotchas\n\nSome intro.\n\n-\n"), false);
});
test("true for a bullet with text", () => {
assert.equal(hasBrainContent("- first real gotcha\n"), true);
});
test("true for indented bullets", () => {
assert.equal(hasBrainContent(" - nested item\n"), true);
});
test("true for asterisk and plus markers", () => {
assert.equal(hasBrainContent("* item\n"), true);
assert.equal(hasBrainContent("+ item\n"), true);
});
test("false for empty body", () => {
assert.equal(hasBrainContent(""), false);
});
test("false for prose-only content with no bullets", () => {
assert.equal(hasBrainContent("Just a paragraph of prose.\n"), false);
});
});
describe("parseQmdIndex", () => {
test("extracts qmd_index when present as a non-empty string", () => {
const manifest = JSON.stringify({ qmd_index: "obsidian-mind" });
assert.equal(parseQmdIndex(manifest), "obsidian-mind");
});
test("returns null when qmd_index is an empty string", () => {
const manifest = JSON.stringify({ qmd_index: "" });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index is missing from the manifest", () => {
const manifest = JSON.stringify({ template: "obsidian-mind" });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index is not a string", () => {
const manifest = JSON.stringify({ qmd_index: 42 });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when the manifest source is null (missing file)", () => {
assert.equal(parseQmdIndex(null), null);
});
test("returns null when the manifest is malformed JSON", () => {
assert.equal(parseQmdIndex("{ not json"), null);
});
test("returns null when the manifest parses to a non-object", () => {
assert.equal(parseQmdIndex('"just a string"'), null);
});
test("returns null when qmd_index contains a forward-slash path separator", () => {
const manifest = JSON.stringify({ qmd_index: "vault/subdir" });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index contains a backslash path separator", () => {
const manifest = JSON.stringify({ qmd_index: "vault\\subdir" });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index is a parent-dir escape attempt", () => {
const manifest = JSON.stringify({ qmd_index: "../../etc/passwd" });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index contains whitespace", () => {
const manifest = JSON.stringify({ qmd_index: "my vault" });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index is whitespace-only", () => {
const manifest = JSON.stringify({ qmd_index: " " });
assert.equal(parseQmdIndex(manifest), null);
});
test("returns null when qmd_index starts with a non-alphanumeric character", () => {
const manifest = JSON.stringify({ qmd_index: "-leading-dash" });
assert.equal(parseQmdIndex(manifest), null);
});
test("accepts dash, dot, and underscore inside the name", () => {
const manifest = JSON.stringify({ qmd_index: "vault-a_b.2" });
assert.equal(parseQmdIndex(manifest), "vault-a_b.2");
});
});
describe("isValidQmdIndex", () => {
test("accepts standard names", () => {
assert.equal(isValidQmdIndex("obsidian-mind"), true);
assert.equal(isValidQmdIndex("vigil"), true);
assert.equal(isValidQmdIndex("vault.2_final"), true);
});
test("rejects path separators, whitespace, empty, and leading punctuation", () => {
assert.equal(isValidQmdIndex(""), false);
assert.equal(isValidQmdIndex(" "), false);
assert.equal(isValidQmdIndex("a b"), false);
assert.equal(isValidQmdIndex("a/b"), false);
assert.equal(isValidQmdIndex("a\\b"), false);
assert.equal(isValidQmdIndex("../x"), false);
assert.equal(isValidQmdIndex("-leading"), false);
assert.equal(isValidQmdIndex(".leading"), false);
});
test("rejects non-string values", () => {
assert.equal(isValidQmdIndex(undefined), false);
assert.equal(isValidQmdIndex(null), false);
assert.equal(isValidQmdIndex(42), false);
assert.equal(isValidQmdIndex({}), false);
});
});
describe("qmdArgsWithIndex", () => {
test("prepends --index <name> when an index is provided", () => {
assert.deepEqual(qmdArgsWithIndex("obsidian-mind", ["update"]), [
"--index",
"obsidian-mind",
"update",
]);
});
test("returns subcommand args unchanged when index is null", () => {
assert.deepEqual(qmdArgsWithIndex(null, ["update"]), ["update"]);
});
test("preserves multi-arg subcommand invocations", () => {
assert.deepEqual(
qmdArgsWithIndex("vault", ["query", "ShardMind", "--json"]),
["--index", "vault", "query", "ShardMind", "--json"],
);
});
test("returns a fresh array (does not mutate the input)", () => {
const input = ["update"];
const out = qmdArgsWithIndex(null, input);
assert.notEqual(out, input);
assert.deepEqual(out, input);
});
});
describe("isQmdNativeAbiMismatch", () => {
test("detects a NODE_MODULE_VERSION mismatch message", () => {
assert.equal(
isQmdNativeAbiMismatch(
"Error: The module '.../better_sqlite3.node'\nwas compiled against a different Node.js version using\nNODE_MODULE_VERSION 141. This version of Node.js requires\nNODE_MODULE_VERSION 147.",
),
true,
);
});
test("detects the ERR_DLOPEN_FAILED error code alone", () => {
assert.equal(isQmdNativeAbiMismatch("code: 'ERR_DLOPEN_FAILED'"), true);
});
test("returns false for unrelated stderr", () => {
assert.equal(isQmdNativeAbiMismatch(""), false);
assert.equal(isQmdNativeAbiMismatch("command not found: qmd"), false);
});
});
describe("qmdPackageRootFromEntry", () => {
test("strips dist/cli/qmd.js to return the package root", () => {
const root = join("/opt/homebrew/lib/node_modules", "@tobilu", "qmd");
const entry = join(root, "dist", "cli", "qmd.js");
assert.equal(qmdPackageRootFromEntry(entry), root);
});
test("returns null for a null entry", () => {
assert.equal(qmdPackageRootFromEntry(null), null);
});
test("returns null when the entry doesn't match the expected shape", () => {
assert.equal(qmdPackageRootFromEntry("/some/other/path.js"), null);
});
});
describe("parseQmdMinVersion", () => {
test("extracts a declared min version", () => {
assert.equal(
parseQmdMinVersion(JSON.stringify({ qmd_min_version: "2.0.0" })),
"2.0.0",
);
});
test("null when absent, empty, non-string, or manifest malformed", () => {
assert.equal(parseQmdMinVersion(JSON.stringify({})), null);
assert.equal(
parseQmdMinVersion(JSON.stringify({ qmd_min_version: "" })),
null,
);
assert.equal(
parseQmdMinVersion(JSON.stringify({ qmd_min_version: 2 })),
null,
);
assert.equal(parseQmdMinVersion("not json"), null);
assert.equal(parseQmdMinVersion(null), null);
});
});
describe("isMarkdownFilename", () => {
test("accepts lowercase .md", () => {
assert.equal(isMarkdownFilename("note.md"), true);
});
test("accepts uppercase .MD (case-insensitive filesystem reality)", () => {
assert.equal(isMarkdownFilename("PROJECT.MD"), true);
});
test("accepts mixed-case .Md and .mD", () => {
assert.equal(isMarkdownFilename("Daily.Md"), true);
assert.equal(isMarkdownFilename("notes.mD"), true);
});
test("rejects non-markdown extensions", () => {
assert.equal(isMarkdownFilename("note.txt"), false);
assert.equal(isMarkdownFilename("note.markdown"), false);
assert.equal(isMarkdownFilename("note.mdx"), false);
});
test("rejects bare names without an extension", () => {
assert.equal(isMarkdownFilename(""), false);
assert.equal(isMarkdownFilename("md"), false);
assert.equal(isMarkdownFilename("note"), false);
});
test("rejects names where .md appears mid-string", () => {
assert.equal(isMarkdownFilename("note.md.bak"), false);
assert.equal(isMarkdownFilename(".mdrc"), false);
});
});
describe("parseInfraRootFilenames", () => {
test("returns empty when manifest is null", () => {
assert.deepEqual(parseInfraRootFilenames(null), []);
});
test("returns empty when JSON is malformed", () => {
assert.deepEqual(parseInfraRootFilenames("{ not json"), []);
});
test("returns empty when parsed value is not an object", () => {
assert.deepEqual(parseInfraRootFilenames('"a string"'), []);
assert.deepEqual(parseInfraRootFilenames("null"), []);
});
test("returns empty when infrastructure field is absent", () => {
assert.deepEqual(parseInfraRootFilenames(JSON.stringify({})), []);
});
test("returns empty when infrastructure field is not an array", () => {
assert.deepEqual(
parseInfraRootFilenames(JSON.stringify({ infrastructure: "AGENTS.md" })),
[],
);
});
test("returns only the root-level entries (filters out anything containing '/')", () => {
const manifest = JSON.stringify({
infrastructure: [
"AGENTS.md",
"README.*.md",
".claude/**",
"templates/**",
"Home.md",
],
});
assert.deepEqual(parseInfraRootFilenames(manifest), [
"AGENTS.md",
"README.*.md",
"Home.md",
]);
});
test("filters out non-string entries silently", () => {
const manifest = JSON.stringify({
infrastructure: ["AGENTS.md", 42, null, "Home.md"],
});
assert.deepEqual(parseInfraRootFilenames(manifest), [
"AGENTS.md",
"Home.md",
]);
});
});
describe("isInfraFilename", () => {
// Mirrors the vault-manifest.json shape: literal entries for the canonical
// names plus a glob for localized README variants. Both forms must work.
const patterns = ["AGENTS.md", "README.md", "README.*.md", "Home.md"];
test("matches literal filenames exactly", () => {
assert.equal(isInfraFilename("AGENTS.md", patterns), true);
assert.equal(isInfraFilename("README.md", patterns), true);
assert.equal(isInfraFilename("Home.md", patterns), true);
});
test("rejects close-but-not-equal filenames", () => {
assert.equal(isInfraFilename("claude.md", patterns), false); // case-sensitive
assert.equal(isInfraFilename("AGENTS.md.bak", patterns), false);
assert.equal(isInfraFilename("MY-AGENTS.md", patterns), false);
});
test("glob patterns match the localized variants they target", () => {
assert.equal(isInfraFilename("README.ja.md", patterns), true);
assert.equal(isInfraFilename("README.zh-CN.md", patterns), true);
});
test("bare * pattern matches every filename — documented footgun", () => {
// If a user writes `"infrastructure": ["*"]` in vault-manifest.json,
// every root-level file is treated as infra and openTasks empties out.
// The behavior is "you asked, you get" — but locked here so a future
// stricter parser doesn't silently regress this corner.
assert.equal(isInfraFilename("anything.md", ["*"]), true);
assert.equal(isInfraFilename("", ["*"]), true);
});
test("multiple wildcards in one pattern", () => {
assert.equal(isInfraFilename("foo.bar.md", ["*.bar.*"]), true);
assert.equal(isInfraFilename("foo.qux.md", ["*.bar.*"]), false);
});
test("escapes regex metacharacters in literal segments of patterns", () => {
// `.` in `AGENTS.md` must not match `AGENTSxmd`
assert.equal(isInfraFilename("AGENTSxmd", patterns), false);
});
test("returns false on empty pattern list", () => {
assert.equal(isInfraFilename("AGENTS.md", []), false);
});
test("user content files are not infra", () => {
assert.equal(isInfraFilename("2026-05-18.md", patterns), false);
assert.equal(isInfraFilename("my-project.md", patterns), false);
});
});
describe("collectOpenTasks", () => {
test("aggregates tasks grouped by source, preserving input order", () => {
const sources = [
{ path: "work/active/a.md", content: "- [ ] task A1\n- [ ] task A2" },
{ path: "work/active/b.md", content: "- [ ] task B1" },
];
assert.equal(
collectOpenTasks(sources, 10),
"work/active/a.md\n- [ ] task A1\n- [ ] task A2\n\nwork/active/b.md\n- [ ] task B1",
);
});
test("skips sources with no unchecked tasks", () => {
const sources = [
{ path: "a.md", content: "# Heading\n\nprose only" },
{ path: "b.md", content: "- [ ] real task" },
];
assert.equal(collectOpenTasks(sources, 10), "b.md\n- [ ] real task");
});
test("ignores checked tasks (both [x] and [X])", () => {
const sources = [
{
path: "a.md",
content: "- [ ] open\n- [x] done\n- [X] also done\n- [ ] still open",
},
];
assert.equal(
collectOpenTasks(sources, 10),
"a.md\n- [ ] open\n- [ ] still open",
);
});
test("preserves leading indentation on nested tasks", () => {
const sources = [
{ path: "a.md", content: " - [ ] nested\n- [ ] top-level" },
];
assert.equal(
collectOpenTasks(sources, 10),
"a.md\n - [ ] nested\n- [ ] top-level",
);
});
test("handles CRLF line endings", () => {
const sources = [{ path: "a.md", content: "- [ ] one\r\n- [ ] two\r\n" }];
assert.equal(collectOpenTasks(sources, 10), "a.md\n- [ ] one\n- [ ] two");
});
test("respects the total limit across multiple sources", () => {
const sources = [
{ path: "a.md", content: "- [ ] a1\n- [ ] a2\n- [ ] a3" },
{ path: "b.md", content: "- [ ] b1\n- [ ] b2" },
];
// limit 4: a1, a2, a3 from a.md (3); then 1 task from b.md
assert.equal(
collectOpenTasks(sources, 4),
"a.md\n- [ ] a1\n- [ ] a2\n- [ ] a3\n\nb.md\n- [ ] b1",
);
});
test("stops emitting groups once limit is fully consumed", () => {
const sources = [
{ path: "a.md", content: "- [ ] a1\n- [ ] a2" },
{ path: "b.md", content: "- [ ] b1" },
];
assert.equal(collectOpenTasks(sources, 2), "a.md\n- [ ] a1\n- [ ] a2");
});
test("empty source list → '(no open tasks)'", () => {
assert.equal(collectOpenTasks([], 10), "(no open tasks)");
});
test("all sources empty of tasks → '(no open tasks)'", () => {
const sources = [
{ path: "a.md", content: "# Heading\n\nprose" },
{ path: "b.md", content: "- [x] done" },
];
assert.equal(collectOpenTasks(sources, 10), "(no open tasks)");
});
test("ignores non-task list items like bare bullets and starred lists", () => {
const sources = [
{
path: "a.md",
content: "- just a bullet\n- [ ] real task\n* [ ] not a dash",
},
];
assert.equal(collectOpenTasks(sources, 10), "a.md\n- [ ] real task");
});
test("limit of 0 yields '(no open tasks)' even when sources are non-empty", () => {
const sources = [{ path: "a.md", content: "- [ ] task one" }];
assert.equal(collectOpenTasks(sources, 0), "(no open tasks)");
});
test("negative limit is treated like zero (no group ever emits)", () => {
const sources = [{ path: "a.md", content: "- [ ] task one" }];
assert.equal(collectOpenTasks(sources, -5), "(no open tasks)");
});
test("newlines in source path are escaped so they cannot corrupt the line-based output", () => {
// readdirSync on POSIX can return filenames containing newlines; if such
// a name reached the output unescaped, downstream parsers would split
// the path across two lines and misattribute the following task.
const sources = [
{ path: "work/active/oops\nname.md", content: "- [ ] task one" },
];
assert.equal(
collectOpenTasks(sources, 10),
"work/active/oops\\nname.md\n- [ ] task one",
);
});
test("carriage-return in source path is also escaped (Windows network shares)", () => {
const sources = [
{ path: "work/active/odd\rname.md", content: "- [ ] task one" },
];
assert.equal(
collectOpenTasks(sources, 10),
"work/active/odd\\nname.md\n- [ ] task one",
);
});
});
describe("formatBrainIndex", () => {
test("renders one wikilink + description per entry", () => {
const out = formatBrainIndex([
{ name: "Patterns", description: "recurring patterns", hasContent: true },
{ name: "Gotchas", description: "things that bite", hasContent: true },
]);
assert.equal(
out,
"- [[Patterns]] — recurring patterns\n- [[Gotchas]] — things that bite",
);
});
test("appends '(empty)' for stub notes", () => {
const out = formatBrainIndex([
{ name: "Gotchas", description: "things that bite", hasContent: false },
]);
assert.equal(out, "- [[Gotchas]] — things that bite (empty)");
});
test("skips North Star and Memories (already surfaced elsewhere)", () => {
const out = formatBrainIndex([
{ name: "North Star", description: "goals", hasContent: true },
{ name: "Memories", description: "index", hasContent: true },
{ name: "Patterns", description: "patterns", hasContent: true },
]);
assert.equal(out, "- [[Patterns]] — patterns");
});
test("falls back to '(no description)' for null description", () => {
const out = formatBrainIndex([
{ name: "Patterns", description: null, hasContent: true },
]);
assert.equal(out, "- [[Patterns]] — (no description)");
});
test("empty input → '(none)'", () => {
assert.equal(formatBrainIndex([]), "(none)");
});
test("all-filtered-out → '(none)'", () => {
const out = formatBrainIndex([
{ name: "North Star", description: "x", hasContent: true },
{ name: "Memories", description: "y", hasContent: true },
]);
assert.equal(out, "(none)");
});
});
describe("formatInjectionSize", () => {
const cases: ReadonlyArray<readonly [number, string]> = [
[0, "_context injected: 0.0kB_"],
[999, "_context injected: 1.0kB_"], // toFixed rounds
[300, "_context injected: 0.3kB_"],
[58_400, "_context injected: 58.4kB_"],
[1_048_576, "_context injected: 1048.6kB_"],
[-5, "_context injected: 0.0kB_"],
[Number.NaN, "_context injected: 0.0kB_"],
];
for (const [bytes, expected] of cases) {
test(`${bytes} → ${expected}`, () => {
assert.equal(formatInjectionSize(bytes), expected);
});
}
test("an unset budget keeps the pre-budget line byte-identical", () => {
assert.equal(formatInjectionSize(58_400, {}), "_context injected: 58.4kB_");
});
test("a budget with nothing collapsed reports the ceiling", () => {
assert.equal(
formatInjectionSize(30_000, { budgetBytes: 40_000 }),
"_context injected: 30.0kB / 40.0kB budget_",
);
});
test("collapsed sections are NAMED — a silent loss is worse than the bloat", () => {
assert.equal(
formatInjectionSize(39_800, {
budgetBytes: 40_000,
collapsed: ["Vault File Listing", "Brain Topics (read on demand)"],
}),
"_context injected: 39.8kB / 40.0kB budget — collapsed: Vault File Listing, Brain Topics (read on demand)_",
);
});
test("a nonsense budget degrades to the plain meter, never throws", () => {
for (const b of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
assert.equal(
formatInjectionSize(1_000, { budgetBytes: b }),
"_context injected: 1.0kB_",
);
}
});
});
describe("applyInjectionBudget", () => {
const mk = (
header: string,
body: string,
priority: number,
fallback?: string,
): BudgetSection =>
fallback === undefined
? { header, body, priority }
: { header, body, priority, fallback };
test("under budget → untouched, nothing collapsed", () => {
const s = [mk("### A", "short", 10, "(dropped)")];
const r = applyInjectionBudget(s, 10_000);
assert.equal(r.text, "### A\nshort");
assert.deepEqual(r.collapsed, []);
});
test("renders header+body joined by a blank line (pre-budget shape)", () => {
const r = applyInjectionBudget(
[mk("", "## Session Context", 0), mk("### Date", "2026-07-24", 0)],
10_000,
);
assert.equal(r.text, "## Session Context\n\n### Date\n2026-07-24");
});
test("surrenders the HIGHEST priority first", () => {
const s = [
mk("### Keep", "x".repeat(50), 10, "(k)"),
mk("### Drop", "y".repeat(50), 90, "(d)"),
];
const r = applyInjectionBudget(s, 80);
assert.deepEqual(r.collapsed, ["Drop"]);
assert.match(r.text, /### Drop\n\(d\)/);
assert.ok(
!r.text.includes("y"),
"the dropped body must be replaced WHOLE, not truncated — no residue",
);
assert.ok(r.text.includes("x".repeat(50)), "the lower-priority section survives");
});
test("keeps surrendering until it fits, in descending priority", () => {
const s = [
mk("### Third", "c".repeat(100), 10, "(c)"),
mk("### First", "a".repeat(100), 50, "(a)"),
mk("### Second", "b".repeat(100), 30, "(b)"),
];
// 335 B intact; 238 after First collapses; 141 after Second. A 150 B
// ceiling therefore lands exactly two collapses deep and stops.
const r = applyInjectionBudget(s, 150);
assert.deepEqual(r.collapsed, ["First", "Second"]);
assert.ok(r.text.includes("c".repeat(100)), "the lowest priority is still intact");
});
test("a section without a fallback is load-bearing and never degrades", () => {
const s = [mk("### Identity", "z".repeat(500), 99)];
const r = applyInjectionBudget(s, 10);
assert.deepEqual(r.collapsed, []);
assert.ok(r.text.includes("z".repeat(500)), "identity survives an impossible budget");
assert.ok(r.bytes > 10, "over budget is reported honestly, not faked");
});
test("stops once it fits — does not over-collapse", () => {
const s = [
mk("### Big", "a".repeat(200), 50, "(a)"),
mk("### Also", "b".repeat(60), 40, "(b)"),
];
const r = applyInjectionBudget(s, 100);
assert.deepEqual(r.collapsed, ["Big"], "second section kept once the first freed enough");
});
test("a nonsense budget is a no-op, never throws", () => {
const s = [mk("### A", "x".repeat(999), 10, "(short)")];
for (const b of [0, -5, Number.NaN]) {
const r = applyInjectionBudget(s, b);
assert.deepEqual(r.collapsed, []);
assert.ok(r.text.includes("x".repeat(999)));
}
});
test("bytes are measured in UTF-8, not UTF-16 code units", () => {
// Four 3-byte chars: 12 bytes, but only 4 .length units. A budget of 8
// must therefore collapse — the bug this guards is measuring .length.
const s = [mk("", "日本語版", 50, "x")];
const r = applyInjectionBudget(s, 8);
assert.deepEqual(r.collapsed, [""]);
});
});
describe("shouldCollapseDir", () => {
const flat = false;
const tree = true;
test("collapses a flat folder strictly above the threshold, not at it", () => {
assert.equal(shouldCollapseDir(12, 12, [], "people", flat), false);
assert.equal(shouldCollapseDir(13, 12, [], "people", flat), true);
});
test("NEVER collapses a folder with subdirectories, however large", () => {
// The regression this locks: collapsing on recursive subtree count
// folded `projects/`, `brain/` and `work/` into three lines and made
// the vault's shape invisible. Structure is navigation; only flat
// bulk is noise.
assert.equal(shouldCollapseDir(9_999, 12, [], "projects", tree), false);
});
test("an always-collapse dir folds regardless of size OR structure", () => {
// work/archive is year-foldered, so the subdir guard would spare it;
// the explicit list is what makes semantic exceptions still work.
assert.equal(
shouldCollapseDir(1, 999, ["work/archive"], "work/archive", tree),
true,
);
});
test("matching is on the posix path, so nesting is respected", () => {
assert.equal(shouldCollapseDir(1, 999, ["reference/cv"], "cv", flat), false);
});
test("a nonsense threshold collapses nothing by size", () => {
for (const t of [0, -1, Number.NaN]) {
assert.equal(shouldCollapseDir(9_999, t, [], "people", flat), false);
}
});
});
describe("formatCollapsedDir", () => {
test("keeps the pre-threshold line shape verbatim", () => {
assert.equal(
formatCollapsedDir("work/archive", 42),
"./work/archive/ — 42 notes (listing collapsed — Glob or QMD on demand)",
);
});
});
describe("manifest budget fields", () => {
const cases: ReadonlyArray<readonly [string | null, number | null]> = [
['{"eager_layer_budget_bytes":40000}', 40_000],
['{"eager_layer_budget_bytes":0}', null], // non-positive → unset
['{"eager_layer_budget_bytes":-1}', null],
['{"eager_layer_budget_bytes":"40000"}', null], // string → unset
['{"eager_layer_budget_bytes":1.5}', null], // non-integer → unset
["{}", null],
["not json", null],
[null, null],
];
for (const [json, expected] of cases) {
test(`parseInjectionBudget(${String(json)}) → ${String(expected)}`, () => {
assert.equal(parseInjectionBudget(json), expected);
});
}
test("parseListingCollapseThreshold reads its own field", () => {
assert.equal(parseListingCollapseThreshold('{"listing_collapse_threshold":25}'), 25);
assert.equal(parseListingCollapseThreshold('{"eager_layer_budget_bytes":25}'), null);
});
test("parseInstructionBudget reads its own field, with the same validation", () => {
assert.equal(parseInstructionBudget('{"eager_layer_instruction_budget_bytes":40000}'), 40_000);
assert.equal(parseInstructionBudget('{"eager_layer_budget_bytes":40000}'), null);
assert.equal(parseInstructionBudget('{"eager_layer_instruction_budget_bytes":0}'), null);
assert.equal(parseInstructionBudget('{"eager_layer_instruction_budget_bytes":"40000"}'), null);
assert.equal(parseInstructionBudget(null), null);
});
test("the instruction-file default is above the hook-output ceiling, or delivering would gain nothing", () => {
assert.ok(DEFAULT_INSTRUCTION_BUDGET_BYTES > INJECTION_CEILING_BYTES);
});
test("the shipped manifest states the same instruction budget the code falls back to", () => {
// The manifest shows users the key; the constant covers a vault whose
// manifest omits it. They are one default, so they must not drift apart.
const manifest = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../../vault-manifest.json"), "utf-8");
assert.equal(parseInstructionBudget(manifest), DEFAULT_INSTRUCTION_BUDGET_BYTES);
});
test("the shipped default threshold is a positive integer", () => {
assert.ok(Number.isInteger(DEFAULT_LISTING_COLLAPSE_THRESHOLD));
assert.ok(DEFAULT_LISTING_COLLAPSE_THRESHOLD > 0);
});
});
describe("resolveIndexStorePath", () => {
test("uses XDG_CACHE_HOME when set (matches qmd's own store rule)", () => {
assert.equal(
resolveIndexStorePath("my-vault", { XDG_CACHE_HOME: "/xdg/cache" }, "/home/u"),
join("/xdg/cache", "qmd", "my-vault.sqlite"),
);
});
test("falls back to ~/.cache when XDG_CACHE_HOME is unset", () => {
assert.equal(
resolveIndexStorePath("my-vault", {}, "/home/u"),
join("/home/u", ".cache", "qmd", "my-vault.sqlite"),
);
});
/**
* qmd's getDefaultDbPath() checks INDEX_PATH first, for every index name.
* Without it, the store-size check behind bootstrap-vs-update looked at a
* file qmd never opens whenever INDEX_PATH was set.
*/
test("INDEX_PATH wins over everything, for any index name", () => {
const env = { INDEX_PATH: "/pinned/store.sqlite", XDG_CACHE_HOME: "/xdg", HOME: "/h" };
assert.equal(resolveIndexStorePath("my-vault", env, "/home/u"), "/pinned/store.sqlite");
assert.equal(resolveIndexStorePath("other", env, "/home/u"), "/pinned/store.sqlite");
});
test("empty values count as unset, as qmd's `||` reads them", () => {
assert.equal(
resolveIndexStorePath("v", { INDEX_PATH: "", XDG_CACHE_HOME: "", HOME: "" }, "/home/u"),
join("/home/u", ".cache", "qmd", "v.sqlite"),
);
});
test("home is qmd's: HOME, then USERPROFILE, then the OS home", () => {
assert.equal(resolveIndexStorePath("v", { HOME: "/h", USERPROFILE: "/u" }, "/os"), join("/h", ".cache", "qmd", "v.sqlite"));
assert.equal(resolveIndexStorePath("v", { USERPROFILE: "/u" }, "/os"), join("/u", ".cache", "qmd", "v.sqlite"));
});
});
describe("injectionMode", () => {
const cases: ReadonlyArray<readonly [unknown, "full" | "pointer"]> = [
["startup", "full"],
["clear", "full"],
["resume", "pointer"],
["compact", "pointer"],
[undefined, "full"], // missing source (Codex/Gemini)
[null, "full"],
[42, "full"], // non-string
];
for (const [source, expected] of cases) {
test(`${String(source)} → ${expected}`, () => {
assert.equal(injectionMode(source), expected);
});
}
});
describe("the injection budget under the hook output cap (#254)", () => {
test("the ceiling leaves the meter its headroom under the hook output cap, once the JSON envelope is counted (#340)", () => {
// The hook path sends the context inside an envelope, which takes its
// share of the cap: the ceiling must come from what the envelope leaves.
assert.equal(INJECTION_CEILING_BYTES, envelopedLimit("SessionStart").max - METER_HEADROOM);
// A ratchet on the value itself, so a wrong formula cannot pass by agreeing with itself.
assert.equal(INJECTION_CEILING_BYTES, 9_024);
});
test("the template's own manifest budget is under the ceiling: a fresh vault's meter never reports a clamp", () => {
const manifest = readFileSync(new URL("../../../vault-manifest.json", import.meta.url), "utf-8");
assert.equal(effectiveInjectionBudget(parseInjectionBudget(manifest)).clampedFrom, undefined);
});
const C = INJECTION_CEILING_BYTES;
const cases: ReadonlyArray<readonly [number | null, number, number | undefined]> = [
[80_000, C, 80_000], // the old default: clamped, and reported
[C + 1, C, C + 1], // one over: clamped
[C, C, undefined], // exactly the ceiling: kept as configured
[4_000, 4_000, undefined], // under: kept
[null, C, undefined], // unset: the ceiling, with nothing to report
];
for (const [configured, bytes, clampedFrom] of cases) {
test(`effectiveInjectionBudget(${String(configured)}) → ${bytes}${clampedFrom === undefined ? "" : " (clamped)"}`, () => {
assert.deepEqual(effectiveInjectionBudget(configured), clampedFrom === undefined ? { bytes } : { bytes, clampedFrom });
});
}
test("the meter names a clamp, a collapse and a cut, in that order", () => {
assert.equal(
formatInjectionSize(9_000, { budgetBytes: 9_100, clampedFrom: 80_000, collapsed: ["Vault File Listing"], cut: true }),
"_context injected: 9.0kB / 9.1kB budget (80.0kB configured, held under the hook output cap) — collapsed: Vault File Listing — truncated to fit the hook output cap_",
);
assert.equal(formatInjectionSize(9_000, { budgetBytes: 9_100 }), "_context injected: 9.0kB / 9.1kB budget_");
});
});
describe("fitWithMeter", () => {
const chars = (max: number): OutputLimit => ({ ...HOOK_OUTPUT_LIMIT, max });
const meter = (cut: boolean, bytes: number) => `_meter ${bytes}${cut ? " cut" : ""}_`;
test("output under the cap is the body and the meter, unchanged", () => {
assert.equal(fitWithMeter("a\nb\n", meter, chars(100)), "a\nb\n\n_meter 4_\n");
});
test("output over the cap is cut on a line, marked, and closed by the meter", () => {
const body = Array.from({ length: 200 }, (_, i) => `line ${i}`).join("\n") + "\n";
const out = fitWithMeter(body, meter, chars(500));
assert.ok(out.length <= 500, `output is ${out.length} characters`);
assert.ok(out.includes(`\n${CUT_LINE}\n`), "the cut is marked");
const lines = out.split("\n");
assert.match(lines.at(-2) ?? "", /^_meter \d+ cut_$/);
// Every kept line is a whole line of the body.
for (const l of lines.slice(0, lines.indexOf(CUT_LINE))) assert.match(l, /^line \d+$/);
});
test("the cut keeps as much as fits: an all-newline body lands one under the cap", () => {
// Every position is a line boundary, so the kept prefix is the longest
// the arithmetic allows; an off-by-one either way moves this length.
// A fixed-width meter, so a size with fewer digits cannot move it too.
const out = fitWithMeter("\n".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), chars(500));
assert.equal(out.length, 499);
});
test("a body with no line to cut on keeps the partial line, filling the cap exactly", () => {
const out = fitWithMeter("x".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), chars(500));
assert.equal(out.length, 500);
assert.ok(out.startsWith("x".repeat(100)), "the partial line is kept, not dropped");
});
test("a partial line never ends in half of a surrogate pair", () => {
// Each emoji is two UTF-16 units; one of the two parities lands mid-pair.
for (const cap of [500, 501]) {
const out = fitWithMeter("😀".repeat(1_000), (cut) => (cut ? "_m cut_" : "_m_"), chars(cap));
assert.ok(out.length <= cap);
assert.doesNotThrow(() => encodeURIComponent(out), `a lone surrogate at cap ${cap}`);
}
});
test("an oversized meter is cut without leaving half of a surrogate pair", () => {
for (const cap of [500, 501]) {
const out = fitWithMeter("x".repeat(2_000), () => "😀".repeat(600), chars(cap));
assert.ok(out.length <= cap);
assert.doesNotThrow(() => encodeURIComponent(out), `a lone surrogate at cap ${cap}`);
}
});
test("a meter longer than the cap is cut too: the cap holds for any input", () => {
const out = fitWithMeter("a\nb\n", () => "m".repeat(600), chars(500));
assert.ok(out.length <= 500, `output is ${out.length} characters`);
});
test("the meter reports the size of what was kept, not of the whole body", () => {
const body = "x\n".repeat(1_000);
const out = fitWithMeter(body, meter, chars(300));
const kept = out.slice(0, out.lastIndexOf("\n\n_meter") + 1);
// In the limit's own unit: characters here, so the marker's "…" counts once.
assert.match(out, new RegExp(`_meter ${kept.length} cut_\n$`));
});
test("a byte limit is measured in UTF-8 bytes, cuts on a line, and never splits a character", () => {
const limit: OutputLimit = { max: 500, unit: "bytes", name: "a test budget" };
// Three bytes per character: 400 characters fit a character cap of 500, not this one.
const body = Array.from({ length: 40 }, () => "界".repeat(10)).join("\n") + "\n";
const out = fitWithMeter(body, meter, limit);
assert.ok(Buffer.byteLength(out, "utf-8") <= 500, `output is ${Buffer.byteLength(out, "utf-8")} bytes`);
assert.ok(out.includes(`\n${cutLine(limit)}\n`), "the cut is marked with the limit's name");
const lines = out.split("\n");
for (const l of lines.slice(0, lines.indexOf(cutLine(limit)))) assert.equal(l, "界".repeat(10));
});
test("a byte limit with no line to cut on keeps whole characters only", () => {
for (const max of [500, 501, 502]) {
const out = fitWithMeter("界".repeat(1_000), (cut) => (cut ? "_m cut_" : "_m_"), { max, unit: "bytes", name: "a test budget" });
assert.ok(Buffer.byteLength(out, "utf-8") <= max);
assert.ok(!out.includes("\uFFFD"), `a split character at ${max}`);
}
});
test("the hook limit's cut line is the one fitEncoded uses", () => {
assert.ok(fitEncoded("x".repeat(100), 60).endsWith(`\n${CUT_LINE}`));
});
});
describe("the eager layer end to end under the cap (#254)", () => {
test("sections totalling 30,000 characters degrade, fit, and the meter names what collapsed", () => {
// The issue's own test: the budget, the fit and the meter together. The
// budget alone brings this one under the cap, so no cut happens.
const sections: BudgetSection[] = [
{ header: "### Date", body: "Friday", priority: 0 },
{ header: "### North Star", body: "n".repeat(6_000), priority: 30, fallback: "(pointer)" },
{ header: "### Brain Topics", body: "b".repeat(9_000), priority: 40, fallback: "(pointer)" },
{ header: "### Vault File Listing", body: "l".repeat(15_000), priority: 50, fallback: "(pointer)" },
];
const budget = effectiveInjectionBudget(80_000);
const budgeted = applyInjectionBudget(sections, budget.bytes);
const out = fitWithMeter(budgeted.text + "\n", (cut, bytes) =>
formatInjectionSize(bytes, { budgetBytes: budget.bytes, collapsed: budgeted.collapsed, clampedFrom: budget.clampedFrom, cut }),
);
assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `output is ${out.length} characters`);
assert.ok(!out.includes(CUT_LINE), "the budget was enough; nothing was cut");
const meter = out.trimEnd().split("\n").at(-1) ?? "";
assert.match(meter, /— collapsed: Vault File Listing, Brain Topics_$/);
assert.match(meter, /\(80\.0kB configured, held under the hook output cap\)/);
assert.ok(out.includes("n".repeat(6_000)), "North Star fits once the larger sections give way");
});
test("when sections that never degrade pass the cap after every collapse, the fit cuts and the meter says both", () => {
const sections: BudgetSection[] = [
{ header: "### Open Tasks", body: Array.from({ length: 40 }, (_, i) => `- [ ] task ${i} ${"t".repeat(300)}`).join("\n"), priority: 0 },
{ header: "### Vault File Listing", body: "l".repeat(15_000), priority: 50, fallback: "(pointer)" },
];
const budget = effectiveInjectionBudget(null);
const budgeted = applyInjectionBudget(sections, budget.bytes);
const out = fitWithMeter(budgeted.text + "\n", (cut, bytes) =>
formatInjectionSize(bytes, { budgetBytes: budget.bytes, collapsed: budgeted.collapsed, cut }),
);
assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `output is ${out.length} characters`);
assert.ok(out.includes(`\n${CUT_LINE}\n`), "the cut is marked");
const meter = out.trimEnd().split("\n").at(-1) ?? "";
assert.match(meter, /— collapsed: Vault File Listing — truncated to fit the hook output cap_$/);
});
});
329 files · 3 not served here
- .claude-plugin/marketplace.json
- .claude-plugin/plugin.json
- .claude/agents/brag-spotter.md
- .claude/agents/context-loader.md
- .claude/agents/correction-sweep.md
- .claude/agents/cross-linker.md
- .claude/agents/people-profiler.md
- .claude/agents/review-fact-checker.md
- .claude/agents/review-prep.md
- .claude/agents/slack-archaeologist.md
- .claude/agents/vault-librarian.md
- .claude/agents/vault-migrator.md
- .claude/commands/om-capture-1on1.md
- .claude/commands/om-correct.md
- .claude/commands/om-dump.md
- .claude/commands/om-humanize.md
- .claude/commands/om-incident-capture.md
- .claude/commands/om-intake.md
- .claude/commands/om-meeting.md
- .claude/commands/om-peer-scan.md
- .claude/commands/om-prep-1on1.md
- .claude/commands/om-project-archive.md
- .claude/commands/om-review-brief.md
- .claude/commands/om-review-peer.md
- .claude/commands/om-self-review.md
- .claude/commands/om-slack-scan.md
- .claude/commands/om-standup.md
- .claude/commands/om-tidy.md
- .claude/commands/om-vault-audit.md
- .claude/commands/om-vault-upgrade.md
- .claude/commands/om-weekly.md
- .claude/commands/om-wrap-up.md
- .claude/memory-template.md
- .claude/rules/brain-topics.md
- .claude/rules/hooks-and-mod.md
- .claude/rules/hooks-per-agent.md
- .claude/rules/memory.md
- .claude/rules/obsidian-cli.md
- .claude/rules/session-workflow.md
- .claude/rules/skills.md
- .claude/rules/subagents.md
- .claude/rules/thinking.md
- .claude/rules/vault-from-another-repo.md
- .claude/scripts/.gitignore
- .claude/scripts/charcount.ts
- .claude/scripts/classify-message.ts
- .claude/scripts/generate-memory-index.ts
- .claude/scripts/lib/active-hygiene.ts
- .claude/scripts/lib/atomic-write.ts
- .claude/scripts/lib/automemory-index.ts
- .claude/scripts/lib/charcount.ts
- .claude/scripts/lib/correction-sweep.ts
- .claude/scripts/lib/env-path.ts
- .claude/scripts/lib/frontmatter.ts
- .claude/scripts/lib/hint-state.ts
- .claude/scripts/lib/hook-io.ts
- .claude/scripts/lib/instruction-files.ts
- .claude/scripts/lib/main-guard.ts
- .claude/scripts/lib/matcher.ts
- .claude/scripts/lib/mcp-caller.ts
- .claude/scripts/lib/mcp-capture.ts
- .claude/scripts/lib/mcp-context.ts
- .claude/scripts/lib/mcp-exposure.ts
- .claude/scripts/lib/mcp-graph.ts
- .claude/scripts/lib/mcp-memory-bridge.ts
- .claude/scripts/lib/mcp-protocol.ts
- .claude/scripts/lib/mcp-qmd-client.ts
- .claude/scripts/lib/mcp-reason.ts
- .claude/scripts/lib/mcp-server.ts
- .claude/scripts/lib/mcp-tools.ts
- .claude/scripts/lib/memory-discover.ts
- .claude/scripts/lib/memory-index.ts
- .claude/scripts/lib/memory-promoted.ts
- .claude/scripts/lib/memory-recall.ts
- .claude/scripts/lib/memory-similarity.ts
- .claude/scripts/lib/memory-supersede.ts
- .claude/scripts/lib/memory-write.ts
- .claude/scripts/lib/om-mod.ts
- .claude/scripts/lib/project-dir.ts
- .claude/scripts/lib/promoted-gate.ts
- .claude/scripts/lib/prose-width.ts
- .claude/scripts/lib/qmd-bootstrap.ts
- .claude/scripts/lib/qmd-cwd.ts
- .claude/scripts/lib/qmd-ignore.ts
- .claude/scripts/lib/qmd-models.ts (not served here)
- .claude/scripts/lib/qmd-refresh.ts
- .claude/scripts/lib/qmd.ts
- .claude/scripts/lib/read-field.ts
- .claude/scripts/lib/read-head.ts
- .claude/scripts/lib/regex.ts
- .claude/scripts/lib/reinject.ts
- .claude/scripts/lib/report-key.ts
- .claude/scripts/lib/session-start-run.ts
- .claude/scripts/lib/session-start.ts
- .claude/scripts/lib/signals.ts
- .claude/scripts/lib/stop-handoff.ts
- .claude/scripts/lib/stop-report.ts
- .claude/scripts/lib/upgrade-plan.ts
- .claude/scripts/lib/wikilinks.ts
- .claude/scripts/lib/write-targets.ts
- .claude/scripts/om-mcp.mjs
- .claude/scripts/om-mcp.ts
- .claude/scripts/package.json
- .claude/scripts/pre-compact.ts
- .claude/scripts/qmd-mcp.d.mts
- .claude/scripts/qmd-mcp.mjs
- .claude/scripts/qmd-refresh-run.ts
- .claude/scripts/session-start.ts
- .claude/scripts/stop-checklist.ts
- .claude/scripts/tests/_helpers.test.ts
- .claude/scripts/tests/_helpers.ts
- .claude/scripts/tests/_proc.ts
- .claude/scripts/tests/_qmd-cache-guard.ts
- .claude/scripts/tests/_race-child.ts
- .claude/scripts/tests/_run-tests.ts
- .claude/scripts/tests/active-hygiene.test.ts
- .claude/scripts/tests/agent-docs-sync.test.ts
- .claude/scripts/tests/atomic-write.test.ts
- .claude/scripts/tests/automemory-index.test.ts
- .claude/scripts/tests/bootstrap-hook.test.ts
- .claude/scripts/tests/budget-ladder.test.ts
- .claude/scripts/tests/capture-markup-guard.test.ts
- .claude/scripts/tests/charcount.test.ts
- .claude/scripts/tests/classify-message.test.ts
- .claude/scripts/tests/correction-sweep-docs-sync.test.ts
- .claude/scripts/tests/correction-sweep.test.ts
- .claude/scripts/tests/delivery-gate.test.ts
- .claude/scripts/tests/frontmatter.test.ts
- .claude/scripts/tests/gemini-commands.test.ts
- .claude/scripts/tests/generate-changelog.test.ts
- .claude/scripts/tests/hint-state.test.ts
- .claude/scripts/tests/hook-config.test.ts
- .claude/scripts/tests/hook-io.test.ts
- .claude/scripts/tests/main-guard.test.ts
- .claude/scripts/tests/manifest-check.test.ts
- .claude/scripts/tests/matcher.test.ts
- .claude/scripts/tests/mcp-caller.test.ts
- .claude/scripts/tests/mcp-capture.test.ts
- .claude/scripts/tests/mcp-context.test.ts
- .claude/scripts/tests/mcp-exposure.test.ts
- .claude/scripts/tests/mcp-graph.test.ts
- .claude/scripts/tests/mcp-memory-bridge.test.ts
- .claude/scripts/tests/mcp-protocol.test.ts
- .claude/scripts/tests/mcp-qmd-client.test.ts
- .claude/scripts/tests/mcp-reason.concurrency.test.ts
- .claude/scripts/tests/mcp-reason.test.ts
- .claude/scripts/tests/mcp-refusal-audit.test.ts
- .claude/scripts/tests/mcp-reindex.test.ts
- .claude/scripts/tests/mcp-required.test.ts
- .claude/scripts/tests/memory-discover.test.ts
- .claude/scripts/tests/memory-index.test.ts
- .claude/scripts/tests/memory-promoted.test.ts
- .claude/scripts/tests/memory-recall.test.ts
- .claude/scripts/tests/memory-similarity.test.ts
- .claude/scripts/tests/memory-supersede-race.test.ts
- .claude/scripts/tests/memory-supersede-same-title.test.ts
- .claude/scripts/tests/memory-supersede.test.ts
- .claude/scripts/tests/memory-write.concurrency.test.ts
- .claude/scripts/tests/memory-write.test.ts
- .claude/scripts/tests/mod-timeouts.test.ts
- .claude/scripts/tests/om-mcp.integration.test.ts
- .claude/scripts/tests/om-mod.test.ts
- .claude/scripts/tests/personalize-hook.test.ts
- .claude/scripts/tests/pre-compact.test.ts
- .claude/scripts/tests/proc.test.ts
- .claude/scripts/tests/project-dir.test.ts
- .claude/scripts/tests/prose-width.test.ts
- .claude/scripts/tests/qmd-bootstrap.test.ts
- .claude/scripts/tests/qmd-cwd.test.ts
- .claude/scripts/tests/qmd-ignore.test.ts
- .claude/scripts/tests/qmd-mcp.test.ts
- .claude/scripts/tests/qmd-models.test.ts
- .claude/scripts/tests/qmd-refresh.integration.test.ts
- .claude/scripts/tests/qmd-refresh.test.ts
- .claude/scripts/tests/qmd.test.ts
- .claude/scripts/tests/read-head.test.ts
- .claude/scripts/tests/record-work-required.test.ts
- .claude/scripts/tests/refresh-in-vault.test.ts
- .claude/scripts/tests/refresh-switch.test.ts
- .claude/scripts/tests/regex.test.ts
- .claude/scripts/tests/reinject.test.ts
- .claude/scripts/tests/report-key.test.ts
- .claude/scripts/tests/sentinel-path.test.ts
- .claude/scripts/tests/session-start.integration.test.ts
- .claude/scripts/tests/session-start.test.ts
- .claude/scripts/tests/shard-contract.test.ts
- .claude/scripts/tests/shardmindignore.test.ts
- .claude/scripts/tests/signals.test.ts
- .claude/scripts/tests/spawn-windows-hide.test.ts
- .claude/scripts/tests/stop-checklist.test.ts
- .claude/scripts/tests/stop-handoff.test.ts
- .claude/scripts/tests/stop-report.test.ts
- .claude/scripts/tests/tidy-fix.test.ts
- .claude/scripts/tests/upgrade-plan.test.ts
- .claude/scripts/tests/validate-write.memory.test.ts
- .claude/scripts/tests/validate-write.test.ts
- .claude/scripts/tests/vault-promoted.test.ts
- .claude/scripts/tests/vault-prose-width.test.ts
- .claude/scripts/tests/vault-wikilinks.test.ts
- .claude/scripts/tests/wikilink-baseline.json
- .claude/scripts/tests/wikilinks.test.ts
- .claude/scripts/tests/write-targets.test.ts
- .claude/scripts/tidy-fix.ts
- .claude/scripts/tsconfig.json
- .claude/scripts/upgrade-plan.ts
- .claude/scripts/validate-write.ts
- .claude/settings.json
- .claude/skills/defuddle/SKILL.md
- .claude/skills/excalidraw-diagram/SKILL.md
- .claude/skills/excalidraw-diagram/references/excalidraw-schema.md
- .claude/skills/json-canvas/SKILL.md
- .claude/skills/json-canvas/references/EXAMPLES.md
- .claude/skills/mermaid-visualizer/SKILL.md
- .claude/skills/mermaid-visualizer/references/syntax-rules.md
- .claude/skills/obsidian-bases/SKILL.md
- .claude/skills/obsidian-bases/references/FUNCTIONS_REFERENCE.md
- .claude/skills/obsidian-cli/SKILL.md
- .claude/skills/obsidian-markdown/SKILL.md
- .claude/skills/obsidian-markdown/references/CALLOUTS.md
- .claude/skills/obsidian-markdown/references/EMBEDS.md
- .claude/skills/obsidian-markdown/references/PROPERTIES.md
- .claude/skills/obsidian-mind/.claude-plugin/plugin.json
- .claude/skills/obsidian-mind/hooks/context.ts
- .claude/skills/obsidian-mind/hooks/hooks.json
- .claude/skills/obsidian-mind/hooks/register.test.ts
- .claude/skills/obsidian-mind/hooks/register.ts
- .claude/skills/obsidian-mind/hooks/stop.test.ts
- .claude/skills/obsidian-mind/hooks/stop.ts
- .claude/skills/obsidian-mind/hooks/world.ts
- .claude/skills/obsidian-mind/types/index.d.ts
- .claude/skills/qmd/SKILL.md
- .claude/update-skills.ts
- .codex/hooks.json
- .gemini/commands/om-capture-1on1.toml
- .gemini/commands/om-correct.toml
- .gemini/commands/om-dump.toml
- .gemini/commands/om-humanize.toml
- .gemini/commands/om-incident-capture.toml
- .gemini/commands/om-intake.toml
- .gemini/commands/om-meeting.toml
- .gemini/commands/om-peer-scan.toml
- .gemini/commands/om-prep-1on1.toml
- .gemini/commands/om-project-archive.toml
- .gemini/commands/om-review-brief.toml
- .gemini/commands/om-review-peer.toml
- .gemini/commands/om-self-review.toml
- .gemini/commands/om-slack-scan.toml
- .gemini/commands/om-standup.toml
- .gemini/commands/om-tidy.toml
- .gemini/commands/om-vault-audit.toml
- .gemini/commands/om-vault-upgrade.toml
- .gemini/commands/om-weekly.toml
- .gemini/commands/om-wrap-up.toml
- .gemini/settings.json
- .gitattributes
- .github/FUNDING.yml
- .github/pull_request_template.md
- .github/scripts/delivery-gate.ts
- .github/scripts/generate-changelog.ts
- .github/scripts/manifest-check.ts
- .github/scripts/package.json
- .github/workflows/manifest-check.yml
- .github/workflows/mod.yml
- .github/workflows/pr-title.yml
- .github/workflows/release.yml
- .github/workflows/test.yml
- .gitignore
- .mcp.json
- .obsidian/app.json
- .scripts/gemini-commands.ts
- .scripts/package.json
- .scripts/qmd-bootstrap.ts
- .shardmind/hooks/bootstrap.ts
- .shardmind/hooks/package.json
- .shardmind/hooks/personalize.ts
- .shardmind/hooks/post-update.ts
- .shardmind/shard-schema.yaml
- .shardmind/shard.yaml
- .shardmindignore
- AGENTS.md
- ARCHITECTURE.md
- ATTRIBUTION.md
- AUTOGINEER-RUNS.md
- CHANGELOG.md
- CONTRIBUTING.md
- Home.md
- LICENSE
- README.ja.md
- README.ko.md
- README.md
- README.zh-CN.md
- bases/1-1 History.base
- bases/Competency Map.base
- bases/Incidents.base
- bases/Memories.base
- bases/People Directory.base
- bases/Recently Touched.base
- bases/Review Evidence.base
- bases/Templates.base
- bases/Work Dashboard.base
- brain/Gotchas.md
- brain/Key Decisions.md
- brain/Memories.md
- brain/North Star.md
- brain/Patterns.md
- brain/Skills.md
- obsidian-mind-demo.gif (not served here)
- obsidian-mind-logo.png (not served here)
- org/People & Context.md
- org/people/.gitkeep
- org/teams/.gitkeep
- perf/Brag Doc.md
- perf/brag/.gitkeep
- perf/competencies/README.md
- perf/evidence/.gitkeep
- reference/.gitkeep
- templates/Competency Note.md
- templates/Decision Record.md
- templates/Review Template.md
- templates/Thinking Note.md
- templates/Work Note.md
- thinking/README.md
- vault-manifest.json
- work/1-1/.gitkeep
- work/Index.md
- work/active/.gitkeep
- work/archive/.gitkeep
- work/incidents/.gitkeep
- work/meetings/README.md
Advantages
- Provides persistent memory across sessions, preventing agents from starting from zero. evidence: README.md
- Uses local semantic search for efficient, offline retrieval of information. evidence: README.md
- Automates vault hygiene and organization through lifecycle hooks. evidence: README.md
Limitations
- Requires manual setup of hooks and optional dependencies like QMD for full functionality. evidence: README.md
- Semantic search indexing can be resource-intensive on machines without a dedicated GPU. evidence: README.md
- Hook scripts rely on experimental Node.js flags that may change in future versions. evidence: README.md
Security
Risk level: High risk
This brain runs
Agent instructions that run or fetch something (82)
.claude/agents/brag-spotter.md:`git log --since="<quarter start>" --oneline` on the vault itself.claude/agents/correction-sweep.md:Run both..claude/agents/review-prep.md:**Git History** (optional): `git log --since="<start>" --until="<end>" --oneline` for volume of vault activity during the period..claude/agents/vault-librarian.md:Run a full health check and produce a maintenance report..claude/agents/vault-librarian.md:**Orphan Detection**: Run `obsidian orphans` (or `grep -rL '\[\[' work/ org/ perf/ brain/ reference/` as fallback)..claude/agents/vault-librarian.md:**Broken Wikilinks**: Run `obsidian unresolved` (or grep for `\[\[.*\]\]` patterns and check if targets exist)..claude/agents/vault-migrator.md:**Task**: Execute the migration plan — read from source, transform, write to target..claude/commands/om-correct.md:Run it **at the moment of correction**, not on a schedule..claude/commands/om-humanize.md:The user can run `git diff` for the full picture..claude/commands/om-humanize.md:If charcount matters (review content in `perf/`), verify limits after editing with `node --experimental-strip-types .claude/scripts/charcount.ts`..claude/commands/om-incident-capture.md:"Should I run `/om-vault-audit` to verify everything links properly?".claude/commands/om-intake.md:No arguments needed — just drop files and run..claude/commands/om-intake.md:Run this command after..claude/commands/om-intake.md:Before routing, run `qmd query "<meeting topic or person name>"` to find existing notes the content should attach to..claude/commands/om-meeting.md:**Search the vault** — run `qmd query "$ARGUMENTS"` and `qmd vsearch "$ARGUMENTS"` to find everything related to the topic, including semantically related content.claude/commands/om-prep-1on1.md:**Check open tasks** — run `obsidian tasks daily todo`;.claude/commands/om-prep-1on1.md:Run `/om-capture-1on1 $ARGUMENTS` to file the notes into `work/1-1/` and update the person note..claude/commands/om-project-archive.md:git mv "work/active/<Note>.md" "work/archive/YYYY/".claude/commands/om-project-archive.md:git mv "work/active/<Topic>" "work/archive/YYYY/<Topic>".claude/commands/om-project-archive.md:Run a quick check that no wikilinks are broken (Obsidian resolves by name, so moves shouldn't break links).claude/commands/om-review-peer.md:PR evidence from `perf/evidence/<Name> PRs - <cycle>.md` (run `/om-peer-scan` if missing).claude/commands/om-review-peer.md:Use `node --experimental-strip-types .claude/scripts/charcount.ts <file> "<section>" "" <limit>` to verify..claude/commands/om-review-peer.md:Run these before presenting the draft:.claude/commands/om-review-peer.md:[ ] All sections within your tool's character limit (use `node --experimental-strip-types .claude/scripts/charcount.ts <file> "<section>" "" <limit>`).claude/commands/om-self-review.md:[ ] All sections within your tool's character limit (use `node --experimental-strip-types .claude/scripts/charcount.ts <file> "<section>" "" <limit>`).claude/commands/om-standup.md:Run the morning standup..claude/commands/om-standup.md:Re-reading `Home.md`, `brain/North Star.md`, or re-running `git log` doubles the token cost for zero new information..claude/commands/om-tidy.md:Run on demand, during wrap-up when flags are present, or when the flag list has visibly piled up..claude/commands/om-tidy.md:**Completed-not-archived** — `git mv` from `work/active/` to `work/archive/YYYY/`;.claude/commands/om-tidy.md:`node --experimental-strip-types .claude/scripts/tidy-fix.ts [--apply]` runs the DETERMINISTIC subset from cron with no agent: archives completed work, migrates misplaced memory files (copy → regenerate index → verify → remove), and refuses every judgment class with a pointer back here..claude/commands/om-tidy.md:Dry-run by default..claude/commands/om-vault-audit.md:If a note is in the wrong folder, move it with `git mv`.claude/commands/om-vault-upgrade.md:/om-vault-upgrade --dry-run # show the upgrade plan only.claude/commands/om-vault-upgrade.md:/om-vault-upgrade <path-to-source-vault> --dry-run.claude/commands/om-vault-upgrade.md:/om-vault-upgrade --source <path-to-source-vault> [--dry-run].claude/commands/om-vault-upgrade.md:`--dry-run` — produce the plan without changing anything.claude/commands/om-vault-upgrade.md:upgrade with `npm i -g shardmind@latest`)..claude/commands/om-vault-upgrade.md:node --experimental-strip-types .claude/scripts/upgrade-plan.ts.claude/commands/om-vault-upgrade.md:**Managed** (`.shardmind/state.json` exists): it reads `shardmind --json` and `shardmind update --dry-run --json`..claude/commands/om-vault-upgrade.md:It reads `shardmind adopt … --from-version <v> --dry-run --yes --json` and hashes each differing file against that release..claude/commands/om-vault-upgrade.md:With `--dry-run`, stop here..claude/commands/om-vault-upgrade.md:ShardMind executes only through its terminal UI (`--json` works with `--dry-run` only), so run it non-interactively: `CI=true … --yes < /dev/null`..claude/commands/om-vault-upgrade.md:**Conflicts:** ask the user to run `!.claude/commands/om-vault-upgrade.md:A managed update deletes an untouched `CLAUDE.md` or `GEMINI.md` in that same run;.claude/commands/om-vault-upgrade.md:node --experimental-strip-types .claude/scripts/upgrade-plan.ts --apply-behind.claude/commands/om-vault-upgrade.md:**Conflicts:** have the user run `!.claude/commands/om-vault-upgrade.md:The hooks run: `echo '{}' | node --experimental-strip-types .claude/scripts/session-start.ts` exits 0 and prints the session context, as one JSON object whose `hookSpecificOutput.additionalContext` carries it..claude/commands/om-vault-upgrade.md:**Not found**: run version fingerprint detection from the target's `vault-manifest.json`:.claude/commands/om-vault-upgrade.md:Run Tier 0 (vault shape detection) to understand the organizational pattern.claude/commands/om-vault-upgrade.md:On re-run, compute the **source hash** for each source file and compare against the logged source hash:.claude/commands/om-vault-upgrade.md:Say 'go' to execute.".claude/commands/om-vault-upgrade.md:**For `--dry-run`**: write the plan to `thinking/vault-upgrade-plan-YYYY-MM-DD.md` and stop..claude/commands/om-vault-upgrade.md:⚠ 3 orphan notes (no inbound links) — run /om-vault-audit to fix.claude/commands/om-vault-upgrade.md:"Run `/om-vault-audit` for a full structural check".claude/commands/om-weekly.md:**`brag-spotter`** — run with weekly scope to find uncaptured wins and competency gaps.claude/commands/om-weekly.md:`git log --since="7 days ago" --oneline --no-merges` — all vault changes.claude/commands/om-weekly.md:Run the `brag-spotter` subagent with its standard (quarterly) scope, then filter its findings down to wins that clearly occurred in the past 7 days..claude/commands/om-wrap-up.md:**`brag-spotter`** — run at the end to find uncaptured wins and competency gaps from the session.claude/commands/om-wrap-up.md:Auto-memory index — if brain/ notes were added or their descriptions changed, REGENERATE the index instead of hand-editing it: `node --experimental-strip-types .claude/scripts/generate-memory-index.ts > <your ~/.claude/projects/<slug>/memory/MEMORY.md path>`..claude/skills/defuddle/SKILL.md:If not installed: `npm install -g defuddle`.claude/skills/excalidraw-diagram/SKILL.md:When generating an Excalidraw diagram, **automatically execute these steps:**.claude/skills/excalidraw-diagram/SKILL.md:1. Open https://excalidraw.com· uses the network.claude/skills/excalidraw-diagram/SKILL.md:1. Open https://dai-shi.github.io/excalidraw-animate/· uses the network.claude/skills/obsidian-bases/SKILL.md:| Function | Signature | Description | |----------|-----------|-------------| | `date()` | `date(string): date` | Parse string to date (`YYYY-MM-DD HH:mm:ss`) | | `now()` | `now(): date` | Current date and time | | `today()` | `today(): date` | Current date (time = 00:00:00) | | `if()` …[+244 chars]· uses the network.claude/skills/obsidian-cli/SKILL.md:Run `obsidian help` to see all available commands..claude/skills/obsidian-cli/SKILL.md:Run JavaScript in the app context:.claude/skills/obsidian-cli/SKILL.md:Run `obsidian help` to see additional developer commands including CDP and debugger controls..claude/skills/qmd/SKILL.md:Use when the MCP server isn't registered (older vault clones, Windows install drift, disabled in `.mcp.json`), or for one-off shell checks outside a session..claude/skills/qmd/SKILL.md:The template ships `qmd_index` empty so every install gets its own store without being asked a question..claude/skills/qmd/SKILL.md:The SessionStart hook and the PostToolUse debounced refresh both run this automatically;.claude/skills/qmd/SKILL.md:`qmd --index <name> embed` — Regenerate vector embeddings (slower, run after bulk changes)..claude/skills/qmd/SKILL.md:Run the bootstrap once:.claude/skills/qmd/SKILL.md:node --experimental-strip-types .scripts/qmd-bootstrap.ts.claude/skills/qmd/SKILL.md:Idempotent — safe to re-run..claude/skills/qmd/SKILL.md:Run `qmd --index <name> update && qmd --index <name> embed` in the shell..claude/skills/qmd/SKILL.md:The SessionStart hook and the PostToolUse debounced refresh run `update` automatically, but `embed` should be run explicitly after sessions that create many notes.AGENTS.md:Stale Actives), `Recently Touched` (recency by real mtime — the answer to "what's most recent", not filename dates), `Incidents`, `People Directory`, `1-1 History`, `Review Evidence`, `Competency Map`, `Templates` | | `work/` | Work notes index | `Index.md` (detailed MOC) | | `work/ac …[+1219 chars]AGENTS.md:See `.claude/rules/obsidian-cli.md`, or run `obsidian help`.AGENTS.md:Codex will find and execute the command file.AGENTS.md:On a fresh clone, run `node --experimental-strip-types .scripts/qmd-bootstrap.ts` once to build the index.AGENTS.md:Run `/om-standup`.AGENTS.md:**Zero data loss**: when reorganizing, always use `git mv`.
Hooks (14)
.claude/settings.json(SessionStart):node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+17 chars].claude/settings.json(UserPromptSubmit):node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+20 chars].claude/settings.json(PostToolUse):node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+18 chars].claude/settings.json(PreCompact):node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+15 chars].claude/settings.json(Stop):node --disable-warning=ExperimentalWarning --experimental-strip-types "$(r="${CLAUDE_PROJECT_DIR:-.}"; d="$r"; while [ ! -f "$d/vault-manifest.json" ] && p="$(dirname "$d")" && [ "$d" != "$p" ]; do d="$p"; done; [ -f "$d/vault-manifest.json" ] || d="$r"; printf %s "$d")/.claude/scripts/ …[+18 chars].codex/hooks.json(SessionStart):node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/session-start.ts".codex/hooks.json(UserPromptSubmit):node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/classify-message.ts".codex/hooks.json(PostToolUse):node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts".codex/hooks.json(Stop):node --disable-warning=ExperimentalWarning --experimental-strip-types "${CODEX_PROJECT_DIR:-.}/.claude/scripts/stop-checklist.ts".gemini/settings.json(SessionStart):node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/session-start.ts.gemini/settings.json(BeforeAgent):node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/classify-message.ts.gemini/settings.json(AfterTool):node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/validate-write.ts.gemini/settings.json(PreCompress):node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/pre-compact.ts.gemini/settings.json(SessionEnd):node --disable-warning=ExperimentalWarning --experimental-strip-types .claude/scripts/stop-checklist.ts
MCP servers (2)
.mcp.json(qmd):node .claude/scripts/qmd-mcp.mjsREADME.md(om):node /absolute/path/to/your-vault/.claude/scripts/om-mcp.mjs
- Medium risk: runs-instruction-instruction-network (.claude/skills/excalidraw-diagram/SKILL.md:456)
- Medium risk: runs-instruction-instruction-network (.claude/skills/excalidraw-diagram/SKILL.md:470)
- Medium risk: runs-instruction-instruction-network (.claude/skills/obsidian-bases/SKILL.md:181)
- Low risk: network-instructions (.claude/commands/om-vault-upgrade.md:30)
- Low risk: scripts-present (.claude/scripts/classify-message.ts)
- Low risk: scripts-present (.claude/scripts/lib/active-hygiene.ts)
- Low risk: scripts-present (.claude/scripts/lib/atomic-write.ts)
- Low risk: scripts-present (.claude/scripts/lib/correction-sweep.ts)
- Low risk: scripts-present (.claude/scripts/lib/env-path.ts)
- Low risk: scripts-present (.claude/scripts/lib/frontmatter.ts)
- Low risk: scripts-present (.claude/scripts/lib/hint-state.ts)
- Low risk: scripts-present (.claude/scripts/lib/hook-io.ts)
- Low risk: scripts-present (.claude/scripts/lib/instruction-files.ts)
- Low risk: scripts-present (.claude/scripts/lib/main-guard.ts)
- Low risk: scripts-present (.claude/scripts/lib/matcher.ts)
- Low risk: scripts-present (.claude/scripts/lib/mcp-exposure.ts)
- Low risk: scripts-present (.claude/scripts/lib/mcp-qmd-client.ts)
- Low risk: scripts-present (.claude/scripts/lib/memory-promoted.ts)
- Low risk: scripts-present (.claude/scripts/lib/memory-recall.ts)
- Low risk: scripts-present (.claude/scripts/lib/memory-supersede.ts)
- Low risk: scripts-present (.claude/scripts/lib/memory-write.ts)
- Low risk: scripts-present (.claude/scripts/lib/om-mod.ts)
- Low risk: scripts-present (.claude/scripts/lib/project-dir.ts)
- Low risk: scripts-present (.claude/scripts/lib/prose-width.ts)
- Low risk: scripts-present (.claude/scripts/lib/qmd-cwd.ts)
- Low risk: scripts-present (.claude/scripts/lib/qmd-refresh.ts)
- Low risk: scripts-present (.claude/scripts/lib/qmd.ts)
- Low risk: scripts-present (.claude/scripts/lib/read-head.ts)
- Low risk: scripts-present (.claude/scripts/lib/regex.ts)
- Low risk: scripts-present (.claude/scripts/lib/reinject.ts)
- Low risk: scripts-present (.claude/scripts/lib/report-key.ts)
- Low risk: scripts-present (.claude/scripts/lib/session-start-run.ts)
- Low risk: scripts-present (.claude/scripts/lib/session-start.ts)
- Low risk: scripts-present (.claude/scripts/lib/signals.ts)
- Low risk: scripts-present (.claude/scripts/lib/stop-handoff.ts)
- Low risk: scripts-present (.claude/scripts/lib/stop-report.ts)
- Low risk: scripts-present (.claude/scripts/lib/write-targets.ts)
- Low risk: scripts-present (.claude/scripts/pre-compact.ts)
- Low risk: scripts-present (.claude/scripts/qmd-mcp.mjs)
- Low risk: scripts-present (.claude/scripts/session-start.ts)
- Low risk: scripts-present (.claude/scripts/stop-checklist.ts)
- Low risk: scripts-present (.claude/scripts/validate-write.ts)
- Low risk: network-instructions (.claude/skills/defuddle/SKILL.md:10)
AutoGineer scanned breferrari/obsidian-mind@fae7be4 (fae7be4).
Attribution and licence
- First committed by
breferrari
- Declared authors
- Steph Ango (declared in .claude-plugin/plugin.json)
- Publisher
- Brenno Ferrari (Community)
- Source
- breferrari/obsidian-mind · commit fae7be4
- Licence
- MIT License (files served here)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- breferrari, Yi-111-a, sedetweiler, A220man, HoangThai18
AutoGineer is not affiliated with or endorsed by breferrari.
Install from source
3 of its files are not served here, so there is no ZIP. breferrari/obsidian-mind at fae7be4