Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

feat: make AGENTS.md the single instruction file (#333)

Brenno Ferrari74b09bcadd83
diff --git a/.claude/agents/vault-migrator.md b/.claude/agents/vault-migrator.md
index 0975bfe..6c9d7a0 100644
--- a/.claude/agents/vault-migrator.md
+++ b/.claude/agents/vault-migrator.md
@@ -259,7 +259,7 @@ target_version: "3.3.0"
Body should include:
- Summary statistics (files migrated by category, transformations applied, conflicts)
- Content hash table (for idempotency on re-runs)
-- CLAUDE.md diff summary (if source had a customized CLAUDE.md, list the differences so the user knows what conventions to re-apply)
+- CLAUDE.md additions (if the source had a CLAUDE.md, list what it adds beyond the template's `AGENTS.md` and `.claude/rules/`, so the user can fold each into `.claude/rules/local.md` or `AGENTS.md`; never write it to the target as CLAUDE.md, which would make Claude Code skip `AGENTS.md`)
- List of user additions copied (custom commands, agents, scripts)
- Any files sent to `thinking/migrate-review/` for manual sorting
diff --git a/.claude/commands/om-correct.md b/.claude/commands/om-correct.md
index e0562af..f098819 100644
--- a/.claude/commands/om-correct.md
+++ b/.claude/commands/om-correct.md
@@ -84,4 +84,4 @@ For a sweep touching more than a handful of notes, invoke the `correction-sweep`
- `/om-vault-audit` — structural health, periodic, whole-vault. Complementary: it checks shape, this checks truth.
- `/om-tidy` — acts on hygiene flags. Also structural.
-- `CLAUDE.md` § Write-Correctness Laws — Laws 1, 2 and 5, which this implements.
+- `AGENTS.md` § Write-Correctness Laws — Laws 1, 2 and 5, which this implements.
diff --git a/.claude/commands/om-dump.md b/.claude/commands/om-dump.md
index 840067c..f96105a 100644
--- a/.claude/commands/om-dump.md
+++ b/.claude/commands/om-dump.md
@@ -6,7 +6,7 @@ Process the following freeform dump. For each distinct piece of information:
1. **Classify** it: decision, incident, 1-on-1 content, win/achievement, architecture, project update, person context, or general work note.
2. **Search first**: Use `qmd vsearch` (or `obsidian search` if QMD unavailable) to check if a related note already exists. Prefer appending to existing notes over creating new ones for small updates.
-3. **Create or update** the appropriate note following CLAUDE.md conventions:
+3. **Create or update** the appropriate note following AGENTS.md conventions:
- Correct folder placement (work/active/, work/incidents/, work/1-1/, org/people/, etc.)
- Full YAML frontmatter with date, description, tags, and type-specific fields
- All relevant [[wikilinks]] to people, projects, teams, competencies
diff --git a/.claude/commands/om-vault-audit.md b/.claude/commands/om-vault-audit.md
index 7d7ee59..31bacce 100644
--- a/.claude/commands/om-vault-audit.md
+++ b/.claude/commands/om-vault-audit.md
@@ -33,7 +33,7 @@ Verify the vault matches the expected layout:
- `org/teams/` contains only notes tagged `team`
- `templates/` contains only template files (with `{{placeholders}}`)
- `thinking/` is clean (no leftover drafts that should have been promoted)
-- Nothing unexpected at vault root (allowed: `Home.md`, `CLAUDE.md`, `vault-manifest.json`, `CHANGELOG.md`, `CONTRIBUTING.md`, `README.md`, `LICENSE`, `.gitignore` — no user notes)
+- Nothing unexpected at vault root (allowed: `Home.md`, `AGENTS.md`, `vault-manifest.json`, `CHANGELOG.md`, `CONTRIBUTING.md`, `README.md`, `LICENSE`, `.gitignore` — no user notes)
### 2. Check Indexes
@@ -120,7 +120,8 @@ Per vault rules, each note should cover ONE concept. Flag notes that:
- `.claude/settings.json` — are hooks well-formed and referencing correct paths?
- `.claude/commands/` — do all commands reference correct folder structure?
-- `CLAUDE.md` — any stale instructions that contradict current vault state?
+- `AGENTS.md` and `.claude/rules/` — any stale instructions that contradict current vault state?
+- No `CLAUDE.md` at the vault root: Claude Code reads it and skips `AGENTS.md` (the hygiene flags say so too)
### 12. Fix and Report
diff --git a/.claude/commands/om-vault-upgrade.md b/.claude/commands/om-vault-upgrade.md
index 36c3397..cffd0fd 100644
--- a/.claude/commands/om-vault-upgrade.md
+++ b/.claude/commands/om-vault-upgrade.md
@@ -46,6 +46,8 @@ It then prints every file needing judgment, sorted into:
| **Merged** | Changed on both sides, merged cleanly | Show the user the result to review |
| **Conflicts** | Changed on both sides, or a new template file where you already have one | The user decides per file |
| **New in the template** | Added | Taken as is |
+| **Move out** | A retired instruction file (`CLAUDE.md`, `GEMINI.md`) still in the vault | Claude Code reads a `CLAUDE.md` and skips `AGENTS.md`; Gemini no longer reads a `GEMINI.md`, so what the user added there is lost. With the user, move what they added: from `GEMINI.md` into `AGENTS.md`; from `CLAUDE.md` into `.claude/rules/local.md` (Claude Code only) or `AGENTS.md` (every agent; keep it under 23 KB, where the hygiene scan flags it: Antigravity stops reading at ~24,000 bytes), then delete it. Nothing is merged automatically |
+| **Settle these first** | Shown above the lists when `AGENTS.md` or `.gemini/settings.json` is a conflict while `CLAUDE.md` or `GEMINI.md` retires (`settleFirst` in `--json`) | The old `AGENTS.md` only points at `CLAUDE.md`, and old Gemini settings send Gemini to `GEMINI.md`, which does the same. Resolve each to the release's version and re-add the user's changes; otherwise a managed update deletes an untouched `CLAUDE.md` and leaves agents without conventions |
Show the report to the user. With `--dry-run`, stop here.
@@ -57,8 +59,12 @@ ShardMind executes only through its terminal UI (`--json` works with `--dry-run`
- **No conflicts:** `CI=true shardmind update --yes < /dev/null`. `--yes` auto-keeps your version wherever both sides changed, so it is safe only once the plan shows no conflicts.
- **Conflicts:** ask the user to run `! shardmind update` themselves and decide each conflicting file in the prompt, or in their editor.
+**Order:** if the plan says *Settle these first*, each listed file is a conflict, so the update runs through the user's own `! shardmind update` (or `decide-per-file` adopt): resolve each there to the release's version, re-adding the user's changes. A managed update deletes an untouched `CLAUDE.md` or `GEMINI.md` in that same run; an unmanaged clone keeps them until these are settled.
+
+**A Move out file the user changed:** the interactive `shardmind update` asks whether to keep or delete it, because the release removed it. Tell the user to answer **keep**: deleting it there loses their additions. Once the update is done, move the additions as U1 says, then delete the file.
+
**Cloned without ShardMind:**
-1. Write the new release's bytes for the **behind** files only. Each is checked against adopt's plan before it is written, so nothing you changed is touched:
+1. Write the new release's bytes for the **behind** files only. Each is checked against adopt's plan before it is written, so nothing you changed is touched. A `CLAUDE.md` or `GEMINI.md` listed as behind is one you never edited, and this step **deletes** it, after the new `AGENTS.md` is written: name it to the user and get their yes before running it:
```bash
node --experimental-strip-types .claude/scripts/upgrade-plan.ts --apply-behind
```
@@ -113,6 +119,7 @@ Glob all `.md`, `.base`, `.canvas` files and binary files (images, PDFs) in the
| `.claude/commands/` not in template | **MERGE** | `.claude/commands/` (user addition) |
| `.claude/agents/` not in template | **MERGE** | `.claude/agents/` (user addition) |
| `.claude/scripts/` not in template | **MERGE** | `.claude/scripts/` (user addition) |
+| `.claude/rules/` not in template | **MERGE** | `.claude/rules/` (user addition, such as `local.md` or a section moved out of `AGENTS.md`; its `AGENTS.md` pointer comes with the user's `AGENTS.md` additions) |
| `scaffold` path with real content | **REPLACE** | Same path in target |
| `scaffold` path with stub-only content | **SKIP** | Template stub is fine |
| `user_content_roots` glob | **COPY** | Same relative path |
@@ -177,7 +184,7 @@ Transformations:
**Conflict section** (if any):
```
⚠ Conflicts requiring your input:
- - source has customized CLAUDE.md (will NOT copy — differences logged)
+ - source has a CLAUDE.md (will NOT copy — its additions are listed for .claude/rules/local.md or AGENTS.md)
- source has .claude/commands/my-custom.md (will MERGE as user addition)
```
@@ -224,14 +231,14 @@ Migration complete.
Offer next steps:
- "Run `/om-vault-audit` for a full structural check"
- "Review `thinking/migrate-review/` for uncategorized files"
-- "Check `brain/Migration Log.md` for the full receipt and CLAUDE.md diff"
+- "Check `brain/Migration Log.md` for the full receipt and the source CLAUDE.md's additions to fold in"
## Important
- **The source vault is NEVER modified.** All operations are read-only on the source, write-only on the target.
- **Plan-first, always.** Never skip the plan presentation step, even if the migration looks simple.
- **Preserve user curation.** When rebuilding indexes, start from the source's version (which has the user's ordering and groupings), then append missing entries. Don't regenerate from scratch.
-- **CLAUDE.md is special.** Never copy it from the source. The template's CLAUDE.md is always authoritative. If the source has customizations, diff them and log the differences so the user can re-apply manually.
+- **CLAUDE.md is user content, and never copied as CLAUDE.md.** A `CLAUDE.md` at the vault root makes Claude Code skip `AGENTS.md`, the template's one instruction file. If the source has one, diff it against the template's `AGENTS.md` and `.claude/rules/`, and log what it adds so the user can fold each addition into `.claude/rules/local.md` (Claude Code only) or `AGENTS.md` (every agent). Nothing is merged automatically.
- **Binary files matter.** Images, PDFs, and attachments embedded in notes must be copied or the embeds break.
- **Wikilinks resolve by filename.** Most folder moves don't break links. Only renames and full-path links need fixing.
- **Markdown links get converted.** Standard markdown links to local files (`[text](path.md)`) are converted to wikilinks (`[[name|text]]`). External URLs are left as-is.
diff --git a/.claude/commands/om-wrap-up.md b/.claude/commands/om-wrap-up.md
index 4d1202d..5b006c7 100644
--- a/.claude/commands/om-wrap-up.md
+++ b/.claude/commands/om-wrap-up.md
@@ -8,7 +8,7 @@ Full session review before ending. Review context, ways of working, files modifi
/om-wrap-up
```
-Triggered when the user says "wrap up", "let's wrap", "wrapping up", or similar. Claude should invoke this automatically.
+Triggered when the user says "wrap up", "let's wrap", "wrapping up", or similar. The agent should invoke this automatically.
## Subagent
@@ -63,7 +63,7 @@ Invoke `/om-tidy` while the conversation and tools are still live. It runs the s
- A new pattern that should be in `brain/Patterns.md`?
- A new gotcha that should be in `brain/Gotchas.md`?
- A workflow improvement for `brain/Skills.md`?
-- A CLAUDE.md update needed (new convention, stale reference)?
+- An AGENTS.md update needed (new convention, stale reference)?
- A new or improved slash command?
- A hook that should be added or modified?
diff --git a/.claude/rules/brain-topics.md b/.claude/rules/brain-topics.md
new file mode 100644
index 0000000..af10260
--- /dev/null
+++ b/.claude/rules/brain-topics.md
@@ -0,0 +1,10 @@
+Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.
+
+## When to Consult Brain Topics
+
+The SessionStart hook injects a **Brain Topics (read on demand)** index listing each `brain/` topic note with its description and an `(empty)` marker for stub notes. Treat that index as a menu:
+
+- When the user's message touches a topic from the index (debugging → Gotchas, "how do we usually…" → Patterns, "why did we decide" → Key Decisions, "which command / slash" → Skills), query QMD **first** before answering — call `mcp__qmd__query` with a `query` argument describing the topic (or fall back to `qmd --index <name> query "<topic>"` if MCP is unavailable). The search covers the whole vault, so filter or prioritize results whose `file` path is under `brain/`. Do not assume the topic name alone scopes the search.
+- If QMD is unavailable, read the specific `brain/` note directly with the Read tool. Don't load all of `brain/` — only the one(s) matching the topic.
+- Skip notes marked `(empty)` in the index — they're stubs with no substantive content.
+- After answering, if the conversation produced durable knowledge, update the relevant brain note (see the "remember" workflow in `AGENTS.md` → **Memory System**).
diff --git a/.claude/rules/hooks-and-mod.md b/.claude/rules/hooks-and-mod.md
new file mode 100644
index 0000000..dcbcf58
--- /dev/null
+++ b/.claude/rules/hooks-and-mod.md
@@ -0,0 +1,22 @@
+# Hooks and the obsidian-mind Mod (Claude Code)
+
+Claude-only: Claude Code loads this file beside `AGENTS.md` and the shared files in this folder, which hold every convention the other agents share.
+
+| Folder | Purpose | Key Files |
+|--------|---------|-----------|
+| `.claude/scripts/` | Hook scripts + the MCP server | `session-start.ts`, `classify-message.ts`, `validate-write.ts`, `pre-compact.ts`, `stop-checklist.ts`, `charcount.ts`, `om-mcp.mjs` (see `.claude/rules/vault-from-another-repo.md`) |
+
+## Hooks
+
+The lifecycle hooks in `.claude/settings.json`:
+
+| Hook | When | What |
+|------|------|------|
+| SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star, active work, recent changes, tasks, file listing (folders past a note-count threshold collapse to one line), vault-hygiene drift flags (completed-not-archived, ungrouped clusters, 25KB oversize, stale open loops, meetings-inbox pressure); the whole injection is held under a byte budget that fits Claude Code's 10,000-character hook output cap — over it, low-priority sections degrade to pointers and the closing injection-size meter names each one it dropped |
+| UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints; also hands the agent a Stop report saved since the last prompt |
+| PostToolUse | After writing `.md` | Validates frontmatter + wikilinks, blocks misplaced memory files, flags notes crossing the 25KB organization threshold (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 vault-hygiene drift findings (same scan as SessionStart), shown once per session and again only when the findings change; hands drift to `om-tidy`. A Stop `systemMessage` reaches only the user, and every Stop output that reaches the agent is also printed in full for the user. So a changed report shows the user a one-line-per-section summary and saves the full report for the next prompt, where the UserPromptSubmit hook hands it to the agent unseen; the agent deals with the user's message first, then acts, asks, or leaves it. If the report cannot be saved, it goes out as Stop feedback instead. SessionEnd and a Stop without a session id show the full report. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |
+
+**On Claude Code 2.1.287+, the `obsidian-mind` mod** (`.claude/skills/obsidian-mind/`) delivers the SessionStart context as an instruction file instead: it runs `session-start.ts` itself and passes the settings hook `om_mod: "standdown"` for that event. The context then survives compaction whole and reaches general-purpose subagents (Explore and Plan skip instruction files by design); `/memory` shows it as `.claude/session-context.md`. It also presents the Stop report: it runs `stop-checklist.ts` with `om_mod: "report"`, stands the Stop hook down, draws one line under the answer when the findings changed, and hands you the full report with the user's next prompt (typed, over Remote Control, through the SDK or a Slack ping; a peer message, a notification or a scheduled prompt does not consume it), or with the mod's own prompt for an urgent finding, at most one per prompt the user sends. Wherever the mod does not load (Codex, Gemini, older Claude Code, an untrusted folder, a session started in a vault subfolder), the hooks above run unchanged.
+
diff --git a/.claude/rules/hooks-per-agent.md b/.claude/rules/hooks-per-agent.md
new file mode 100644
index 0000000..24cc7a6
--- /dev/null
+++ b/.claude/rules/hooks-per-agent.md
@@ -0,0 +1,21 @@
+Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.
+
+## Hooks
+
+The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell, executed natively by Node via `--experimental-strip-types` — no build step, no runtime dependencies, no Claude SDK. Hook configs are provided for these agents:
+
+| Agent | Config | Status |
+|-------|--------|--------|
+| Claude Code | `.claude/settings.json` | Full support |
+| Codex CLI | `.codex/hooks.json` | Shared hook scripts |
+| Gemini CLI | `.gemini/settings.json` | Shared hook scripts |
+
+| Script | Purpose | Claude event | Codex event | Gemini event |
+|--------|---------|--------------|-------------|--------------|
+| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
+| `classify-message.ts` | Classify messages, inject routing hints, hand over the last Stop report (Claude Code and Codex: Gemini's checklist runs on SessionEnd and saves none) | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
+| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
+| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
+| `stop-checklist.ts` | Wrap-up checklist and vault-hygiene drift findings (Claude Code and Codex: per response, deduped; Gemini: once, at shutdown) | Stop | Stop | SessionEnd |
+
+Grok, once the vault is trusted, loads the project `.claude/settings.json` hooks (observed for #321); how each event behaves under Grok is not verified (TBC), and its own layer is #323.
diff --git a/.claude/rules/memory.md b/.claude/rules/memory.md
new file mode 100644
index 0000000..022f27f
--- /dev/null
+++ b/.claude/rules/memory.md
@@ -0,0 +1,15 @@
+# Auto-Memory Index (Claude Code)
+
+Claude-only: Claude Code loads this file beside `AGENTS.md` and the shared files in this folder, which hold every convention the other agents share.
+
+**All project memories live in the vault.** The `~/.claude/` MEMORY.md is an auto-loaded index that points to vault locations. The `~/.claude/` MEMORY.md is the only file that should exist there -- it is an auto-loaded index. Never create additional memory files in that directory.
+
+| System | Location | Purpose |
+|--------|----------|---------|
+| **MEMORY.md** | `~/.claude/projects/.../memory/MEMORY.md` | Auto-loaded index only. Pointers to vault notes. |
+
+When asked to "remember" something (steps 1–3 are in `AGENTS.md` → **Memory System**):
+
+4. Do NOT create additional files in `~/.claude/projects/.../memory/` beyond MEMORY.md -- they are not version-controlled
+
+From `AGENTS.md` → **Rules**: Never create memory files in `~/.claude/` -- they are not git-tracked.
diff --git a/.claude/rules/obsidian-cli.md b/.claude/rules/obsidian-cli.md
new file mode 100644
index 0000000..3eda418
--- /dev/null
+++ b/.claude/rules/obsidian-cli.md
@@ -0,0 +1,20 @@
+Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.
+
+## Obsidian CLI
+
+When Obsidian is running, prefer CLI over raw filesystem — it provides vault-aware search, backlink discovery, and property management. **On macOS, open Obsidian before invoking the CLI**: the first `obsidian` call launches the Electron app (visible window flash) if no instance is running; subsequent calls forward args silently. In non-interactive contexts where you can't guarantee Obsidian is open (background hooks, automation), prefer filesystem reads instead.
+
+```bash
+obsidian read file="Note Name" # Read a note
+obsidian create name="Name" content="..." silent # Create without opening
+obsidian append file="Name" content="..." # Append to note
+obsidian search query="text" limit=10 # Vault-aware search
+obsidian backlinks file="Name" # Discover connections
+obsidian tags sort=count counts # List all tags
+obsidian tasks daily todo # Open tasks
+obsidian daily:read # Today's daily note
+obsidian property:set name="status" value="done" file="Name"
+obsidian orphans # Unlinked notes
+```
+
+`file=` resolves like a wikilink (by name). `path=` for exact path from root. Use `silent` to prevent files from opening. Run `obsidian help` for full reference.
diff --git a/.claude/rules/session-workflow.md b/.claude/rules/session-workflow.md
new file mode 100644
index 0000000..e437402
--- /dev/null
+++ b/.claude/rules/session-workflow.md
@@ -0,0 +1,33 @@
+Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.
+
+## Session Workflow
+
+### Starting a Substantial Session
+
+The `SessionStart` hook automatically injects rich context: vault file listing, North Star goals, active work, recent git changes, open tasks (aggregated from `work/active/` and the vault root, excluding infrastructure files), vault-hygiene drift flags (act on them or run `/om-tidy`), and triggers a QMD re-index. Most context is already loaded -- you don't need to manually read files.
+
+**Shortcut**: Run `/om-standup` for a structured morning kickoff that reads everything and presents a summary with suggested priorities.
+
+If doing it manually:
+
+1. Read `Home.md` -- vault entry point with embedded dashboards
+2. Read `brain/North Star.md` -- ground suggestions in current goals
+3. Check `work/Index.md` -- see active projects and recent notes
+4. Scan `brain/Memories.md` -- index of memory topics, then read relevant topic notes
+5. `obsidian tasks daily todo` -- see pending items
+
+### Ending a Substantial Session
+
+If `/om-wrap-up` is not invoked, at minimum do these before wrapping up:
+
+1. **Archive completed projects**: `git mv` from `work/active/` to `work/archive/YYYY/`, update `status: completed` (or use `/om-project-archive`)
+2. Update `work/Index.md` if new notes or decisions were created
+3. Update the relevant brain topic note (`brain/Key Decisions.md`, `brain/Patterns.md`, `brain/Gotchas.md`) with key learnings
+4. Update `org/People & Context.md` if org knowledge changed
+5. Update `perf/Brag Doc.md` if wins or impact were achieved
+6. Offer to update `brain/North Star.md` if goals shifted or new focus emerged
+7. Verify all new notes link to at least one existing note (orphans are bugs)
+8. If work demonstrates competencies, add competency links to the work note's `## Related`
+9. Run `/om-vault-audit` if the session created many notes
+
+Skip steps that don't apply. The goal is transferring durable knowledge from conversation to vault state.
diff --git a/.claude/rules/skills.md b/.claude/rules/skills.md
new file mode 100644
index 0000000..821ab8a
--- /dev/null
+++ b/.claude/rules/skills.md
@@ -0,0 +1,28 @@
+# Skills and Commands (Claude Code)
+
+Claude-only: Claude Code loads this file beside `AGENTS.md` and the shared files in this folder, which hold every convention the other agents share.
+
+## Skills & Capabilities
+
+This vault has [obsidian-skills](https://github.com/kepano/obsidian-skills) installed in `.claude/skills/`. Follow these skill conventions:
+
+- **obsidian-markdown**: Obsidian-flavored markdown -- wikilinks, embeds, callouts, properties. See `references/` for callout types, embed syntax, and property specs. Always prefer `[[wikilinks]]` over markdown links.
+- **obsidian-cli**: CLI commands for vault operations when Obsidian is running. See `.claude/rules/obsidian-cli.md`.
+- **json-canvas**: Create `.canvas` files with nodes, edges, and visual layouts. See `references/EXAMPLES.md`.
+- **obsidian-bases**: Create `.base` files with views, filters, and formulas. Bases core plugin is enabled. See `references/FUNCTIONS_REFERENCE.md`.
+- **defuddle**: Extract clean markdown from web pages via `defuddle parse <url> --md`.
+
+### Custom Slash Commands
+
+Defined in `.claude/commands/`. Claude Code auto-surfaces every command with its description in the session's skills list — **that injected list is the live catalog**. Do not maintain a command table here (it drifts; the injected list can't — see Write-Correctness law 6). **Agents without that injection (Codex, Gemini, Cursor): read `brain/Skills.md`** — it carries the full command catalog plus usage docs and workflow sequences.
+
+## Where they live
+
+| Folder | Purpose | Key Files |
+|--------|---------|-----------|
+| `.claude/commands/` | Slash commands (auto-surfaced in-session; catalog in `brain/Skills.md`) | One `.md` per command |
+| `.claude/skills/` | Obsidian + QMD skills, and the `obsidian-mind` Claude Code mod | Skills load via the Skill tool; the mod loads as a plugin on Claude Code 2.1.287+ |
+
+## Rule
+
+- **Always invoke Obsidian skills via the Skill tool** before doing vault work. Load `obsidian-markdown` when creating/editing `.md` files. Load `obsidian-cli` when running vault commands. Load `obsidian-bases` or `json-canvas` when working with those file types.
diff --git a/.claude/rules/subagents.md b/.claude/rules/subagents.md
new file mode 100644
index 0000000..0227bde
--- /dev/null
+++ b/.claude/rules/subagents.md
@@ -0,0 +1,25 @@
+# Subagents (Claude Code)
+
+Claude-only: Claude Code loads this file beside `AGENTS.md` and the shared files in this folder, which hold every convention the other agents share.
+
+| Folder | Purpose | Key Files |
+|--------|---------|-----------|
+| `.claude/agents/` | Subagents | See subagents table below |
+
+## Subagents
+
+Specialized agents in `.claude/agents/` for heavy operations. They run in isolated context windows.
+
+| 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 |
+| `correction-sweep` | Finds every note restating a corrected fact; classifies each as authoritative, restatement, or historical. Never edits | `/om-correct` |
+| `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` | Verifies every claim in a review draft against vault sources | `/om-self-review`, `/om-review-peer` |
+| `vault-migrator` | Classifies, transforms, and migrates content from a source vault | `/om-vault-upgrade` |
+
diff --git a/.claude/rules/thinking.md b/.claude/rules/thinking.md
new file mode 100644
index 0000000..f02c604
--- /dev/null
+++ b/.claude/rules/thinking.md
@@ -0,0 +1,12 @@
+Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.
+
+## Thinking Workflow
+
+Use `thinking/` for drafts, reasoning, and analysis before writing final notes. **Thinking notes are scratchpads, not storage.** They exist to help you reason -- once the reasoning produces durable knowledge, promote it to proper notes and delete the scratchpad.
+
+1. Create a thinking note: `thinking/YYYY-MM-DD-descriptive-name.md`
+2. Use the Thinking Note template
+3. Reason through the problem, analyze options, draft content
+4. Promote findings to atomic notes in the correct folder (not one monolith -- one note per distinct concept)
+5. Delete the thinking note -- it served its purpose
+6. If the thinking process itself is worth preserving (unusual), keep it but link to the promoted notes
diff --git a/.claude/rules/vault-from-another-repo.md b/.claude/rules/vault-from-another-repo.md
new file mode 100644
index 0000000..be0dc97
--- /dev/null
+++ b/.claude/rules/vault-from-another-repo.md
@@ -0,0 +1,105 @@
+Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.
+
+## Reaching the Vault From Another Repo
+
+The vault normally only helps while you are sitting in it. The **`om` MCP server** makes it reachable from a coding session running in any other repository: that session can search the vault, read notes, follow the graph, and record back into it.
+
+### The install is two steps, and both are required
+
+**1. Register the server** in the consuming project's `.mcp.json`:
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["<absolute path to your vault>/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+**2. Add a short section to that project's own instruction file (`CLAUDE.md` or `AGENTS.md`)**, telling it the vault exists and to consult it.
+
+> [!warning] Step 2 is not documentation garnish.
+> **Measured:** with the server wired and *no* repo-side instruction, a session made **zero** vault calls and went on to implement a design the vault had recorded as explicitly rejected. With the instruction present, it refused and cited the note.
+>
+> The reason is an asymmetry in how MCP `instructions` propagate: a **prohibition** holds reliably, while 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.
+
+> [!warning] Do not register the raw `qmd` server in a consuming repo.
+> It searches every note directly, with no notion of which memories were written for which project — so the repo matches against lessons meant for unrelated ones. Applying each memory's declared scope on top of the index is exactly what `om` adds, and going around it returns the **wrong** things, not merely more of them.
+
+### What it exposes
+
+| tool | purpose |
+|------|---------|
+| `search` | semantic + keyword search over exposed notes |
+| `expand` | a note's graph neighbourhood — links out and backlinks |
+| `recall` | durable lessons scoped to the calling repo, most specific first |
+| `remember` | record a lesson that will still be true in a different repo |
+| `record_work` | record what happened in this repo, filed where it belongs |
+| `reason` | judgement across several notes — spawns a second session, so it takes longer |
+| `health` | is the wiring intact? |
+
+Plus notes as readable **resources**, and `recall_topic` / `prior_art` as **prompts** you invoke yourself from the `/` menu.
+
+### `reason` — judgement across notes
+
+The other tools answer without inference. `reason` reads the vault with a second Claude session, so it is slower and uses more — reach for it when `search` or `recall` returned the notes but not the judgement. It seeds itself from search, so there is no need to search first.
+
+**It runs on your own CLI default model**, so the vault answers at the level you are already working at. MCP gives a server no way to see the calling session's model, so inheriting the CLI default is the closest reachable thing to "the same model I am using".
+
+**Every call is on the record** — including one that produced no answer, since the log is written before any refusal. It lands in `.claude/om-mcp-audit.jsonl` with the question, cost, turns, terminal reason, model asked for, model that ran, wall time, and the roots the spawn was given. `health` reports the day's figure, and says *at least* when the log was too big to read whole rather than quietly under-reporting.
+
+**It reads what this vault serves, and nothing else.** The spawn is handed the same three rules the exposure policy applies to search results: your `mcp_exposed_roots`, your `mcp_never_expose` filenames, and `private:`-tagged notes — the last two matter because they live *inside* exposed roots. Unset, that is simply your `user_content_roots`, so the boundary is whatever you already declared rather than anything this tool adds. It is also told not to read the memory root, since a memory belongs to the project it was scoped to.
+
+**The server stays responsive while it runs.** Other tools answer normally mid-call, and a shutdown ends any spawn still in flight rather than orphaning it.
+
+One optional key, which does not ship set:
+
+```json
+"reason": { "model": "claude-haiku-4-5" } // pin a model instead of inheriting
+```
+
+Left unset — the default — it uses your own Claude settings.
+
+> [!warning] If you pin a model, use a FULL id.
+> `--model haiku` is not honoured by the CLI and does not error — it silently runs `claude-sonnet-5`. Bare aliases (`haiku`, `sonnet`, `opus`) are therefore dropped in favour of inheriting; anything else is passed through as written. Every answer names the model that actually ran, and says whether it was the pinned one.
+
+If a run ends early you get **no answer**, not a truncated one, plus the evidence search already found — a partial synthesis presented as complete is the one outcome worse than none.
+
+Answers land in `.claude/om-reasoning/` (gitignored) marked `confidence: inferred`. They are deliberately **not** recorded as memories — a spawned conclusion is reasoning, not verified knowledge, and the calling session decides whether any of it earns a `remember`.
+
+### Which memories reach which project
+
+This is the part worth understanding, and it is what the layer is for. Every memory declares its reach when written:
+
+- `scope: project`, `projects: [a, b]` — reaches those repos and no others
+- `scope: platform`, `platforms: [ios]` — reaches any repo on that platform
+- `scope: general` — reaches everywhere
+
+A reader never widens what the writer declared, so a sibling app on the same platform does not inherit another app's project-scoped constraints. `recall` with `explain: true` reports why each memory was shown and how many were withheld.
+
+**Getting the reach wrong is corrected the same way any other error is** — `remember` is append-only, so re-file the lesson with the right scope and pass `supersedes: ["<its exact title>"]`. Narrowing takes effect: a superseded memory is served only where its correction can follow it, so the caller the correction excludes stops receiving the wider stale copy rather than receiving it alone with nothing to replace it.
+
+**A repo is identified by its folder name**, which is usually right and occasionally not: two repos both called `api` share one identity, so each receives the other's memories. Write a distinct name into a `.om-project` file at the repo root to separate them — `health` reports which repo it thinks is calling and where that name came from.
+
+### Which notes the server serves
+
+Your vault, your notes, your session. The default is the vault's own `user_content_roots`, at the granularity it declares them (`work/active/`, not all of `work/`). Set `mcp_exposed_roots` only if this vault holds material that is **not yours to share** — employer-confidential notes, a client's data.
+
+| key | default | meaning |
+|-----|---------|---------|
+| `mcp_exposed_roots` | *(empty → `user_content_roots`)* | folders whose notes may be read |
+| `mcp_never_expose` | *(empty)* | filenames withheld regardless of folder |
+| `memory_root` | `memories` | where cross-repo memories live |
+| `mcp_inbox` | `inbox` | fallback destination for `record_work` |
+
+`memories/` is never served as an ordinary note whatever the config says — memories carry their own scope, and the note surface would bypass it. A note tagged `private` in frontmatter is never served either.
+
+That holds on **every** surface, including the one that reads across both. `recall` serves a promoted block out of `brain/` when a capture's `promoted:` marker carries an anchor (`promoted: "brain/Gotchas - Engineering#^om-a1b2c3"`), so a foreign repo gets the corrected version rather than the capture as first written. It asks the same exposure predicate as everything else, so a withheld or `private` note is refused there too, and a marker with no anchor still serves nothing. Write anchors with `/om-tidy` — the block you point at is what a session in another repo reads.
+
+> [!note] Keeping vault material out of repos is the contract's job, not this list's.
+> A session can read the vault directly, so narrowing what the server serves prevents nothing on its own. What works is the prohibition injected into the calling session, plus `.claude/om-mcp-audit.jsonl` (gitignored), which records every read with the calling repo.
+
+Run `health` when something that should be in the vault cannot be found — every failure in this layer presents identically as "no results", and that tool is what tells them apart.
diff --git a/.claude/scripts/classify-message.ts b/.claude/scripts/classify-message.ts
index c218575..d08419d 100644
--- a/.claude/scripts/classify-message.ts
+++ b/.claude/scripts/classify-message.ts
@@ -64,7 +64,7 @@ if (toEmit.length > 0) {
parts.push(
"Content classification hints (act on these if the user's message contains relevant info):\n" +
hints +
- "\n\nRemember: use proper templates, add [[wikilinks]], follow CLAUDE.md conventions.",
+ "\n\nRemember: use proper templates, add [[wikilinks]], follow AGENTS.md conventions.",
);
}
if (stopReport !== null) parts.push(stopReport);
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.ts
index d3cb8da..28d54a9 100644
--- a/.claude/scripts/lib/active-hygiene.ts
+++ b/.claude/scripts/lib/active-hygiene.ts
@@ -29,6 +29,11 @@
* by /om-intake; raw exports sitting there are unprocessed by
* definition.
*
+ * 6. LEFTOVER CLAUDE.md (#321) — AGENTS.md is the one instruction file,
+ * and Claude Code reads a CLAUDE.md beside it instead, silently. An
+ * update keeps a CLAUDE.md the user edited, so this says so until the
+ * user's additions are moved to .claude/rules/ and the file is gone.
+ *
* Philosophy: pattern-based, no LLM, conservative. This NUDGES — it never
* moves files. False negatives (missing a cluster) are preferable to false
* positives (nagging about unrelated notes), so the cluster detector leans
@@ -37,8 +42,17 @@
* topic.
*/
-import { readdirSync, readFileSync, statSync, type Dirent } from "node:fs";
+import { existsSync, readdirSync, readFileSync, realpathSync, statSync, type Dirent } from "node:fs";
import { join } from "node:path";
+import {
+ AGENTS_MD_FLAG_BYTES,
+ CLAUDE_MD,
+ GEMINI_MD,
+ GEMINI_SETTINGS,
+ INSTRUCTION_FILE,
+ isRetiredInstructionFile,
+ RETIRED_INSTRUCTION_FILES,
+} from "./instruction-files.ts";
import { escapeRegex } from "./regex.ts";
import { parsePromotedMarker, type PromotedRef } from "./memory-promoted.ts";
import {
@@ -79,6 +93,15 @@ function titleTokens(filename: string): string[] {
.filter((t) => t.length >= 4 && !/^\d+$/.test(t) && !STOPWORDS.has(t));
}
+/**
+ * Numbers in the report that move with no new drift to act on: a note growing
+ * past the threshold, an item a day older. They stay in the message but not
+ * in the report's identity, and neither does the order they sort findings
+ * into (lib/report-key.ts), or a note the agent keeps appending to would
+ * re-show the Stop report every turn — the #252 repeat by another route.
+ */
+export const HYGIENE_VOLATILE_FIELDS: ReadonlySet<string> = new Set(["sizeKb", "ageDays", "oldestDays"]);
+
export type TopicCluster = {
readonly token: string;
readonly files: readonly string[]; // root-level filenames
@@ -120,6 +143,13 @@ export type ActiveHygieneReport = {
readonly openLoops: readonly OpenLoop[];
readonly inboxPressure: InboxPressure | null;
readonly memoryInbox: MemoryInboxPressure | null;
+ /**
+ * Retired instruction files at the vault root beside AGENTS.md that still go
+ * wrong, in RETIRED_INSTRUCTION_FILES order (see LEFTOVER_HARM).
+ */
+ readonly leftoverInstructionFiles: readonly string[];
+ /** AGENTS.md's size once it reaches AGENTS_MD_FLAG_BYTES, else null. `sizeKb`, so a report's identity ignores it (#252). */
+ readonly agentsMd: { readonly sizeKb: number } | null;
};
// ---------------------------------------------------------------------------
@@ -407,9 +437,16 @@ function findOversizedNotes(
} else if (e.isFile() && isMarkdownFilename(e.name)) {
if (isMonolithExempt(e.name)) continue;
// Root-level infrastructure docs (README + translations,
- // CLAUDE.md, …) are repo files, not vault notes — their bulk
+ // AGENTS.md, …) are repo files, not vault notes — their bulk
// is not a split candidate.
- if (relDir === "" && isInfraFilename(e.name, infraRootFilenames))
+ // A retired instruction file is not a note either, whatever the
+ // manifest lists: left over beside AGENTS.md it has its own flag,
+ // which says to move it out, not to split it (#321).
+ if (
+ relDir === "" &&
+ (isInfraFilename(e.name, infraRootFilenames) ||
+ loadsAsRetiredInstructionFile(root, e.name))
+ )
continue;
try {
const size = statSync(join(root, rel)).size;
@@ -644,9 +681,100 @@ export function scanActiveHygiene(
openLoops: findOpenLoops(root, nowMs, openLoopConfig),
inboxPressure: findInboxPressure(root, nowMs),
memoryInbox: findMemoryInbox(root, memoryRoot, nowMs),
+ leftoverInstructionFiles: findLeftoverInstructionFiles(root),
+ agentsMd: agentsMdPastFlag(root),
};
}
+/**
+ * A root file an agent loads as a retired instruction file: the exact name,
+ * or another casing that the filesystem resolves to that same file (Windows,
+ * macOS). On a case-sensitive filesystem a `claude.md` is a plain note, even
+ * beside a real CLAUDE.md, which is a different file there. Same file means
+ * the same real path, which also covers a CLAUDE.md symlinked to it; inode
+ * numbers are not used, as some filesystems report them as 0.
+ */
+function loadsAsRetiredInstructionFile(root: string, name: string): boolean {
+ if (!isRetiredInstructionFile(name)) return false;
+ if (RETIRED_INSTRUCTION_FILES.includes(name)) return true;
+ const real = realPath(join(root, name));
+ return (
+ real !== null &&
+ RETIRED_INSTRUCTION_FILES.some((f) => f.toLowerCase() === name.toLowerCase() && realPath(join(root, f)) === real)
+ );
+}
+
+function realPath(path: string): string | null {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * AGENTS.md's size once it reaches the flag. It is an infrastructure file, so
+ * the oversize scan never sees it, yet a user folding their additions into it
+ * can push it past where Antigravity stops reading, silently.
+ */
+function agentsMdPastFlag(root: string): { sizeKb: number } | null {
+ try {
+ const size = statSync(join(root, INSTRUCTION_FILE)).size;
+ return size >= AGENTS_MD_FLAG_BYTES ? { sizeKb: Math.round(size / 1000) } : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Retired instruction files beside AGENTS.md that still go wrong. Without
+ * AGENTS.md the vault has not upgraded yet, and its old file still carries
+ * everything. A GEMINI.md counts only once Gemini's settings point it at
+ * AGENTS.md: before that, Gemini still reads GEMINI.md, and deleting it would
+ * cut Gemini off.
+ */
+function findLeftoverInstructionFiles(root: string): string[] {
+ if (!existsSync(join(root, INSTRUCTION_FILE))) return [];
+ return RETIRED_INSTRUCTION_FILES.filter(
+ (f) => existsSync(join(root, f)) && (f !== GEMINI_MD || geminiReadsAgentsMd(root)),
+ );
+}
+
+/** Whether .gemini/settings.json lists AGENTS.md in context.fileName. */
+function geminiReadsAgentsMd(root: string): boolean {
+ const names = geminiContextFiles(root);
+ return names.includes(INSTRUCTION_FILE) && !names.includes(GEMINI_MD);
+}
+
+/**
+ * The context files .gemini/settings.json names (context.fileName, a string
+ * or a list), or [] when there is none. Gemini accepts comments and a BOM in
+ * that file, so a strict JSON.parse is tried first and a narrow read of the
+ * fileName value second.
+ */
+function geminiContextFiles(root: string): string[] {
+ let text: string;
+ try {
+ text = readFileSync(join(root, GEMINI_SETTINGS), "utf8").replace(/^\uFEFF/, "");
+ } catch {
+ return [];
+ }
+ try {
+ const names = (JSON.parse(text) as { context?: { fileName?: unknown } }).context?.fileName;
+ return (Array.isArray(names) ? names : [names]).filter((n): n is string => typeof n === "string");
+ } catch {
+ const value = /"fileName"\s*:\s*(\[[^\]]*\]|"[^"]*")/.exec(text)?.[1] ?? "";
+ return [...value.matchAll(/"([^"]*)"/g)].map((m) => m[1]!);
+ }
+}
+
+/** What each retired file does wrong while it stays, and what to do about it. */
+const LEFTOVER_HARM: Readonly<Record<string, string>> = {
+ [CLAUDE_MD]: "Claude Code reads CLAUDE.md and skips AGENTS.md; move your additions to .claude/rules/ and delete it.",
+ [GEMINI_MD]:
+ "Gemini no longer reads GEMINI.md: .gemini/settings.json points it at AGENTS.md. Move anything you added there to AGENTS.md and delete it.",
+};
+
/**
* How many entries a hygiene list prints before "… and N more". The flag's
* headline keeps the full count. Hygiene never degrades under the injection
@@ -683,12 +811,16 @@ const claims = {
openLoops: (n: number) => `${n} note(s) with open follow-ups untouched ${OPEN_LOOP_DAYS}+ days`,
inbox: (n: number) => `${n} raw export(s) sitting in work/meetings/ for ${INBOX_PRESSURE_DAYS}+ days`,
memoryInbox: (n: number) => `${n} cross-repo memory capture(s) awaiting review`,
+ leftover: (file: string) => `${file} present beside AGENTS.md`,
+ agentsMd: (sizeKb: number) => `AGENTS.md is ${sizeKb}KB`,
};
/** The claim of every finding in `report`, in the order the formatter lists them. */
export function hygieneClaims(report: ActiveHygieneReport): string[] {
- const { completedInActive, ungroupedClusters, oversizedNotes, openLoops, inboxPressure, memoryInbox } = report;
+ const { completedInActive, ungroupedClusters, oversizedNotes, openLoops, inboxPressure, memoryInbox, leftoverInstructionFiles, agentsMd } = report;
const out: string[] = [];
+ for (const file of leftoverInstructionFiles) out.push(claims.leftover(file));
+ if (agentsMd !== null) out.push(claims.agentsMd(agentsMd.sizeKb));
if (completedInActive.length > 0) out.push(claims.completed(completedInActive.length));
if (ungroupedClusters.length > 0) out.push(claims.clusters());
if (oversizedNotes.length > 0) out.push(claims.oversized(oversizedNotes.length));
@@ -710,6 +842,8 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
openLoops,
inboxPressure,
memoryInbox,
+ leftoverInstructionFiles,
+ agentsMd,
} = report;
if (
completedInActive.length === 0 &&
@@ -717,12 +851,29 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
oversizedNotes.length === 0 &&
openLoops.length === 0 &&
inboxPressure === null &&
- memoryInbox === null
+ memoryInbox === null &&
+ leftoverInstructionFiles.length === 0 &&
+ agentsMd === null
) {
return [];
}
const lines: string[] = [];
+ // First: until they are gone, an agent reads none of the rest of the
+ // conventions this vault ships in AGENTS.md, or loses what the user added.
+ for (const file of leftoverInstructionFiles) {
+ if (lines.length > 0) lines.push("");
+ const harm = LEFTOVER_HARM[file] ?? "it is a retired instruction file; move anything you added there to AGENTS.md and delete it.";
+ lines.push(`⚠️ ${claims.leftover(file)} — ${harm}`);
+ }
+
+ if (agentsMd !== null) {
+ if (lines.length > 0) lines.push("");
+ lines.push(
+ `⚠️ ${claims.agentsMd(agentsMd.sizeKb)} — Antigravity stopped reading it at ~24,000 bytes, silently, and Codex at ~32 KiB (Antigravity 1.3.0, Codex CLI 0.160.0, measured 2026-10-06, #321). Keep it under 23KB. Move a section an agent can safely skip to a file it reads on demand, word for word, and leave a one-line pointer; Claude Code-only additions go to .claude/rules/.`,
+ );
+ }
+
if (completedInActive.length > 0) {
lines.push(
`⚠️ ${claims.completed(completedInActive.length)} — archive to archive/YYYY/ (ask the agent to run om-project-archive):`,
diff --git a/.claude/scripts/lib/automemory-index.ts b/.claude/scripts/lib/automemory-index.ts
index 688cf5b..5542e8c 100644
--- a/.claude/scripts/lib/automemory-index.ts
+++ b/.claude/scripts/lib/automemory-index.ts
@@ -8,7 +8,7 @@
* original name because it is quoted verbatim in `om-wrap-up.md` and pinned in
* `vault-manifest.json`, and a rename there would break a documented command.
*
- * CLAUDE.md doctrine: `~/.claude/.../memory/MEMORY.md` is an auto-loaded
+ * .claude/rules/memory.md doctrine: `~/.claude/.../memory/MEMORY.md` is an auto-loaded
* index ONLY — pointers to brain/ topic notes, never content. The doctrine
* only holds if the index is derivable: the moment authored knowledge
* accumulates there, it forks the source of truth and silently desyncs
@@ -25,7 +25,7 @@ export type BrainNote = {
};
export const MEMORY_INDEX_HEADER =
- "All durable memory lives in the vault under `brain/` per CLAUDE.md. " +
+ "All durable memory lives in the vault under `brain/` per .claude/rules/memory.md. " +
"This index points to vault topic notes — never write content here. " +
"Regenerated from brain/ frontmatter (see `generate-memory-index.ts`); " +
"hand edits will be overwritten.";
diff --git a/.claude/scripts/lib/correction-sweep.ts b/.claude/scripts/lib/correction-sweep.ts
index 8f72fc8..6684296 100644
--- a/.claude/scripts/lib/correction-sweep.ts
+++ b/.claude/scripts/lib/correction-sweep.ts
@@ -3,7 +3,7 @@
*
* WHY THIS EXISTS
*
- * `CLAUDE.md` Law 2 instructs a sweep: when a fact is corrected, find every
+ * `AGENTS.md` Law 2 instructs a sweep: when a fact is corrected, find every
* restatement and fix them all in the same pass. Nothing in the vault helped do
* it. Every existing check is about a note's SHAPE — frontmatter present,
* wikilinks resolve, size under the split threshold, orphans, stale actives —
@@ -45,7 +45,7 @@
* TWO RULES DECIDED DELIBERATELY, NOT INHERITED
*
* 1. Historical is keyed on BOTH the naming convention AND explicit signals.
- * The convention alone (`CLAUDE.md` § Creating Notes: point-in-time notes
+ * The convention alone (`AGENTS.md` § Creating Notes: point-in-time notes
* carry a date, living notes do not) is the right instinct but too fragile to
* be the only signal — it silently misclassifies the moment someone names a
* file differently. Frontmatter `status` and the archive/log directories say
diff --git a/.claude/scripts/lib/frontmatter.ts b/.claude/scripts/lib/frontmatter.ts
index ecf9bb9..69c2158 100644
--- a/.claude/scripts/lib/frontmatter.ts
+++ b/.claude/scripts/lib/frontmatter.ts
@@ -30,7 +30,7 @@ const SKIP_PATH_SEGMENTS: readonly string[] = [
/**
* Return true if the path is an auto-memory file in ~/.claude/ that should
* be flagged (#81). Only MEMORY.md (the auto-loaded index) is allowed there
- * — all durable knowledge goes to brain/ topic notes per CLAUDE.md.
+ * — all durable knowledge goes to brain/ topic notes per .claude/rules/memory.md.
*
* The path is lexically normalized first (separators unified, `.`/`..`
* segments collapsed) so a path can't dodge the check by spelling the
@@ -84,7 +84,7 @@ const DEFAULT_GLOBAL: readonly string[] = ["date", "description", "tags"];
/**
* Which note type a vault path is, by folder. The folder→type map is
* vault-specific; a future extension point. It mirrors the placement table
- * in CLAUDE.md and /om-vault-audit's per-type rules, which are keyed by
+ * in AGENTS.md and /om-vault-audit's per-type rules, which are keyed by
* folder too. Tags cannot carry this: 1:1 notes are tagged `work-note`, yet
* do not need a work note's `status`.
*/
diff --git a/.claude/scripts/lib/instruction-files.ts b/.claude/scripts/lib/instruction-files.ts
new file mode 100644
index 0000000..c3549cd
--- /dev/null
+++ b/.claude/scripts/lib/instruction-files.ts
@@ -0,0 +1,47 @@
+/**
+ * The vault's instruction files (#321). `AGENTS.md` is the one every agent
+ * reads. A retired one left at the vault root goes wrong silently, each its
+ * own way: Claude Code reads a `CLAUDE.md` in place of `AGENTS.md`, and
+ * Gemini, which now reads `AGENTS.md` through `.gemini/settings.json`, never
+ * loads a `GEMINI.md`, so whatever the user added there is lost. The hygiene
+ * scan and `upgrade-plan` both read this list, so a file retired later is
+ * retired in one place.
+ */
+
+export const INSTRUCTION_FILE = "AGENTS.md";
+export const CLAUDE_MD = "CLAUDE.md";
+export const GEMINI_MD = "GEMINI.md";
+
+/**
+ * Gemini's settings, whose `context.fileName` points it at `AGENTS.md`. A
+ * user's own older copy names no context file, so Gemini reads `GEMINI.md`,
+ * which in the old release only says "read CLAUDE.md".
+ */
+export const GEMINI_SETTINGS = ".gemini/settings.json";
+
+/**
+ * The size `AGENTS.md` stays under. Measured 2026-10-06 (#321): Antigravity
+ * 1.3.0 truncated a 36 KB `AGENTS.md` between byte 23,860 and byte 24,305,
+ * silently, and Codex CLI 0.160.0 stopped consistent with a 32 KiB cap; this
+ * leaves ~2 KB of margin under the first. The template's own
+ * test fails at it.
+ */
+export const AGENTS_MD_MAX_BYTES = 22_000;
+
+/**
+ * Where the hygiene scan flags a vault's own AGENTS.md: 1 KB above the
+ * template's cap, so a user's first additions are not a finding, and still
+ * under byte 23,860, the last one Antigravity was seen to read.
+ */
+export const AGENTS_MD_FLAG_BYTES = 23_000;
+
+export const RETIRED_INSTRUCTION_FILES: readonly string[] = [CLAUDE_MD, GEMINI_MD];
+
+/**
+ * Whether a root file name is a retired instruction file, ignoring case:
+ * Windows and macOS resolve `claude.md` as `CLAUDE.md`, so an agent loads it.
+ */
+export function isRetiredInstructionFile(name: string): boolean {
+ const lower = name.toLowerCase();
+ return RETIRED_INSTRUCTION_FILES.some((f) => f.toLowerCase() === lower);
+}
diff --git a/.claude/scripts/lib/mcp-context.ts b/.claude/scripts/lib/mcp-context.ts
index 714a36f..62c06e9 100644
--- a/.claude/scripts/lib/mcp-context.ts
+++ b/.claude/scripts/lib/mcp-context.ts
@@ -158,8 +158,9 @@ export function createContext(vaultRoot: string, derivedFrom?: string): VaultCon
* reliably: measured, a session refused a direct request and an authority
* override rather than break it. The "when to use it" section is ADVISORY and
* gets skipped whenever a nearer source exists — which is why the install also
- * requires a pointer in the consuming repo's own CLAUDE.md. A server can stop a
- * session doing something; it cannot make one go looking.
+ * requires a pointer in the consuming repo's own instruction file (CLAUDE.md
+ * or AGENTS.md). A server can stop a session doing something; it cannot make
+ * one go looking.
*/
export const INSTRUCTIONS: string = [
"You have access to the user's personal knowledge vault through this server.",
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index 9cca858..d43b119 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -747,7 +747,7 @@ export function isMarkdownFilename(name: string): boolean {
/**
* Extract the root-level entries from `vault-manifest.json`'s `infrastructure`
- * list — files like CLAUDE.md, README.*.md, Home.md that aren't user content
+ * list — files like AGENTS.md, README.*.md, Home.md that aren't user content
* and therefore shouldn't be scanned for open tasks. Glob patterns with `/`
* (e.g. `.claude/**`) are excluded because they target subdirectories.
*
@@ -774,7 +774,7 @@ export function parseInfraRootFilenames(
/**
* True if `filename` matches any of the given root-level infrastructure
- * patterns. Patterns are literal filenames (`CLAUDE.md`) or globs with `*`
+ * patterns. Patterns are literal filenames (`AGENTS.md`) or globs with `*`
* wildcards (`README.*.md`). Other regex metacharacters are escaped so a
* pattern like `foo.md` matches `foo.md`, not `fooXmd`.
*/
diff --git a/.claude/scripts/lib/upgrade-plan.ts b/.claude/scripts/lib/upgrade-plan.ts
index 4a9573b..ec09d8a 100644
--- a/.claude/scripts/lib/upgrade-plan.ts
+++ b/.claude/scripts/lib/upgrade-plan.ts
@@ -16,6 +16,8 @@
* supplies the hash of each file at the release the vault was cloned from.
*/
+import { GEMINI_MD, GEMINI_SETTINGS, INSTRUCTION_FILE, RETIRED_INSTRUCTION_FILES } from "./instruction-files.ts";
+
/** ShardMind's `--json` envelope. */
export type ShardmindEnvelope<T> =
| { readonly schemaVersion: number; readonly command: string; readonly ok: true; readonly result: T }
@@ -70,6 +72,8 @@ export type UpgradeReport = {
readonly conflicts: readonly string[];
/** New in the template. */
readonly added: readonly string[];
+ /** A retired instruction file still in the vault: the user moves their additions out, then deletes it. */
+ readonly move: readonly string[];
/** Nothing to judge: identical, volatile, or the user's own by design. */
readonly unchanged: number;
};
@@ -80,9 +84,69 @@ const empty = (): { -readonly [K in keyof UpgradeReport]: K extends "unchanged"
merged: [],
conflicts: [],
added: [],
+ move: [],
unchanged: 0,
});
+/**
+ * Retired instruction files in an unmanaged clone whose bytes are still those
+ * of the release it was cloned from: the user never edited them, so they are
+ * behind (the update removes them), not a move. Adopt cannot say so itself,
+ * because the latest release has no such file.
+ *
+ * Only each one whose replacement is certain to be in place (`ready`, from
+ * `retiredFileReady`). Until then deleting it would leave an agent pointed at
+ * a missing file.
+ */
+export function untouchedRetiredFiles(
+ vaultHash: (path: string) => string | null,
+ baseHash: (path: string) => string | null,
+ ready: (retired: string) => boolean,
+): string[] {
+ return RETIRED_INSTRUCTION_FILES.filter((p) => {
+ const mine = vaultHash(p);
+ return mine !== null && mine === baseHash(p) && ready(p);
+ });
+}
+
+/**
+ * Whether an adopt leaves in place what replaces a retired file, so an
+ * untouched one may be deleted. A file counts when it already matches the
+ * release, or is behind and `--apply-behind` writes it; ahead or a conflict,
+ * it may stay the user's own old copy.
+ * - CLAUDE.md needs the new AGENTS.md (the old one only points at CLAUDE.md),
+ * and, where the vault has Gemini settings of its own, the new settings too
+ * (old ones send Gemini to GEMINI.md, which also points at CLAUDE.md).
+ * - GEMINI.md needs both, and needs the settings even when the vault has none
+ * (shard-only): they arrive only with the later adopt, and until then
+ * Gemini reads GEMINI.md by default.
+ */
+export function retiredFileReady(plan: AdoptPlan, report: UpgradeReport): (retired: string) => boolean {
+ const inPlace = (path: string) =>
+ report.behind.includes(path) || plan.files.some((f) => f.path === path && f.classification === "matches");
+ const settings = plan.files.find((f) => f.path === GEMINI_SETTINGS);
+ const vaultHasSettings = settings !== undefined && settings.classification !== "shard-only";
+ return (retired) => {
+ if (!inPlace(INSTRUCTION_FILE)) return false;
+ if (retired === GEMINI_MD) return settings === undefined || inPlace(GEMINI_SETTINGS);
+ return !vaultHasSettings || inPlace(GEMINI_SETTINGS);
+ };
+}
+
+/**
+ * `report` with every retired instruction file still in the vault listed
+ * under `move`, unless the update removes it anyway (it is behind: the user
+ * never changed it). A retired file the user edited is neither "ahead" (keep
+ * it) nor a conflict to merge: Claude Code reads a CLAUDE.md in place of
+ * AGENTS.md (#321), so the user moves their additions out and deletes it.
+ * Adopt plans never list these paths, because the release has no such file,
+ * so presence in the vault is what decides.
+ */
+export function withRetiredInstructionFiles(report: UpgradeReport, present: (path: string) => boolean): UpgradeReport {
+ const move = RETIRED_INSTRUCTION_FILES.filter((p) => present(p) && !report.behind.includes(p));
+ return { ...report, move };
+}
+
function modifiedPaths(status: StatusResult | null): Set<string> {
const list = status?.files?.modified ?? [];
return new Set(list.map((m) => (typeof m === "string" ? m : m.path)));
@@ -100,6 +164,8 @@ export function classifyUpdate(plan: UpdatePlan, status: StatusResult | null): U
const r = empty();
const modified = modifiedPaths(status);
for (const f of plan.files) {
+ // Exact names: plan paths are the template's own, never re-cased.
+ if (RETIRED_INSTRUCTION_FILES.includes(f.path) && f.action !== "delete") continue;
switch (f.action) {
case "overwrite":
case "restore_missing":
@@ -161,6 +227,42 @@ export function classifyAdopt(plan: AdoptPlan, baseHash: (path: string) => strin
return r;
}
+/**
+ * Files to resolve to the release's version before the retired instruction
+ * files go, in that order. Each is a conflict (both sides changed it) while a
+ * retired file leaves (behind or a move); changed by the user on top of the
+ * old release, it may still be the old wiring:
+ * - AGENTS.md, whose old version only points at CLAUDE.md, when either
+ * retired file is leaving: the new Gemini settings send Gemini to AGENTS.md
+ * too, so an old one leaves both agents with a dangling pointer;
+ * - .gemini/settings.json, whose old version names no context file, so
+ * Gemini reads GEMINI.md (which only points at CLAUDE.md), when either is
+ * leaving.
+ * Ahead never qualifies: ahead means the template did not change the file
+ * between the two releases, and the release that retires CLAUDE.md changes
+ * both, so an ahead copy is the user's edit of the current one.
+ */
+export function settleFirst(r: UpgradeReport): string[] {
+ const leaving = (p: string) => r.behind.includes(p) || r.move.includes(p);
+ const out: string[] = [];
+ if (r.conflicts.includes(INSTRUCTION_FILE) && RETIRED_INSTRUCTION_FILES.some(leaving)) out.push(INSTRUCTION_FILE);
+ if (r.conflicts.includes(GEMINI_SETTINGS) && RETIRED_INSTRUCTION_FILES.some(leaving)) out.push(GEMINI_SETTINGS);
+ return out;
+}
+
+const SETTLE_WHY: Readonly<Record<string, string>> = {
+ [INSTRUCTION_FILE]:
+ "your copy may be the old one, which only points at CLAUDE.md. This update retires CLAUDE.md and GEMINI.md, and the new Gemini settings send Gemini to AGENTS.md too, so an old copy leaves every agent without the vault's conventions. Take the release's AGENTS.md, then re-add your own changes to it (or to `.claude/rules/local.md`).",
+ [GEMINI_SETTINGS]:
+ "your copy may name no context file, so Gemini keeps reading GEMINI.md, which only points at CLAUDE.md. Take the release's version, which sets `context.fileName` to AGENTS.md, then re-add your own settings.",
+};
+
+function settleSection(files: readonly string[]): string {
+ if (files.length === 0) return "";
+ const lines = files.map((p) => `- \`${p}\` conflicts with the release's: ${SETTLE_WHY[p]}`);
+ return `\n### Settle these first\nResolve each to the release's version in the same update, before the retired instruction files go. A managed update deletes an untouched CLAUDE.md or GEMINI.md in that run; an unmanaged clone keeps them until these are settled.\n${lines.join("\n")}\n`;
+}
+
/** The report as markdown, for the user. Every list in full: a cut list would hide a decision. */
export function formatUpgradeReport(r: UpgradeReport, from: string, to: string): string {
const section = (title: string, what: string, paths: readonly string[]): string =>
@@ -168,9 +270,15 @@ export function formatUpgradeReport(r: UpgradeReport, from: string, to: string):
return [
`## Upgrade plan: ${from} → ${to}`,
`${r.unchanged} file(s) need no judgment.`,
+ settleSection(settleFirst(r)),
section("Behind", "The template changed these and you never did. Taking the new version loses nothing.", r.behind),
section("Ahead — keep, and consider upstreaming", "Changed only in this vault. Kept as yours.", r.ahead),
section("Merged — review", "Changed on both sides; merged without conflict.", r.merged),
+ section(
+ "Move out — retired instruction file",
+ "Claude Code reads CLAUDE.md and skips AGENTS.md while it is here, and Gemini no longer reads GEMINI.md, so anything you added there is lost. Settle the files this report lists first, if any. Then move what you added: from GEMINI.md into `AGENTS.md`; from CLAUDE.md into `.claude/rules/local.md`, or into `AGENTS.md` if every agent needs it. Keep `AGENTS.md` under 23 KB. Then delete the file. If you never edited it, just delete it. Nothing is merged automatically.",
+ r.move,
+ ),
section("Conflicts — your decision", "Changed on both sides (or a new template file where you already have one).", r.conflicts),
section("New in the template", "Added as they are.", r.added),
]
diff --git a/.claude/scripts/lib/wikilinks.ts b/.claude/scripts/lib/wikilinks.ts
index 091c690..804681c 100644
--- a/.claude/scripts/lib/wikilinks.ts
+++ b/.claude/scripts/lib/wikilinks.ts
@@ -11,7 +11,7 @@
*
* Rules:
* - Fenced code blocks AND inline code spans are stripped before
- * extraction — CLAUDE.md and the skills carry literal `[[...]]`
+ * extraction — AGENTS.md and the skills carry literal `[[...]]`
* syntax examples that are documentation, not edges.
* - `!` embed prefix, `|alias` tails (including the table-escaped `\|`
* form), `#heading` and `#^block` fragments are stripped from targets.
diff --git a/.claude/scripts/om-mcp.ts b/.claude/scripts/om-mcp.ts
index 863b163..1d3eaa0 100644
--- a/.claude/scripts/om-mcp.ts
+++ b/.claude/scripts/om-mcp.ts
@@ -12,9 +12,9 @@
* launcher, which adds the type-stripping flags this file needs.
*
* The server is only HALF the install. The other half is a short section in the
- * consuming repo's own CLAUDE.md, and that is not documentation garnish: a
- * prohibition in the MCP `instructions` field propagates into a calling session
- * reliably, while a positive instruction to go and consult the vault is
+ * consuming repo's own instruction file (CLAUDE.md or AGENTS.md), and that is
+ * not documentation garnish: a prohibition in the MCP `instructions` field
+ * propagates into a calling session reliably, while a positive instruction to go and consult the vault is
* advisory and gets skipped whenever a nearer source exists. This server can
* stop a session doing something; only the project's own law makes one look.
*/
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 06620db..8347a18 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -402,7 +402,7 @@ function openTasks(): Built {
// the Electron app on macOS). Order matters: project tasks in work/active/
// surface first, then vault-root notes (which is where daily notes live by
// Obsidian's default — empirically the dominant task store in user vaults).
- // Infra files (CLAUDE.md, README.*.md, …) are excluded so the section is
+ // Infra files (AGENTS.md, README.*.md, …) are excluded so the section is
// user content only. Paths use forward slashes so the output reads the same
// in Claude's context on any OS.
const sources = [
diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.ts
index 2a940c4..a9ceb11 100644
--- a/.claude/scripts/stop-checklist.ts
+++ b/.claude/scripts/stop-checklist.ts
@@ -65,6 +65,7 @@ import { HANDOFF_DIR, pruneHandoffs, writeHandoff } from "./lib/stop-handoff.ts"
import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, MOD_PREFACE, stopSummary } from "./lib/stop-report.ts";
import {
formatActiveHygiene,
+ HYGIENE_VOLATILE_FIELDS,
hygieneClaims,
parseMemoryRoot,
parseOpenLoopConfig,
@@ -158,13 +159,6 @@ const message =
? "\n\nVault Hygiene (drift detected):\n" + hygieneLines.join("\n")
: "");
-// Numbers that move with no new drift to act on: a note growing past the
-// threshold, an item a day older. They stay in the message but not in the
-// report's identity, and neither does the order they sort findings into
-// (lib/report-key.ts), or a note the agent keeps appending to would re-show
-// the report every turn — the #252 repeat by another route.
-const VOLATILE_FIELDS = new Set(["sizeKb", "ageDays", "oldestDays"]);
-
// SessionEnd (and any input without a recognisable event, the safe default)
// always reports. Stop reports when the findings differ from the last report
// this session was shown: the first Stop, and any change since, including
@@ -173,7 +167,7 @@ const VOLATILE_FIELDS = new Set(["sizeKb", "ageDays", "oldestDays"]);
const sessionId = input?.session_id;
const isStop = input?.hook_event_name === "Stop";
const hasSession = typeof sessionId === "string" && sessionId !== "";
-const key = reportKey({ checklist, report }, VOLATILE_FIELDS);
+const key = reportKey({ checklist, report }, HYGIENE_VOLATILE_FIELDS);
const claims = hygieneClaims(report);
if (omMod === "report") {
diff --git a/.claude/scripts/tests/active-hygiene.test.ts b/.claude/scripts/tests/active-hygiene.test.ts
index 0653076..1109f37 100644
--- a/.claude/scripts/tests/active-hygiene.test.ts
+++ b/.claude/scripts/tests/active-hygiene.test.ts
@@ -8,9 +8,12 @@
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import {
+ existsSync,
mkdirSync,
+ readdirSync,
mkdtempSync,
rmSync,
+ symlinkSync,
utimesSync,
writeFileSync,
} from "node:fs";
@@ -18,6 +21,7 @@ import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import {
HYGIENE_LIST_CAP,
+ HYGIENE_VOLATILE_FIELDS,
MONOLITH_BYTES,
OPEN_LOOP_DAYS,
countOpenLoops,
@@ -33,6 +37,8 @@ import {
walkMarkdown,
} from "../lib/active-hygiene.ts";
+import { AGENTS_MD_FLAG_BYTES, AGENTS_MD_MAX_BYTES } from "../lib/instruction-files.ts";
+import { reportKey } from "../lib/report-key.ts";
import { rmTemp } from "./_helpers.ts";
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -426,6 +432,8 @@ describe("scanActiveHygiene — detectors", () => {
openLoops: [],
inboxPressure: null,
memoryInbox: { count: 4, oldestDays: 2, namedOnly: 0 },
+ leftoverInstructionFiles: [],
+ agentsMd: null,
});
const text = lines.join("\n");
assert.match(text, /COPYING it/);
@@ -446,6 +454,8 @@ describe("scanActiveHygiene — detectors", () => {
openLoops: [],
inboxPressure: null,
memoryInbox: null,
+ leftoverInstructionFiles: [],
+ agentsMd: null,
});
const atCap = report(HYGIENE_LIST_CAP);
assert.equal(atCap.filter((l) => l.startsWith(" - ")).length, 3 * HYGIENE_LIST_CAP);
@@ -539,6 +549,8 @@ describe("formatActiveHygiene", () => {
openLoops: [{ path: "work/1-1/A 2026-01-01.md", ageDays: 20, openItems: 2 }],
inboxPressure: null,
memoryInbox: null,
+ leftoverInstructionFiles: [],
+ agentsMd: null,
});
const text = lines.join("\n");
assert.match(text, /marked done but still in active\//);
@@ -575,3 +587,195 @@ describe("open loops — a capped list keeps its membership as time passes", ()
}
});
});
+
+describe("leftover CLAUDE.md beside AGENTS.md (#321)", () => {
+ // A vault upgraded past the single-instruction-file release keeps a
+ // CLAUDE.md the user edited (their bytes survive the update). Claude Code
+ // then reads CLAUDE.md and silently skips AGENTS.md, so the hygiene scan
+ // says so at every session boundary until it is moved out.
+ const withFiles = (names: readonly string[], run: (root: string) => void): void => {
+ const root = mkdtempSync(join(tmpdir(), "leftover-claude-md-"));
+ try {
+ for (const n of names) writeFileSync(join(root, n), "# Vault\n");
+ run(root);
+ } finally {
+ rmTemp(root);
+ }
+ };
+
+ test("flags a CLAUDE.md sitting beside AGENTS.md, with what to do about it", () => {
+ withFiles(["AGENTS.md", "CLAUDE.md"], (root) => {
+ const report = scanActiveHygiene(root, NOW, DEFAULTS);
+ assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
+ const text = formatActiveHygiene(report).join("\n");
+ assert.match(
+ text,
+ /CLAUDE\.md present beside AGENTS\.md — Claude Code reads CLAUDE\.md and skips AGENTS\.md; move your additions to \.claude\/rules\/ and delete it\./,
+ );
+ });
+ });
+
+ /** Write .gemini/settings.json with the given context.fileName (or none). */
+ const geminiSettings = (root: string, fileName?: string[]): void => {
+ mkdirSync(join(root, ".gemini"), { recursive: true });
+ writeFileSync(join(root, ".gemini/settings.json"), JSON.stringify(fileName ? { context: { fileName } } : { hooks: {} }));
+ };
+
+ test("flags a GEMINI.md beside AGENTS.md once Gemini's settings point it at AGENTS.md, so GEMINI.md is never loaded", () => {
+ withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
+ geminiSettings(root, ["AGENTS.md"]);
+ const report = scanActiveHygiene(root, NOW, DEFAULTS);
+ assert.deepEqual(report.leftoverInstructionFiles, ["GEMINI.md"], "a GEMINI.md is not a leftover CLAUDE.md");
+ assert.match(formatActiveHygiene(report).join("\n"), /GEMINI\.md present beside AGENTS\.md — Gemini no longer reads GEMINI\.md/);
+ });
+ withFiles(["AGENTS.md", "CLAUDE.md"], (root) => {
+ geminiSettings(root, ["AGENTS.md"]);
+ assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, ["CLAUDE.md"]);
+ });
+ });
+
+ test("silent about a GEMINI.md that Gemini still reads: its settings name no AGENTS.md, or there are none", () => {
+ // A vault that kept its own older settings: Gemini reads GEMINI.md as its
+ // only context file, so telling the user to delete it would cut Gemini off.
+ withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
+ geminiSettings(root);
+ assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
+ });
+ withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
+ geminiSettings(root, ["GEMINI.md"]);
+ assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
+ });
+ withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
+ assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
+ });
+ // Both named: Gemini loads GEMINI.md as well, so it is not a leftover.
+ withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
+ geminiSettings(root, ["AGENTS.md", "GEMINI.md"]);
+ assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, []);
+ });
+ });
+
+ test("Gemini settings with comments or a BOM, which Gemini accepts, are still read", () => {
+ withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
+ mkdirSync(join(root, ".gemini"), { recursive: true });
+ writeFileSync(
+ join(root, ".gemini/settings.json"),
+ '{\n // where Gemini looks\n "context": { "fileName": ["AGENTS.md"] },\n /* hooks */ "hooks": {}\n}\n',
+ );
+ assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, ["GEMINI.md"]);
+ });
+ });
+
+ test("silent with AGENTS.md alone", () => {
+ withFiles(["AGENTS.md"], (root) => {
+ const report = scanActiveHygiene(root, NOW, DEFAULTS);
+ assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), false);
+ assert.deepEqual(formatActiveHygiene(report), []);
+ });
+ });
+
+ test("a large leftover CLAUDE.md is the leftover flag only, never a note to SPLIT", () => {
+ // CLAUDE.md left the manifest's infrastructure list in the same release,
+ // so the root-infra exemption no longer covers it. Telling the user to
+ // split a file the other flag says to move out and delete would be two
+ // contradictory instructions about one file.
+ withFiles(["AGENTS.md"], (root) => {
+ writeFileSync(join(root, "CLAUDE.md"), "x".repeat(MONOLITH_BYTES + 1000));
+ const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
+ assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
+ assert.deepEqual(report.oversizedNotes, []);
+ });
+ });
+
+ test("a differently cased claude.md flags exactly where the filesystem resolves it as CLAUDE.md", () => {
+ // Windows and macOS resolve names case-insensitively, so Claude Code
+ // finds a `claude.md` there as CLAUDE.md, and the flag must say so; on
+ // a case-sensitive filesystem neither finds it.
+ withFiles(["AGENTS.md", "claude.md"], (root) => {
+ const resolves = existsSync(join(root, "CLAUDE.md"));
+ assert.equal(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles.includes("CLAUDE.md"), resolves);
+ });
+ });
+
+ test("a large claude.md is the leftover flag where it resolves as CLAUDE.md, and an oversized note where it does not", () => {
+ withFiles(["AGENTS.md"], (root) => {
+ writeFileSync(join(root, "claude.md"), "x".repeat(MONOLITH_BYTES + 1000));
+ const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
+ if (existsSync(join(root, "CLAUDE.md"))) {
+ // Windows, macOS: Claude Code loads it, so it is a leftover, never a note to split.
+ assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
+ assert.deepEqual(report.oversizedNotes, []);
+ } else {
+ // A case-sensitive filesystem: no agent loads it, so it is a plain note, and still seen.
+ assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), false);
+ assert.deepEqual(report.oversizedNotes.map((n) => n.path), ["claude.md"]);
+ }
+ });
+ });
+
+ test("AGENTS.md near where Antigravity stops reading is flagged, with the agent that cuts it off", () => {
+ withFiles([], (root) => {
+ writeFileSync(join(root, "AGENTS.md"), "x".repeat(AGENTS_MD_FLAG_BYTES));
+ const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
+ assert.deepEqual(report.agentsMd, { sizeKb: 23 });
+ assert.match(formatActiveHygiene(report).join("\n"), /AGENTS\.md is 23KB[\s\S]*Antigravity stopped reading it at ~24,000 bytes/);
+ });
+ withFiles([], (root) => {
+ writeFileSync(join(root, "AGENTS.md"), "x".repeat(AGENTS_MD_FLAG_BYTES - 1));
+ assert.equal(scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]).agentsMd, null);
+ });
+ });
+
+ test("a vault's AGENTS.md has room to grow past the template's own cap before it is flagged", () => {
+ // The template's test holds the shipped file under AGENTS_MD_MAX_BYTES;
+ // the vault flag sits nearer the measured cutoff (byte 23,860 was still
+ // read), so a user's first additions are not a finding.
+ assert.ok(AGENTS_MD_FLAG_BYTES >= AGENTS_MD_MAX_BYTES + 1000);
+ assert.ok(AGENTS_MD_FLAG_BYTES < 23_860);
+ });
+
+ test("editing an AGENTS.md that is already flagged is not a new finding (#252)", () => {
+ const keyAt = (bytes: number) =>
+ withScan(bytes, (report) => reportKey({ report }, HYGIENE_VOLATILE_FIELDS));
+ const withScan = <T,>(bytes: number, run: (r: ReturnType<typeof scanActiveHygiene>) => T): T => {
+ let out!: T;
+ withFiles([], (root) => {
+ writeFileSync(join(root, "AGENTS.md"), "x".repeat(bytes));
+ out = run(scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]));
+ });
+ return out;
+ };
+ assert.equal(keyAt(AGENTS_MD_FLAG_BYTES + 10), keyAt(AGENTS_MD_FLAG_BYTES + 900));
+ assert.notEqual(keyAt(AGENTS_MD_FLAG_BYTES - 1), keyAt(AGENTS_MD_FLAG_BYTES + 10));
+ });
+
+ test("a CLAUDE.md symlinked to a large claude.md is the leftover flag only, never a note to SPLIT", () => {
+ withFiles(["AGENTS.md"], (root) => {
+ writeFileSync(join(root, "claude.md"), "x".repeat(MONOLITH_BYTES + 1000));
+ try {
+ symlinkSync("claude.md", join(root, "CLAUDE.md"));
+ } catch {
+ return; // no symlink rights (Windows without developer mode), or the name is taken (case-insensitive)
+ }
+ const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
+ assert.equal(report.leftoverInstructionFiles.includes("CLAUDE.md"), true);
+ assert.deepEqual(report.oversizedNotes, []);
+ });
+ });
+
+ test("on a case-sensitive filesystem, a claude.md beside a real CLAUDE.md is still a note that can be oversized", () => {
+ withFiles(["AGENTS.md", "CLAUDE.md"], (root) => {
+ writeFileSync(join(root, "claude.md"), "x".repeat(MONOLITH_BYTES + 1000));
+ const caseSensitive = readdirSync(root).includes("claude.md") && readdirSync(root).includes("CLAUDE.md");
+ if (!caseSensitive) return; // Windows, macOS: the write above went to CLAUDE.md itself
+ const report = scanActiveHygiene(root, NOW, DEFAULTS, ["AGENTS.md"]);
+ assert.deepEqual(report.oversizedNotes.map((n) => n.path), ["claude.md"]);
+ });
+ });
+
+ test("silent for a vault that has not upgraded yet (CLAUDE.md, no AGENTS.md)", () => {
+ withFiles(["CLAUDE.md"], (root) => {
+ assert.equal(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles.includes("CLAUDE.md"), false);
+ });
+ });
+});
diff --git a/.claude/scripts/tests/agent-docs-sync.test.ts b/.claude/scripts/tests/agent-docs-sync.test.ts
index 6e326fb..a3a4f95 100644
--- a/.claude/scripts/tests/agent-docs-sync.test.ts
+++ b/.claude/scripts/tests/agent-docs-sync.test.ts
@@ -1,29 +1,163 @@
/**
- * Duplication-guard (#115): AGENTS.md and GEMINI.md are the same pointer
- * doc by design — two filenames because two agent ecosystems look for
- * them, one content because they say the same thing. When duplication IS
- * the design, guard it with a test so the copies can't drift silently.
- * (The pattern matters more than the instance: apply it wherever the same
- * instruction text must exist in two places that can't reference each
- * other.)
+ * Layout pin (#321): `AGENTS.md` is the vault's one instruction file.
+ *
+ * Every agent reads it: Codex and Antigravity natively, Grok once the folder
+ * is trusted, Gemini through `.gemini/settings.json`'s `context.fileName`, and
+ * Claude Code natively when no `CLAUDE.md` is present. Claude-only guidance
+ * lives in `.claude/rules/*.md`, which Claude Code loads beside it.
+ *
+ * What would quietly undo that:
+ * - a `CLAUDE.md` back at the root: Claude Code reads it and skips
+ * `AGENTS.md` without saying so;
+ * - a `GEMINI.md` back at the root, or the Gemini setting dropped: Gemini
+ * falls back to looking for `GEMINI.md`;
+ * - `AGENTS.md` turned back into a pointer at another file, which Codex
+ * never follows unless told to;
+ * - `AGENTS.md` growing past what the agents read: Antigravity cuts it off
+ * silently past ~24,000 bytes (measured), Codex past ~32 KiB.
*/
import { test, describe } from "node:test";
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { AGENTS_MD_MAX_BYTES } from "../lib/instruction-files.ts";
+
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
-describe("agent docs sync", () => {
- test("AGENTS.md and GEMINI.md are byte-identical", () => {
- const agents = readFileSync(resolve(repoRoot, "AGENTS.md"), "utf-8");
- const gemini = readFileSync(resolve(repoRoot, "GEMINI.md"), "utf-8");
- assert.equal(
- agents,
- gemini,
- "AGENTS.md and GEMINI.md drifted — they are the same pointer doc by design; edit both or neither",
+describe("AGENTS.md is the one instruction file (#321)", () => {
+ const agentsPath = resolve(repoRoot, "AGENTS.md");
+
+ test("AGENTS.md exists and carries the conventions itself, not a pointer to another file", () => {
+ assert.ok(existsSync(agentsPath), "AGENTS.md is missing from the vault root");
+ const text = readFileSync(agentsPath, "utf-8");
+ // Headings every agent needs at the moment of acting (#321: these stay
+ // inline because a skipped pointer means a misplaced note or a record
+ // never written).
+ for (const heading of ["## Vault Structure", "### Note Types", "### Decision Records", "## Write-Correctness Laws", "## Rules"]) {
+ assert.ok(text.includes(`\n${heading}\n`), `AGENTS.md lost its "${heading}" section`);
+ }
+ assert.doesNotMatch(text, /Read `CLAUDE\.md` for all vault conventions/, "AGENTS.md is a pointer to CLAUDE.md again");
+ });
+
+ test(`AGENTS.md stays under ${AGENTS_MD_MAX_BYTES} bytes`, () => {
+ const size = statSync(agentsPath).size;
+ assert.ok(
+ size < AGENTS_MD_MAX_BYTES,
+ `AGENTS.md is ${size} bytes, at or over the ${AGENTS_MD_MAX_BYTES}-byte threshold. Antigravity silently stops reading it at ~24,000 bytes (and Codex at ~32 KiB). Move a section an agent can safely skip to a file it reads on demand, verbatim, and leave a one-line pointer (#321).`,
+ );
+ });
+
+ test("AGENTS.md is LF-only, so its size is the same on every checkout", () => {
+ // .gitattributes forces eol=lf; a CRLF checkout would add a byte per
+ // line (~300) and move the file toward the cap on Windows only.
+ assert.ok(!readFileSync(agentsPath, "utf-8").includes("\r"), "AGENTS.md has CRLF line endings");
+ });
+
+ test("no CLAUDE.md or GEMINI.md at the vault root", () => {
+ // Claude Code reads a CLAUDE.md in place of AGENTS.md, silently.
+ assert.ok(!existsSync(resolve(repoRoot, "CLAUDE.md")), "CLAUDE.md is back at the root: Claude Code reads it and skips AGENTS.md");
+ assert.ok(!existsSync(resolve(repoRoot, "GEMINI.md")), "GEMINI.md is back at the root: Gemini reads AGENTS.md through .gemini/settings.json instead");
+ });
+
+ test(".gemini/settings.json points Gemini at AGENTS.md", () => {
+ const settings = JSON.parse(readFileSync(resolve(repoRoot, ".gemini/settings.json"), "utf-8")) as {
+ context?: { fileName?: unknown };
+ };
+ const names = settings.context?.fileName;
+ assert.ok(Array.isArray(names) && names.includes("AGENTS.md"), ".gemini/settings.json context.fileName must list AGENTS.md");
+ });
+
+ /** The `.claude/rules/*.md` files AGENTS.md's pointers name. */
+ const pointerTargets = (): string[] => [
+ ...new Set([...readFileSync(agentsPath, "utf-8").matchAll(/`(\.claude\/rules\/[\w.-]+\.md)`/g)].map((m) => m[1]!)),
+ ];
+ const SHARED_LINE =
+ "Shared section: Claude Code and Grok load it at session start; other agents read it when AGENTS.md points here.";
+
+ test("every rules file AGENTS.md points at exists, is non-empty, and says it is shared", () => {
+ const targets = pointerTargets();
+ assert.ok(targets.length > 0, "AGENTS.md names no .claude/rules/ file: the moved sections have no pointer");
+ for (const t of targets) {
+ const p = resolve(repoRoot, t);
+ assert.ok(existsSync(p), `AGENTS.md points at ${t}, which does not exist`);
+ const text = readFileSync(p, "utf-8");
+ assert.ok(text.trim().length > 0, `${t} is empty`);
+ assert.equal(text.split("\n")[0], SHARED_LINE, `${t} does not open with the shared-section line`);
+ }
+ });
+
+ test("every shared rules file is pointed at by AGENTS.md, so no agent but Claude Code and Grok is cut off from it", () => {
+ const targets = new Set(pointerTargets());
+ const dir = resolve(repoRoot, ".claude/rules");
+ for (const f of readdirSync(dir).filter((n) => n.endsWith(".md"))) {
+ const shared = readFileSync(resolve(dir, f), "utf-8").startsWith(SHARED_LINE);
+ assert.equal(targets.has(`.claude/rules/${f}`), shared, `.claude/rules/${f}: ${shared ? "shared but AGENTS.md never points at it" : "Claude-only but AGENTS.md points at it"}`);
+ }
+ });
+
+ test("every file AGENTS.md points at is claimed by no removable module, so every module selection installs it", () => {
+ // A file claimed by a removable module disappears when that module is
+ // deselected, and a Codex-only vault would then follow a pointer to
+ // nothing. Shared files must be core: claimed by no removable module.
+ const schema = readFileSync(resolve(repoRoot, ".shardmind/shard-schema.yaml"), "utf-8");
+ const modulesBlock = schema.slice(schema.indexOf("\nmodules:\n"), schema.indexOf("\nsignals:\n"));
+ const modules = modulesBlock.split(/\n (?=[a-z_]+:\n)/).slice(1);
+ // A module's `paths`, written either as a flow list (`paths: ["a/"]`)
+ // or as a block list of `- "a/"` lines; the schema uses both.
+ const pathsOf = (m: string): string[] => {
+ const flow = /\n paths: \[([^\]]*)\]/.exec(m);
+ if (flow) return [...flow[1]!.matchAll(/"([^"]+)"/g)].map((x) => x[1]!);
+ const at = m.indexOf("\n paths:\n");
+ if (at < 0) return [];
+ const items: string[] = [];
+ // Every line until the next key at module level or above; blank
+ // lines, comments, a trailing comment or an unquoted item (spaces
+ // and all) must not end the list early or cut an item short.
+ for (const line of m.slice(at + "\n paths:\n".length).split("\n")) {
+ if (/^ {0,4}[^\s#]/.test(line)) break;
+ const item = /^\s+-\s+(?:"([^"]*)"|'([^']*)'|(.*?))\s*(?:#.*)?$/.exec(line);
+ if (item) items.push(item[1] ?? item[2] ?? item[3]!);
+ }
+ return items;
+ };
+ assert.ok(pathsOf(modules.find((m) => m.startsWith("brain:"))!).includes("brain/"), "pathsOf misreads a flow-style list");
+ const claudeList = pathsOf(modules.find((m) => m.startsWith("claude:"))!);
+ assert.ok(claudeList.includes(".claude/agents/") && claudeList.includes(".claude-plugin/"), "pathsOf misreads a block list");
+ const removablePaths = modules.filter((m) => /\n removable: true\b/.test(m)).flatMap(pathsOf);
+ assert.ok(modules.length > 0, "found no modules in shard-schema.yaml");
+ const claims = (path: string, claim: string) => (claim.endsWith("/") ? path.startsWith(claim) : path === claim);
+ for (const t of [...pointerTargets(), "AGENTS.md"]) {
+ const by = removablePaths.find((c) => claims(t, c));
+ assert.equal(by, undefined, `${t} is claimed by a removable module (${by}), so a vault without that module loses it`);
+ }
+ // And the Claude module, removable or not, claims only the Claude-only files.
+ const claude = modules.find((m) => m.startsWith("claude:"))!;
+ const claudePaths = pathsOf(claude);
+ assert.ok(!claudePaths.includes(".claude/rules/"), "the Claude module claims all of .claude/rules/, shared files included");
+ const dir = resolve(repoRoot, ".claude/rules");
+ const claudeOnly = readdirSync(dir)
+ .filter((f) => f.endsWith(".md") && !readFileSync(resolve(dir, f), "utf-8").startsWith(SHARED_LINE))
+ .map((f) => `.claude/rules/${f}`)
+ .sort();
+ assert.deepEqual(
+ claudePaths.filter((p) => p.startsWith(".claude/rules/")).sort(),
+ claudeOnly,
+ "the Claude module must claim exactly the Claude-only rules files",
);
});
+
+ test("every .claude/rules/*.md exists and is non-empty", () => {
+ const dir = resolve(repoRoot, ".claude/rules");
+ assert.ok(existsSync(dir), ".claude/rules/ is missing: the Claude-only guidance has nowhere to load from");
+ const files = readdirSync(dir).filter((f) => f.endsWith(".md"));
+ for (const name of ["skills.md", "subagents.md", "memory.md", "hooks-and-mod.md"]) {
+ assert.ok(files.includes(name), `.claude/rules/${name} is missing`);
+ }
+ for (const f of files) {
+ assert.ok(readFileSync(resolve(dir, f), "utf-8").trim().length > 0, `.claude/rules/${f} is empty`);
+ }
+ });
});
diff --git a/.claude/scripts/tests/generate-changelog.test.ts b/.claude/scripts/tests/generate-changelog.test.ts
index e4893b3..aa7c517 100644
--- a/.claude/scripts/tests/generate-changelog.test.ts
+++ b/.claude/scripts/tests/generate-changelog.test.ts
@@ -7,7 +7,7 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import {
@@ -17,6 +17,7 @@ import {
toFingerprintKey,
pickMarkers,
findLatestOpenFingerprint,
+ compareFingerprintKeys,
bumpPluginJsonVersion,
bumpShardYamlVersion,
PLUGIN_JSON,
@@ -146,7 +147,6 @@ describe("toFingerprintKey", () => {
describe("pickMarkers", () => {
const GLOBS = [
- "CLAUDE.md",
"AGENTS.md",
".mcp.json",
".claude/**",
@@ -429,3 +429,58 @@ describe("findLatestOpenFingerprint", () => {
assert.equal(findLatestOpenFingerprint(fp), "v3.7");
});
});
+
+describe("version detection across the AGENTS.md release (#321)", () => {
+ // The rule /om-vault-upgrade applies to a vault with no manifest version:
+ // a fingerprint matches when every `exists` path is there and no `missing`
+ // path is; the newest match wins. Run here against the real manifest and
+ // this repo's own tree, so the entries the release depends on are pinned.
+ // Only the fingerprints up to v10.0 take part, and v10.0's own `missing`
+ // is ignored: a later release adds both, and neither changes how a v9.1
+ // or v10.0 vault is told apart.
+ type Fp = { exists: string[]; missing?: string[] };
+ const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+ const all = (
+ JSON.parse(readFileSync(join(repoRoot, "vault-manifest.json"), "utf-8")) as { version_fingerprints: Record<string, Fp> }
+ ).version_fingerprints;
+ const fingerprints: Record<string, Fp> = Object.fromEntries(
+ Object.entries(all)
+ .filter(([key]) => compareFingerprintKeys(key, "v10.0") <= 0)
+ .map(([key, fp]) => [key, key === "v10.0" ? { exists: fp.exists } : fp]),
+ );
+ /** This repo's tree, with some paths forced present or absent. */
+ const vault = (overrides: Record<string, boolean>) => (p: string) =>
+ p in overrides ? overrides[p]! : existsSync(join(repoRoot, p));
+ const detect = (has: (p: string) => boolean): string | null => {
+ let best: string | null = null;
+ for (const [key, fp] of Object.entries(fingerprints)) {
+ if (!fp.exists.every(has) || (fp.missing ?? []).some(has)) continue;
+ if (best === null || compareFingerprintKeys(key, best) > 0) best = key;
+ }
+ return best;
+ };
+ const RULES = [".claude/rules/skills.md", ".claude/rules/subagents.md", ".claude/rules/memory.md", ".claude/rules/hooks-and-mod.md"];
+ const without = (paths: readonly string[]) => Object.fromEntries(paths.map((p) => [p, false]));
+
+ test("a v10 vault reads as v10.0", () => {
+ assert.equal(detect(vault({ "CLAUDE.md": false, "GEMINI.md": false })), "v10.0");
+ });
+
+ test("a v10 vault with a leftover CLAUDE.md (the case the upgrade guards target) still reads as v10.0", () => {
+ assert.equal(detect(vault({ "CLAUDE.md": true })), "v10.0");
+ });
+
+ test("a v9.1 vault, with CLAUDE.md and GEMINI.md and no .claude/rules/, reads as v9.1", () => {
+ assert.equal(detect(vault({ ...without(RULES), "CLAUDE.md": true, "GEMINI.md": true })), "v9.1");
+ });
+
+ test("the newest fingerprint in the manifest is the open one, so the next release can close it", () => {
+ const newest = Object.keys(all).sort(compareFingerprintKeys).at(-1);
+ assert.equal(findLatestOpenFingerprint(all), newest);
+ });
+
+ test("v9.1 is closed by a v10.0 marker, so the two never both match", () => {
+ const v91 = all["v9.1"]!;
+ assert.ok(v91.missing?.some((p) => all["v10.0"]!.exists.includes(p)), "v9.1's missing must name a file v10.0 requires");
+ });
+});
diff --git a/.claude/scripts/tests/manifest-check.test.ts b/.claude/scripts/tests/manifest-check.test.ts
index 7d1521c..4422923 100644
--- a/.claude/scripts/tests/manifest-check.test.ts
+++ b/.claude/scripts/tests/manifest-check.test.ts
@@ -19,14 +19,14 @@ import {
import { rmTemp } from "./_helpers.ts";
/** The real manifest's shape, in miniature. */
-const GLOBS = ["CLAUDE.md", ".claude/**", "templates/**", "brain/Skills.md"];
+const GLOBS = ["AGENTS.md", ".claude/**", "templates/**", "brain/Skills.md"];
describe("globToRegex", () => {
test("exact string (no wildcards)", () => {
- const r = globToRegex("CLAUDE.md");
- assert.ok(r.test("CLAUDE.md"));
+ const r = globToRegex("AGENTS.md");
+ assert.ok(r.test("AGENTS.md"));
// dots must be escaped — a slash-separator should not match a dot
- assert.ok(!r.test("CLAUDExmd"));
+ assert.ok(!r.test("AGENTSxmd"));
});
test("double-star matches any depth", () => {
@@ -62,9 +62,9 @@ describe("globToRegex", () => {
});
test("anchors with ^ and $ (no prefix/suffix bleed)", () => {
- const r = globToRegex("CLAUDE.md");
- assert.ok(!r.test("xCLAUDE.md"));
- assert.ok(!r.test("CLAUDE.mdx"));
+ const r = globToRegex("AGENTS.md");
+ assert.ok(!r.test("xAGENTS.md"));
+ assert.ok(!r.test("AGENTS.mdx"));
});
test("plus and other regex specials are escaped", () => {
@@ -76,7 +76,7 @@ describe("globToRegex", () => {
describe("isCovered", () => {
test("exact-string glob matches the same string", () => {
- assert.equal(isCovered("CLAUDE.md", GLOBS), true);
+ assert.equal(isCovered("AGENTS.md", GLOBS), true);
assert.equal(isCovered("brain/Skills.md", GLOBS), true);
});
@@ -95,8 +95,8 @@ describe("isCovered", () => {
});
test("exact-string glob does NOT match prefix variants", () => {
- assert.equal(isCovered("CLAUDE.md.bak", GLOBS), false);
- assert.equal(isCovered("x/CLAUDE.md", GLOBS), false);
+ assert.equal(isCovered("AGENTS.md.bak", GLOBS), false);
+ assert.equal(isCovered("x/AGENTS.md", GLOBS), false);
});
// The manifest globs are POSIX, but the directory walk built its paths with
diff --git a/.claude/scripts/tests/mcp-caller.test.ts b/.claude/scripts/tests/mcp-caller.test.ts
index d075b78..33bff4e 100644
--- a/.claude/scripts/tests/mcp-caller.test.ts
+++ b/.claude/scripts/tests/mcp-caller.test.ts
@@ -223,7 +223,7 @@ describe("recognising the vault itself", () => {
describe("sanitising text that crosses back to the caller", () => {
test("a Windows path in a real fs error is stripped", () => {
- const msg = "ENOENT: no such file or directory, lstat 'C:\\Users\\someone\\vault\\CLAUDE.md'";
+ const msg = "ENOENT: no such file or directory, lstat 'C:\\Users\\someone\\vault\\AGENTS.md'";
const out = sanitize(msg);
assert.ok(!out.includes("Users"), out);
assert.ok(!out.includes("someone"), out);
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 94d085d..1e3c941 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -407,7 +407,7 @@ describe("MACHINERY_DIRS", () => {
// 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/CLAUDE.md", MACHINERY_DIRS),
+ isSkippedPath(".shardmind/templates/AGENTS.md", MACHINERY_DIRS),
true,
);
assert.equal(
@@ -740,14 +740,14 @@ describe("parseInfraRootFilenames", () => {
});
test("returns empty when infrastructure field is not an array", () => {
assert.deepEqual(
- parseInfraRootFilenames(JSON.stringify({ infrastructure: "CLAUDE.md" })),
+ parseInfraRootFilenames(JSON.stringify({ infrastructure: "AGENTS.md" })),
[],
);
});
test("returns only the root-level entries (filters out anything containing '/')", () => {
const manifest = JSON.stringify({
infrastructure: [
- "CLAUDE.md",
+ "AGENTS.md",
"README.*.md",
".claude/**",
"templates/**",
@@ -755,17 +755,17 @@ describe("parseInfraRootFilenames", () => {
],
});
assert.deepEqual(parseInfraRootFilenames(manifest), [
- "CLAUDE.md",
+ "AGENTS.md",
"README.*.md",
"Home.md",
]);
});
test("filters out non-string entries silently", () => {
const manifest = JSON.stringify({
- infrastructure: ["CLAUDE.md", 42, null, "Home.md"],
+ infrastructure: ["AGENTS.md", 42, null, "Home.md"],
});
assert.deepEqual(parseInfraRootFilenames(manifest), [
- "CLAUDE.md",
+ "AGENTS.md",
"Home.md",
]);
});
@@ -774,17 +774,17 @@ describe("parseInfraRootFilenames", () => {
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 = ["CLAUDE.md", "README.md", "README.*.md", "Home.md"];
+ const patterns = ["AGENTS.md", "README.md", "README.*.md", "Home.md"];
test("matches literal filenames exactly", () => {
- assert.equal(isInfraFilename("CLAUDE.md", patterns), true);
+ 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("CLAUDE.md.bak", patterns), false);
- assert.equal(isInfraFilename("MY-CLAUDE.md", patterns), false);
+ 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);
@@ -803,11 +803,11 @@ describe("isInfraFilename", () => {
assert.equal(isInfraFilename("foo.qux.md", ["*.bar.*"]), false);
});
test("escapes regex metacharacters in literal segments of patterns", () => {
- // `.` in `CLAUDE.md` must not match `CLAUDExmd`
- assert.equal(isInfraFilename("CLAUDExmd", patterns), false);
+ // `.` in `AGENTS.md` must not match `AGENTSxmd`
+ assert.equal(isInfraFilename("AGENTSxmd", patterns), false);
});
test("returns false on empty pattern list", () => {
- assert.equal(isInfraFilename("CLAUDE.md", []), false);
+ assert.equal(isInfraFilename("AGENTS.md", []), false);
});
test("user content files are not infra", () => {
assert.equal(isInfraFilename("2026-05-18.md", patterns), false);
diff --git a/.claude/scripts/tests/stop-report.test.ts b/.claude/scripts/tests/stop-report.test.ts
index 654a5eb..111bd8d 100644
--- a/.claude/scripts/tests/stop-report.test.ts
+++ b/.claude/scripts/tests/stop-report.test.ts
@@ -25,6 +25,8 @@ const EVERY_FINDING: ActiveHygieneReport = {
openLoops: [{ path: "work/1-1/Weekly.md", ageDays: 20, openItems: 2 }],
inboxPressure: { count: 2, oldestDays: 9 },
memoryInbox: { count: 4, oldestDays: 2, namedOnly: 1 },
+ leftoverInstructionFiles: ["CLAUDE.md", "GEMINI.md"],
+ agentsMd: { sizeKb: 23 },
};
describe("stopSummary", () => {
@@ -48,6 +50,9 @@ describe("stopSummary", () => {
describe("hygieneClaims", () => {
test("every finding reduces to its claim: counts, no file lists, no instructions", () => {
assert.deepEqual(hygieneClaims(EVERY_FINDING), [
+ "CLAUDE.md present beside AGENTS.md",
+ "GEMINI.md present beside AGENTS.md",
+ "AGENTS.md is 23KB",
"2 note(s) marked done but still in active/",
"Loose active/ notes that look like one topic",
`1 note(s) past the ${MONOLITH_BYTES / 1000}KB organization threshold`,
@@ -67,7 +72,7 @@ describe("hygieneClaims", () => {
test("a clean report has no claims", () => {
assert.deepEqual(
- hygieneClaims({ completedInActive: [], ungroupedClusters: [], oversizedNotes: [], openLoops: [], inboxPressure: null, memoryInbox: null }),
+ hygieneClaims({ completedInActive: [], ungroupedClusters: [], oversizedNotes: [], openLoops: [], inboxPressure: null, memoryInbox: null, leftoverInstructionFiles: [], agentsMd: null }),
[],
);
});
diff --git a/.claude/scripts/tests/upgrade-plan.test.ts b/.claude/scripts/tests/upgrade-plan.test.ts
index 76e0568..3a0eeab 100644
--- a/.claude/scripts/tests/upgrade-plan.test.ts
+++ b/.claude/scripts/tests/upgrade-plan.test.ts
@@ -15,6 +15,10 @@ import {
classifyAdopt,
classifyUpdate,
formatUpgradeReport,
+ retiredFileReady,
+ settleFirst,
+ untouchedRetiredFiles,
+ withRetiredInstructionFiles,
type AdoptPlan,
type UpdatePlan,
} from "../lib/upgrade-plan.ts";
@@ -105,16 +109,252 @@ describe("classifyAdopt — a vault cloned without ShardMind", () => {
});
});
+describe("a CLAUDE.md left in the vault (#321)", () => {
+ // AGENTS.md is the one instruction file from the release that retires
+ // CLAUDE.md. A CLAUDE.md the user edited survives the update, and Claude
+ // Code then reads it and skips AGENTS.md, so the plan names it as a move:
+ // never as "ahead" (keep it) or as a conflict to merge.
+ const present = (paths: readonly string[]) => (p: string) => paths.includes(p);
+
+ test("managed: a CLAUDE.md the user changed is a move, not a conflict", () => {
+ const plan: UpdatePlan = {
+ dryRun: true,
+ files: [
+ { path: "CLAUDE.md", action: "conflict" },
+ { path: "AGENTS.md", action: "overwrite" },
+ ],
+ };
+ const r = withRetiredInstructionFiles(classifyUpdate(plan, null), present(["CLAUDE.md", "AGENTS.md"]));
+ assert.deepEqual(r.move, ["CLAUDE.md"]);
+ assert.deepEqual(r.conflicts, []);
+ assert.deepEqual(r.behind, ["AGENTS.md"]);
+ });
+
+ test("managed: a modified CLAUDE.md the template no longer touches is a move, not 'ahead'", () => {
+ const plan: UpdatePlan = { dryRun: true, files: [{ path: "CLAUDE.md", action: "noop" }] };
+ const status = { installed: true, files: { modified: ["CLAUDE.md"] } };
+ const r = withRetiredInstructionFiles(classifyUpdate(plan, status), present(["CLAUDE.md"]));
+ assert.deepEqual(r.move, ["CLAUDE.md"]);
+ assert.deepEqual(r.ahead, []);
+ assert.equal(r.unchanged, 0);
+ });
+
+ test("managed: an untouched CLAUDE.md the update deletes is behind, not a move", () => {
+ const plan: UpdatePlan = { dryRun: true, files: [{ path: "CLAUDE.md", action: "delete" }] };
+ const r = withRetiredInstructionFiles(classifyUpdate(plan, null), present(["CLAUDE.md"]));
+ assert.deepEqual(r.behind, ["CLAUDE.md"]);
+ assert.deepEqual(r.move, []);
+ });
+
+ test("unmanaged: adopt never lists CLAUDE.md (the release has none), so its presence alone makes it a move", () => {
+ const plan: AdoptPlan = {
+ dryRun: true,
+ files: [{ path: "Home.md", classification: "matches", shardHash: "h", volatile: false }],
+ };
+ const r = withRetiredInstructionFiles(classifyAdopt(plan, () => null), present(["CLAUDE.md"]));
+ assert.deepEqual(r.move, ["CLAUDE.md"]);
+ });
+
+ test("unmanaged: a CLAUDE.md byte-identical to the release the vault was cloned from is behind (delete it), not a move", () => {
+ const hashes: Record<string, string> = { "CLAUDE.md": "h-template" };
+ const untouched = untouchedRetiredFiles(
+ (p) => hashes[p] ?? null,
+ (p) => (p === "CLAUDE.md" ? "h-template" : null),
+ () => true,
+ );
+ assert.deepEqual(untouched, ["CLAUDE.md"]);
+ const plan: AdoptPlan = { dryRun: true, files: [] };
+ const r = withRetiredInstructionFiles(
+ { ...classifyAdopt(plan, () => null), behind: untouched },
+ present(["CLAUDE.md"]),
+ );
+ assert.deepEqual(r.behind, ["CLAUDE.md"]);
+ assert.deepEqual(r.move, []);
+ });
+
+ test("unmanaged: an edited CLAUDE.md, or one the base release never had, is not untouched", () => {
+ assert.deepEqual(untouchedRetiredFiles(() => "h-mine", () => "h-template", () => true), []);
+ assert.deepEqual(untouchedRetiredFiles(() => "h-mine", () => null, () => true), []);
+ assert.deepEqual(untouchedRetiredFiles(() => null, () => "h-template", () => true), []);
+ });
+
+ test("unmanaged: an untouched CLAUDE.md stays a move while the new AGENTS.md is not certain to be in place", () => {
+ // The v9.1 AGENTS.md only says "read CLAUDE.md". If the user's AGENTS.md
+ // is ahead or a conflict, it is not rewritten, and deleting CLAUDE.md
+ // would leave every agent pointed at a missing file.
+ assert.deepEqual(untouchedRetiredFiles(() => "h-template", () => "h-template", () => false), []);
+ });
+
+ test("the new AGENTS.md is in place when it matches the release or is behind, not when it is ahead or a conflict", () => {
+ const agents = (classification: AdoptPlan["files"][number]["classification"]): AdoptPlan => ({
+ dryRun: true,
+ files: [{ path: "AGENTS.md", classification, shardHash: "h", volatile: false }],
+ });
+ const report = (behind: string[]) => ({ behind, ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 });
+ assert.equal(retiredFileReady(agents("matches"), report([]))("CLAUDE.md"), true);
+ assert.equal(retiredFileReady(agents("differs"), report(["AGENTS.md"]))("CLAUDE.md"), true);
+ assert.equal(retiredFileReady(agents("differs"), report([]))("CLAUDE.md"), false);
+ });
+
+ test("a retired file is not deleted while .gemini/settings.json is still the user's old one", () => {
+ // The old settings name no context file, so Gemini reads GEMINI.md, and
+ // the old GEMINI.md only says "read CLAUDE.md".
+ const plan = (settings: AdoptPlan["files"][number]["classification"]): AdoptPlan => ({
+ dryRun: true,
+ files: [
+ { path: "AGENTS.md", classification: "matches", shardHash: "h", volatile: false },
+ { path: ".gemini/settings.json", classification: settings, shardHash: "s", volatile: false },
+ ],
+ });
+ const report = (behind: string[]) => ({ behind, ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 });
+ for (const file of ["CLAUDE.md", "GEMINI.md"]) {
+ assert.equal(retiredFileReady(plan("matches"), report([]))(file), true, file);
+ assert.equal(retiredFileReady(plan("differs"), report([".gemini/settings.json"]))(file), true, file);
+ assert.equal(retiredFileReady(plan("differs"), report([]))(file), false, file);
+ }
+ // A vault without the Gemini module has no settings file to wait for.
+ assert.equal(retiredFileReady({ dryRun: true, files: [plan("matches").files[0]!] }, report([]))("CLAUDE.md"), true);
+ });
+
+ test("a vault with no Gemini settings (shard-only) frees CLAUDE.md but keeps GEMINI.md, which Gemini still falls back to", () => {
+ // --apply-behind writes behind files only; a shard-only settings file
+ // arrives with the later adopt. Until then Gemini has no settings and
+ // reads GEMINI.md by default, so deleting it would cut Gemini off.
+ const plan: AdoptPlan = {
+ dryRun: true,
+ files: [
+ { path: "AGENTS.md", classification: "matches", shardHash: "h", volatile: false },
+ { path: ".gemini/settings.json", classification: "shard-only", shardHash: "s", volatile: false },
+ ],
+ };
+ const report = { behind: [], ahead: [], merged: [], conflicts: [], added: [".gemini/settings.json"], move: [], unchanged: 0 };
+ const ready = retiredFileReady(plan, report);
+ assert.equal(ready("CLAUDE.md"), true);
+ assert.equal(ready("GEMINI.md"), false);
+ assert.deepEqual(untouchedRetiredFiles(() => "h", () => "h", ready), ["CLAUDE.md"]);
+ });
+
+ test("managed: a GEMINI.md the user edited, which ShardMind keeps as theirs, is a move, not 'unchanged'", () => {
+ // Gemini now reads AGENTS.md through .gemini/settings.json, so an edited
+ // GEMINI.md is no longer loaded: its additions would vanish silently.
+ const plan: UpdatePlan = { dryRun: true, files: [{ path: "GEMINI.md", action: "keep_as_user" }] };
+ const r = withRetiredInstructionFiles(classifyUpdate(plan, null), present(["GEMINI.md"]));
+ assert.deepEqual(r.move, ["GEMINI.md"]);
+ assert.equal(r.unchanged, 0);
+ });
+
+ test("unmanaged: a GEMINI.md still byte-identical to the base release is behind, like CLAUDE.md", () => {
+ const untouched = untouchedRetiredFiles(() => "h-template", (p) => (p === "GEMINI.md" ? "h-template" : null), () => true);
+ assert.deepEqual(untouched, ["GEMINI.md"]);
+ });
+
+ test("a CLAUDE.md the update deletes stays behind, whatever AGENTS.md is: the report says what the update does", () => {
+ // ShardMind deletes an untouched CLAUDE.md on update regardless of this
+ // report, so listing it anywhere but Behind would hide a deletion.
+ for (const where of ["ahead", "conflicts"] as const) {
+ const base = { behind: ["CLAUDE.md"], ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 };
+ const r = withRetiredInstructionFiles({ ...base, [where]: ["AGENTS.md"] }, present(["CLAUDE.md", "AGENTS.md"]));
+ assert.deepEqual(r.behind, ["CLAUDE.md"], where);
+ assert.deepEqual(r.move, [], where);
+ }
+ });
+
+ test("while AGENTS.md is a conflict and CLAUDE.md is retiring, the report says to settle AGENTS.md first", () => {
+ // The vault's AGENTS.md may be the old one that only says "read
+ // CLAUDE.md": once CLAUDE.md is gone, every agent is left with nothing.
+ const empty = { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 };
+ for (const report of [
+ { ...empty, behind: ["CLAUDE.md"], conflicts: ["AGENTS.md"] },
+ { ...empty, move: ["CLAUDE.md"], conflicts: ["AGENTS.md"] },
+ ]) {
+ assert.deepEqual(settleFirst(report), ["AGENTS.md"]);
+ const out = formatUpgradeReport(report, "v9.1.0", "v10.0.0");
+ assert.match(out, /### Settle these first/);
+ assert.match(out, /`AGENTS\.md`[^\n]*only points at CLAUDE\.md/);
+ // First, before any section that acts on CLAUDE.md.
+ assert.ok(out.indexOf("Settle these first") < out.indexOf("- `CLAUDE.md`"));
+ }
+ assert.doesNotMatch(formatUpgradeReport({ ...empty, behind: ["CLAUDE.md"] }, "v9.1.0", "v10.0.0"), /Settle these first/);
+ assert.doesNotMatch(formatUpgradeReport({ ...empty, conflicts: ["AGENTS.md"] }, "v9.1.0", "v10.0.0"), /Settle these first/);
+ });
+
+ test("while .gemini/settings.json is a conflict and a retired file is leaving, the report says to settle it first", () => {
+ // The user's old settings name no context file, so Gemini keeps reading
+ // GEMINI.md, which only points at CLAUDE.md.
+ const empty = { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 };
+ for (const leaving of [{ behind: ["CLAUDE.md"] }, { move: ["GEMINI.md"] }]) {
+ const report = { ...empty, ...leaving, conflicts: [".gemini/settings.json"] };
+ assert.deepEqual(settleFirst(report), [".gemini/settings.json"]);
+ assert.match(formatUpgradeReport(report, "v9.1.0", "v10.0.0"), /`\.gemini\/settings\.json`[^\n]*context\.fileName/);
+ }
+ const both = { ...empty, behind: ["CLAUDE.md"], conflicts: ["AGENTS.md", ".gemini/settings.json"] };
+ assert.deepEqual(settleFirst(both), ["AGENTS.md", ".gemini/settings.json"]);
+ });
+
+ test("an AGENTS.md conflict is settled first even when GEMINI.md is the only file leaving", () => {
+ // The new settings send Gemini to AGENTS.md: if that is still the old
+ // pointer to a CLAUDE.md that is gone, Gemini reads nothing.
+ const empty = { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 };
+ const report = { ...empty, move: ["GEMINI.md"], conflicts: ["AGENTS.md", ".gemini/settings.json"] };
+ assert.deepEqual(settleFirst(report), ["AGENTS.md", ".gemini/settings.json"]);
+ });
+
+ test("an ahead AGENTS.md is the user's edit of the current release, never the old pointer: no settle warning", () => {
+ // Ahead means the template did not change AGENTS.md between the two
+ // releases, and the release that retires CLAUDE.md does change it.
+ const empty = { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: [], unchanged: 0 };
+ const report = { ...empty, move: ["CLAUDE.md"], ahead: ["AGENTS.md"] };
+ assert.deepEqual(settleFirst(report), []);
+ assert.doesNotMatch(formatUpgradeReport(report, "v10.0.0", "v10.1.0"), /Settle these first/);
+ });
+
+ test("the Move out text names what each retired file does wrong", () => {
+ const out = formatUpgradeReport(
+ { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: ["CLAUDE.md", "GEMINI.md"], unchanged: 0 },
+ "v9.1.0",
+ "v10.0.0",
+ );
+ assert.match(out, /Gemini no longer reads GEMINI\.md/);
+ });
+
+ test("the Move out text covers an untouched CLAUDE.md and an AGENTS.md that is not the new one yet", () => {
+ const out = formatUpgradeReport(
+ { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: ["CLAUDE.md"], unchanged: 0 },
+ "v9.1.0",
+ "v10.0.0",
+ );
+ assert.match(out, /If you never edited it, just delete it/);
+ assert.match(out, /Settle the files this report lists first, if any/);
+ });
+
+ test("no CLAUDE.md in the vault: nothing to move", () => {
+ const r = withRetiredInstructionFiles(classifyUpdate({ dryRun: true, files: [] }, null), present([]));
+ assert.deepEqual(r.move, []);
+ });
+
+ test("the report says what to do, and that nothing is merged automatically", () => {
+ const out = formatUpgradeReport(
+ { behind: [], ahead: [], merged: [], conflicts: [], added: [], move: ["CLAUDE.md"], unchanged: 0 },
+ "v9.1.0",
+ "v10.0.0",
+ );
+ assert.match(out, /### Move out — retired instruction file \(1\)[\s\S]*- `CLAUDE\.md`/);
+ assert.match(out, /Claude Code reads CLAUDE\.md and skips AGENTS\.md/);
+ assert.match(out, /\.claude\/rules\/local\.md/);
+ assert.match(out, /Nothing is merged automatically/);
+ });
+});
+
describe("formatUpgradeReport", () => {
test("names every file in full, by section, and skips empty sections", () => {
const out = formatUpgradeReport(
- { behind: ["a.md"], ahead: ["b.ts"], merged: [], conflicts: [], added: [], unchanged: 7 },
+ { behind: ["a.md"], ahead: ["b.ts"], merged: [], conflicts: [], added: [], move: [], unchanged: 7 },
"v9.0.0",
"v9.0.1",
);
assert.match(out, /^## Upgrade plan: v9\.0\.0 → v9\.0\.1\n7 file\(s\) need no judgment\./);
assert.match(out, /### Behind \(1\)[\s\S]*- `a\.md`/);
assert.match(out, /### Ahead — keep, and consider upstreaming \(1\)[\s\S]*- `b\.ts`/);
- assert.doesNotMatch(out, /Merged|Conflicts|New in the template/);
+ assert.doesNotMatch(out, /Merged|Conflicts|New in the template|Move out/);
});
});
diff --git a/.claude/scripts/upgrade-plan.ts b/.claude/scripts/upgrade-plan.ts
index 02b084b..640c81d 100644
--- a/.claude/scripts/upgrade-plan.ts
+++ b/.claude/scripts/upgrade-plan.ts
@@ -12,7 +12,13 @@
* `shardmind adopt <source> --from-version <v> --dry-run --yes --json`,
* fetches that release to hash each file's base, and classifies with
* `classifyAdopt`.
- * Prints the report (or, with --json, `{ mode, from, to, report }`).
+ * In both modes, a CLAUDE.md or GEMINI.md still in the vault is reported as a
+ * move (#321): Claude Code reads a CLAUDE.md in place of AGENTS.md, and
+ * Gemini no longer reads GEMINI.md. In an unmanaged clone, one whose
+ * bytes are the release it was cloned from is behind instead, and
+ * --apply-behind deletes it.
+ * Prints the report (or, with --json, `{ mode, from, to, report,
+ * settleFirst }`).
*
* --apply-behind (unmanaged clone only): writes the latest release's bytes
* for every BEHIND file — one the user never changed — after checking each
@@ -37,6 +43,10 @@ import {
classifyAdopt,
classifyUpdate,
formatUpgradeReport,
+ retiredFileReady,
+ settleFirst,
+ untouchedRetiredFiles,
+ withRetiredInstructionFiles,
type AdoptPlan,
type ShardmindEnvelope,
type StatusResult,
@@ -158,33 +168,50 @@ function main(): void {
const plan = shardmind<AdoptPlan>(vault, ["adopt", source, "--from-version", from, "--dry-run", "--yes", "--json"]);
if (!plan.ok) fail(`adopt plan: ${plan.error.message}${plan.error.hint ? ` — ${plan.error.hint}` : ""}`);
const base = cloneRelease(source, from);
+ // Retired instruction files the user never edited: the latest release
+ // has none, so applying "behind" for them means deleting them.
+ let untouched: string[] = [];
try {
- report = classifyAdopt(plan.result, (p) => {
- const f = join(base, p);
+ const hashIn = (dir: string) => (p: string) => {
+ const f = join(dir, p);
return existsSync(f) ? sha256(readFileSync(f)) : null;
- });
+ };
+ report = classifyAdopt(plan.result, hashIn(base));
+ untouched = untouchedRetiredFiles(hashIn(vault), hashIn(base), retiredFileReady(plan.result, report));
} finally {
rmSync(base, { recursive: true, force: true });
}
+ const toWrite = report.behind;
+ report = { ...report, behind: [...toWrite, ...untouched] };
if (applyBehind && report.behind.length > 0) {
- const latest = cloneRelease(source, to);
- try {
- const want = new Map(plan.result.files.map((f) => [f.path, f.shardHash]));
- for (const p of report.behind) {
- const bytes = readFileSync(join(latest, p));
- if (sha256(bytes) !== want.get(p)) fail(`${p} at v${to} does not match adopt's plan; nothing more was written`);
- writeFileSync(join(vault, p), bytes);
+ if (toWrite.length > 0) {
+ const latest = cloneRelease(source, to);
+ try {
+ const want = new Map(plan.result.files.map((f) => [f.path, f.shardHash]));
+ for (const p of toWrite) {
+ const bytes = readFileSync(join(latest, p));
+ if (sha256(bytes) !== want.get(p)) fail(`${p} at v${to} does not match adopt's plan; nothing more was written`);
+ writeFileSync(join(vault, p), bytes);
+ }
+ } finally {
+ rmSync(latest, { recursive: true, force: true });
}
- } finally {
- rmSync(latest, { recursive: true, force: true });
}
- process.stderr.write(`upgrade-plan: wrote v${to} of ${report.behind.length} behind file(s)\n`);
+ // Only after every write succeeded: the new AGENTS.md is in place.
+ for (const p of untouched) rmSync(join(vault, p));
+ process.stderr.write(
+ `upgrade-plan: wrote v${to} of ${toWrite.length} behind file(s), removed ${untouched.length} retired instruction file(s) you never edited\n`,
+ );
}
}
+ report = withRetiredInstructionFiles(report, (p) => existsSync(join(vault, p)));
+
process.stdout.write(
- asJson ? `${JSON.stringify({ mode, from, to, report }, null, 2)}\n` : `${formatUpgradeReport(report, `v${from}`, `v${to}`)}\n`,
+ asJson
+ ? `${JSON.stringify({ mode, from, to, report, settleFirst: settleFirst(report) }, null, 2)}\n`
+ : `${formatUpgradeReport(report, `v${from}`, `v${to}`)}\n`,
);
}
diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.ts
index 87d1167..e1fc0df 100644
--- a/.claude/scripts/validate-write.ts
+++ b/.claude/scripts/validate-write.ts
@@ -82,7 +82,7 @@ if (shouldRefreshForPath(filePath)) {
// Memory-location guard (#81) runs BEFORE the vault-root skip: the
// auto-memory directory lives in ~/.claude/, outside the vault, and would
// otherwise be skipped. Only MEMORY.md (the auto-loaded index) belongs
-// there — durable knowledge goes to brain/ topic notes per CLAUDE.md.
+// there — durable knowledge goes to brain/ topic notes per .claude/rules/memory.md.
// PostToolUse can't block the write, but a loud warning makes the
// violation immediately visible so the file gets migrated before the
// index drifts. The predicate checks the lexically-normalized path AND
@@ -100,7 +100,7 @@ if (isBlockedMemoryPath(filePath) || isBlockedMemoryPath(resolvedPath)) {
const memoryContext = [
`⚠️ Memory location violation: \`${file}\` was written to \`~/.claude/.../memory/\`.`,
"",
- "Per CLAUDE.md, this directory should contain only MEMORY.md (the auto-loaded index).",
+ "Per .claude/rules/memory.md, this directory should contain only MEMORY.md (the auto-loaded index).",
"All durable knowledge belongs in the vault under `brain/` topic notes:",
"",
"- Patterns/conventions → `brain/Patterns.md`",
diff --git a/.claude/skills/obsidian-mind/hooks/context.ts b/.claude/skills/obsidian-mind/hooks/context.ts
index 02843ca..faa1448 100644
--- a/.claude/skills/obsidian-mind/hooks/context.ts
+++ b/.claude/skills/obsidian-mind/hooks/context.ts
@@ -5,7 +5,7 @@ export const CONTEXT_BLOCK = "obsidian-mind";
/**
* The first message's context with the session context added: as a project
- * instruction file, which Claude Code frames like CLAUDE.md, re-reads after
+ * instruction file, which Claude Code frames like AGENTS.md, re-reads after
* compaction and `/clear`, and gives general-purpose subagents.
*
* When a hook above rewrote the `claudeMd` text, the files behind it are
diff --git a/.claude/skills/obsidian-mind/hooks/register.test.ts b/.claude/skills/obsidian-mind/hooks/register.test.ts
index c4f5fea..7582048 100644
--- a/.claude/skills/obsidian-mind/hooks/register.test.ts
+++ b/.claude/skills/obsidian-mind/hooks/register.test.ts
@@ -116,16 +116,16 @@ describe("session context (#265)", () => {
describe("withSessionContext", () => {
const PATH = `${ROOT}/.claude/session-context.md`;
- const claudeMd = { path: `${ROOT}/CLAUDE.md`, kind: "project" as const, content: "# Vault" };
+ const agentsMd = { path: `${ROOT}/AGENTS.md`, kind: "project" as const, content: "# Vault" };
test("adds the context as a project instruction file, after the files already there", () => {
- const out = withSessionContext({ blocks: [{ name: "claudeMd", text: "" }], instructionFiles: [claudeMd] }, PATH, CONTEXT);
- expect(out.instructionFiles).toEqual([claudeMd, { path: PATH, kind: "project", content: CONTEXT }]);
+ const out = withSessionContext({ blocks: [{ name: "claudeMd", text: "" }], instructionFiles: [agentsMd] }, PATH, CONTEXT);
+ expect(out.instructionFiles).toEqual([agentsMd, { path: PATH, kind: "project", content: CONTEXT }]);
expect(out.blocks).toEqual([{ name: "claudeMd", text: "" }]);
});
test("replaces an earlier copy instead of adding a second", () => {
- const once = withSessionContext({ blocks: [], instructionFiles: [claudeMd] }, PATH, "old");
+ const once = withSessionContext({ blocks: [], instructionFiles: [agentsMd] }, PATH, "old");
const twice = withSessionContext(once, PATH, CONTEXT);
expect(twice.instructionFiles?.filter((file) => file.path === PATH)).toEqual([{ path: PATH, kind: "project", content: CONTEXT }]);
});
diff --git a/.gemini/settings.json b/.gemini/settings.json
index 7c9a782..9b22ee4 100644
--- a/.gemini/settings.json
+++ b/.gemini/settings.json
@@ -1,4 +1,9 @@
{
+ "context": {
+ "fileName": [
+ "AGENTS.md"
+ ]
+ },
"hooks": {
"SessionStart": [
{
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 2faef48..030f23f 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -22,5 +22,5 @@
- [ ] PR title follows `type: description` format
- [ ] Tests pass (`cd .claude/scripts && npm test`)
- [ ] Any NEW guard, check, or config constraint has demonstrated a red — broken deliberately, seen to fire, reverted. Say which, in one line
-- [ ] Doc tables updated if adding commands/agents (CLAUDE.md, README, Skills.md, translations)
+- [ ] Doc tables updated if adding commands/agents (AGENTS.md, README, Skills.md, translations)
- [ ] No changes to CHANGELOG.md or vault-manifest.json version (automated by release pipeline)
diff --git a/.github/scripts/generate-changelog.ts b/.github/scripts/generate-changelog.ts
index 7367ee1..bdbca3e 100644
--- a/.github/scripts/generate-changelog.ts
+++ b/.github/scripts/generate-changelog.ts
@@ -317,27 +317,33 @@ type Fingerprint = {
missing?: string[];
};
+/**
+ * Order fingerprint keys by numeric version components (v3.7 < v3.10, unlike
+ * string sort), a missing component counting as 0. Negative when `a` is older.
+ */
+export function compareFingerprintKeys(a: string, b: string): number {
+ const pa = a.replace(/^v/, "").split(".").map(Number);
+ const pb = b.replace(/^v/, "").split(".").map(Number);
+ const len = Math.max(pa.length, pb.length);
+ for (let i = 0; i < len; i++) {
+ const da = pa[i] ?? 0;
+ const db = pb[i] ?? 0;
+ if (da !== db) return da - db;
+ }
+ return 0;
+}
+
/**
* Find the latest fingerprint key that has no `missing` field — conceptually
* "the currently-open-ended release." Returns null if the map is empty or
- * every entry already has a `missing`. Keys are sorted by numeric version
- * components (v3.7 < v3.10, unlike string sort) so the "latest" is the one
- * with the highest major/minor/patch.
+ * every entry already has a `missing`. Keys are sorted with
+ * `compareFingerprintKeys`, so the "latest" is the one with the highest
+ * major/minor/patch.
*/
export function findLatestOpenFingerprint(
fingerprints: Readonly<Record<string, Fingerprint>>,
): string | null {
- const sorted = Object.keys(fingerprints).sort((a, b) => {
- const pa = a.replace(/^v/, "").split(".").map(Number);
- const pb = b.replace(/^v/, "").split(".").map(Number);
- const len = Math.max(pa.length, pb.length);
- for (let i = 0; i < len; i++) {
- const da = pa[i] ?? 0;
- const db = pb[i] ?? 0;
- if (da !== db) return da - db;
- }
- return 0;
- });
+ const sorted = Object.keys(fingerprints).sort(compareFingerprintKeys);
for (let i = sorted.length - 1; i >= 0; i--) {
const key = sorted[i]!;
if (!fingerprints[key]!.missing) return key;
diff --git a/.github/scripts/manifest-check.ts b/.github/scripts/manifest-check.ts
index 56d3654..4db59eb 100644
--- a/.github/scripts/manifest-check.ts
+++ b/.github/scripts/manifest-check.ts
@@ -88,6 +88,7 @@ const WATCHED: ReadonlyArray<{
}> = [
{ dir: ".claude/commands", exts: [".md"] },
{ dir: ".claude/agents", exts: [".md"] },
+ { dir: ".claude/rules", exts: [".md"] },
{ dir: ".claude/scripts", exts: [".ts", ".json"] },
{ dir: ".claude-plugin", exts: [".json"] },
{ dir: ".codex", exts: [".json", ".md"] },
@@ -104,10 +105,8 @@ const WATCHED: ReadonlyArray<{
const WATCHED_ROOT_FILES: readonly string[] = [
"AGENTS.md",
"ARCHITECTURE.md",
- "CLAUDE.md",
"CHANGELOG.md",
"CONTRIBUTING.md",
- "GEMINI.md",
"Home.md",
"LICENSE",
"README.md",
diff --git a/.shardmind/shard-schema.yaml b/.shardmind/shard-schema.yaml
index 21c7bb7..6a9f61c 100644
--- a/.shardmind/shard-schema.yaml
+++ b/.shardmind/shard-schema.yaml
@@ -72,10 +72,11 @@ groups:
# * 4 removable content modules: org, perf, incidents, one_on_ones.
# Deselected modules drop their paths AND their per-name commands /
# agents under `.claude/{commands,agents}/`.
-# * 2 removable agent modules: codex, gemini. Deselect to omit
-# AGENTS.md / GEMINI.md and the matching dotfolder contents.
-# `.claude/scripts/` (shared hook implementations) stays always-on
-# by virtue of being claimed by no module.
+# * 2 removable agent modules: codex, gemini. Deselect to omit the
+# matching dotfolder contents.
+# `.claude/scripts/` (shared hook implementations) and `AGENTS.md`
+# (the one instruction file every agent reads, #321) stay always-on by
+# virtue of being claimed by no module.
#
# Bases (`bases/*.base`) are listed by exact path under their owning
# module's `paths` — the engine's `mod.bases` field only matches
@@ -146,9 +147,14 @@ modules:
removable: true
claude:
- label: "Claude (Anthropic) agent — CLAUDE.md, .claude/agents, .claude/skills, .claude/commands, .claude-plugin"
+ label: "Claude (Anthropic) agent — .claude/rules, .claude/agents, .claude/skills, .claude/commands, .claude-plugin"
paths:
- - "CLAUDE.md"
+ # Claude-only rules. The shared ones AGENTS.md points to stay core
+ # (claimed by no module), so every agent selection installs them.
+ - ".claude/rules/skills.md"
+ - ".claude/rules/subagents.md"
+ - ".claude/rules/memory.md"
+ - ".claude/rules/hooks-and-mod.md"
- ".claude/agents/"
- ".claude/skills/"
- ".claude/commands/"
@@ -166,17 +172,15 @@ modules:
removable: false
codex:
- label: "Codex (OpenAI) agent — AGENTS.md, .codex/"
+ label: "Codex (OpenAI) agent — .codex/"
paths:
- - "AGENTS.md"
- ".codex/"
agents: ["codex"]
removable: true
gemini:
- label: "Gemini (Google) agent — GEMINI.md, .gemini/"
+ label: "Gemini (Google) agent — .gemini/"
paths:
- - "GEMINI.md"
- ".gemini/"
agents: ["gemini"]
removable: true
diff --git a/AGENTS.md b/AGENTS.md
index 646b549..618c2d9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,25 +1,38 @@
# Obsidian Mind
-This vault is built for [Claude Code](https://claude.ai/code) with a full operating manual in `CLAUDE.md`.
+Personal Obsidian vault -- an external brain for work notes, decisions, performance tracking, and agent context.
-**Read `CLAUDE.md` for all vault conventions** — structure, note types, linking rules, frontmatter schemas, indexes, and workflows. Most of the content is agent-agnostic.
+## Vault Structure
-## Hooks
-
-The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell, executed natively by Node via `--experimental-strip-types` — no build step, no runtime dependencies, no Claude SDK. Hook configs are provided for three agents:
+| Folder | Purpose | Key Files |
+|--------|---------|-----------|
+| `Home.md` | **Vault entry point** -- embedded Base views, quick links | Open this first |
+| `vault-manifest.json` | **Template metadata** -- version, infrastructure vs user content boundaries, frontmatter schemas, version fingerprints | Used by `/om-vault-upgrade` for migration |
+| `CHANGELOG.md` | **Version history** -- tracks template releases (v1--v3.3) with what changed | Reference for upgrade paths |
+| `bases/` | **All Bases centralized** -- dynamic views for navigation | `Work Dashboard` (incl. 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/active/` | **Current projects only** (1-3 files) | Move here when starting, move to archive when done |
+| `work/archive/YYYY/` | Completed work organized by year | Grows over time |
+| `work/incidents/` | Incident docs (main note + RCA + deep dive + drafts) | Per-incident grouping |
+| `work/1-1/` | 1:1 meeting notes (accumulate weekly) | Named `<Person> YYYY-MM-DD.md` |
+| `work/meetings/` | **Meeting notes inbox** -- staging area for raw exports, processed by `/om-intake` | Drop files, run `/om-intake` |
+| `perf/` | Performance framework, brag doc | `Brag Doc.md` (index) |
+| `perf/brag/` | Quarterly brag notes | One per quarter, e.g. `Q1 2025.md` |
+| `perf/competencies/` | Atomic competency notes (link targets) | One note per competency |
+| `perf/evidence/` | PR deep scans, data extracts for reviews | Named `<Person> PRs - <Period>.md` |
+| `perf/<cycle>/` | Review cycle briefs + artifacts | Review briefs (private, manager, peer) |
+| `brain/` | The agent's operational knowledge | `Memories.md`, `Key Decisions.md`, `Patterns.md`, `Gotchas.md`, `Skills.md`, `North Star.md` |
+| `memories/YYYY/MM/` | **Cross-repo agent memory** -- durable lessons recorded over MCP by sessions working in *other* repositories. Time is the only thing in the path; reach is declared in frontmatter | Browse via `bases/Memories.base`; never edit by hand |
+| `org/` | Organizational knowledge index | `People & Context.md` (MOC) |
+| `org/people/` | Atomic person notes | One note per person |
+| `org/teams/` | Team notes as graph nodes | One note per team |
+| `reference/` | Codebase knowledge, architecture maps | Flow docs, architecture docs |
+| `thinking/` | Scratchpad for drafts and reasoning | Named `YYYY-MM-DD-topic.md` |
+| `templates/` | Obsidian templates | `Work Note.md`, `Decision Record.md`, etc. |
-| Agent | Config | Status |
-|-------|--------|--------|
-| Claude Code | `.claude/settings.json` | Full support |
-| Codex CLI | `.codex/hooks.json` | Shared hook scripts |
-| Gemini CLI | `.gemini/settings.json` | Shared hook scripts |
+## Obsidian CLI
-| Script | Purpose | Claude event | Codex event | Gemini event |
-|--------|---------|--------------|-------------|--------------|
-| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
-| `classify-message.ts` | Classify messages, inject routing hints, hand over the last Stop report (Claude Code and Codex: Gemini's checklist runs on SessionEnd and saves none) | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
-| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
-| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
+Need a CLI command? See `.claude/rules/obsidian-cli.md`, or run `obsidian help`.
## Commands
@@ -28,43 +41,245 @@ Commands live in `.claude/commands/` — agent-agnostic markdown with YAML front
- **Claude Code / Gemini CLI**: invoke as `/om-standup`, `/om-dump`, etc.
- **Codex CLI**: type the command name as a regular prompt without the `/` prefix (e.g. `om-standup`). Codex will find and execute the command file.
-## Memory
+## Search
+
+- **qmd**: Semantic search across the vault via [QMD](https://github.com/tobi/qmd). Use PROACTIVELY before reading files. **Preference order — pick the highest surface available and stop:**
+ 1. **`mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, `mcp__qmd__status`** — registered MCP tools. If you see them in your tool menu, they are live and pre-scoped to this vault's index. Use them first; no `--index` argument needed.
+ 2. **`qmd --index <name> query|search|vsearch|get|multi-get`** — CLI fallback for one-off shell checks or when the MCP server is unavailable. Always pass `--index <name>`, where `<name>` is the `qmd_index` field from `vault-manifest.json` when set and otherwise the vault folder name slugified, so the SQLite store stays isolated from other vaults on the machine.
+ 3. **Grep / Glob / Read** — last resort, only when QMD is not installed at all.
+
+ The MCP server (`.mcp.json` → `.claude/scripts/qmd-mcp.mjs`), the CLI, and the SessionStart hook all read the same manifest field, so every surface scopes to the same store. On a fresh clone, run `node --experimental-strip-types .scripts/qmd-bootstrap.ts` once to build the index. Note: the MCP connect-time banner can read "0 documents" when the server registers before the SessionStart reindex finishes — a stale snapshot, not the dead-search state the self-heal guards; don't diagnose it.
+
+## Session Workflow
+
+### Starting a Substantial Session
+
+Run `/om-standup`. The manual steps are in `.claude/rules/session-workflow.md`.
+
+### Ending a Substantial Session
+
+**When the user says "wrap up", "let's wrap", "wrapping up", or similar -- invoke `/om-wrap-up` automatically.** This runs a full review of the session.
+
+Without it, the minimum checklist is in `.claude/rules/session-workflow.md`.
+
+### Thinking Workflow
+
+Drafting before a final note? Read `.claude/rules/thinking.md`.
+
+### Creating Notes
+
+1. **Always use YAML frontmatter** with at minimum `date`, `description` (~150 chars), `tags`, and type-specific fields. Work notes and incidents also need `quarter` (e.g., `Q1-2026`). Incidents need `ticket`, `severity`, `role`.
+2. **Use templates** from `templates/`. Fill `{{placeholders}}` with real values.
+2b. **Write fully, organize structurally — the vault tidies itself.** Size is a STRUCTURE signal, never a brevity signal: when a note crosses the ~25KB organization threshold (bytes, not lines — giant single-line entries hide in low line counts), the PostToolUse hook flags it at write time and the hygiene scan flags it at session boundaries. The response is always a SPLIT (domain notes, event-log satellites, or a cluster folder — content moved verbatim, one-liner index left behind, inbound links retargeted), never trimming content. The same hook flags write-time topic clusters — token overlap is blind, so judge genuine shared context before grouping. `/om-tidy` is the acting half. Exempt: `*Archive*` notes (bulk is their job).
+3. **Place files correctly**:
+ - **Active** work notes, decisions, peer review prep -- `work/active/`
+ - **Completed** work notes -- `work/archive/YYYY/` (by year)
+ - Incident docs -- `work/incidents/`
+ - 1:1 meeting notes -- `work/1-1/`
+ - Performance content -- `perf/` (cycle subfolder for review briefs)
+ - PR evidence -- `perf/evidence/`
+ - Competency definitions -- `perf/competencies/`
+ - People -- `org/people/`
+ - Teams -- `org/teams/`
+ - Agent operational context -- `brain/`
+ - Codebase knowledge -- `reference/`
+ - Drafts -- `thinking/`
+ - Vault root: `Home.md`, `AGENTS.md`, `vault-manifest.json`, `CHANGELOG.md`, `CONTRIBUTING.md`, `README.md`, `LICENSE`, `.gitignore`. No user notes at root.
+4. **Name files descriptively.** Use the note title as filename. **Date convention:** prefix **point-in-time** notes with a date — 1:1s (`<Person> YYYY-MM-DD.md`), dated captures, meeting exports. **Living and entity notes use a bare title** — work notes, person/team notes, competencies, `brain/`, `reference/`. *Why the split:* a creation-date prefix on a continuously-edited note **inverts the recency signal** (a living doc looks stale while being updated daily). For "what's most recent," use `bases/Recently Touched.base` (real modified time), never filename dates.
+5. **Group multi-note workstreams in a subfolder.** Once a workstream has more than one note, it gets a folder (`work/active/<Topic>/`; the archive mirrors the grouping). Folders are the lifecycle/context axis only — links remain the primary organization (wikilinks resolve by name across folders, so grouping never breaks links, QMD, or the graph). The hygiene scan and write-time cluster sensor flag candidates; `/om-project-archive` moves whole clusters.
+
+### Note Types
+
+| Type | Location | Naming | Key Sections |
+|------|----------|--------|--------------|
+| Work note | `work/active/` (then `archive/YYYY/` when done) | Descriptive title | Context, What/Why, Links, Related |
+| Incident | `work/incidents/` | Ticket number or descriptive title | Context, Root Cause, Timeline, Impact, Analysis, Related |
+| 1:1 note | `work/1-1/` | `<Person> YYYY-MM-DD.md` | Key Takeaways, Action Items, Quotes, What to Watch, Related |
+| PR analysis | `perf/evidence/` | `<Person> PRs - <Period>.md` | PR Count, Projects, Quality, Growth, Full Table |
+| Review brief | `perf/<cycle>/` | `<Cycle> Review Brief.md` | Arc, Impact, Competencies, Documentation Trail |
+| Person note | `org/people/` | Full name | Role & Team, Relationship, Key Moments, Notes |
+| Team note | `org/teams/` | Team name | Members, Scope, Interactions |
+| Competency | `perf/competencies/` | Competency name | Definition, level criteria, Evidence (via backlinks) |
+| Brain note | `brain/` | Topic name | Topic-specific content |
+| Domain note | Beside its family index | `<Index> - <Domain>` (e.g. `Gotchas - Tooling`) | Substance lives here; the family index keeps a one-liner per entry. Born from monolith splits — never re-inline into the index |
+| Event-log satellite | Beside its core note | `<Core> — <Event> Log` or dated title | Chronological bulk offloaded from a person/project core note; the core links it. Dated entries, verbatim moves |
+| Archive note | Beside its live note | `<Live Name> Archive[ — <window>]` | Bulk by design, hygiene-exempt (name contains "Archive"). Verbatim zero-loss moves; live note keeps a one-liner index + link |
+
+### Linking -- This Is Critical
+
+**Graph-first, not folder-first.** Folders help browse in the sidebar. Links help discover through connections. Both matter, but links are the primary organizational tool.
+
+**A note without links is a bug.** When creating a note, the FIRST thing to do after writing content is add wikilinks. Every new note must link to at least one existing note.
+
+**Atomicity rule**: Before writing or appending to any note, ask: "Does this cover multiple distinct concepts that could be separate nodes?" If a note has or would have 3+ independent sections that don't need each other to make sense, split into atomic notes that link to each other.
+
+Note types have graph roles:
+- **Evidence nodes** (work notes, 1:1s, PR analyses): add outbound links to concepts they demonstrate
+- **Concept nodes** (competencies, patterns): stay definitional -- evidence arrives via backlinks
+- **Index nodes** (Index, Brag Doc, Memories, People & Context): actively curate links -- they're navigational
+- **Person nodes** (org/people/): link to projects, teams, evidence. Receive backlinks from work notes.
+
+Link syntax:
+- `[[Note Title]]` -- standard wikilink
+- `[[Note Title|display text]]` -- aliased link
+- `[[Note Title#Heading]]` -- deep link to section
+- `![[Note Title]]` -- embed content inline
+- `[[Note Title#^block-id]]` -- link to specific block
+
+#### When to Link
+
+- **Work note <-> Decision**: bidirectional links
+- **Work note -> Competency**: in `## Related`, link to competencies demonstrated
+- **Work note -> Team**: in `## Related`, link to team(s) involved
+- **Work note -> Person**: link people involved (especially in 1:1 notes)
+- **Person -> PR analysis**: link to their evidence file if one exists
+- **Brag Doc -> Work note**: every entry links to evidence
+- **Memories -> Source**: every memory links to where it was learned
+- **Index -> Everything**: `work/Index.md` links to all work notes
+- **North Star -> Projects**: active focus areas link to project work notes
+
+### Maintaining Indexes
+
+Update these when creating or archiving notes:
-The vault's memory lives in `brain/` — `Memories.md`, `Patterns.md`, `Key Decisions.md`, `Gotchas.md`. These are plain markdown files that any agent can read and write. When you learn something worth remembering, write it to the relevant `brain/` topic note with a wikilink to context.
+- **`work/Index.md`** -- add to Active Projects or Recent Notes, move completed to Archive
+- **`brain/Memories.md`** -- index of memory topics. Add new memories to the relevant topic note, not here.
+- **`brain/Skills.md`** -- register vault-specific workflows and slash commands
+- **`org/People & Context.md`** -- update when people, teams, or org structure changes
+- **`perf/Brag Doc.md`** -- log wins with links to evidence, add new quarters as needed
-The `~/.claude/` auto-loaded memory index is Claude Code-specific — skip that section in `CLAUDE.md`. The vault-side `brain/` notes are the source of truth.
+### Decision Records
-## Reaching this vault from another repo
+**When a decision earns a record.** Any ONE of these holding is enough:
-The `om` MCP server (`.claude/scripts/om-mcp.mjs`) exposes this vault over MCP, so a session running in a **different repository** can search it, read notes, follow the graph, and record durable lessons back into it. It speaks plain MCP over stdio, so any MCP-capable agent can register it — nothing about it is Claude Code-specific.
+- **Hard to reverse** — undoing it later costs real work (a schema, a public contract, a naming scheme).
+- **Surprising without context** — a competent reader would ask "why is it like this?" and the code alone cannot answer. This is the clause that stops the next contributor from "fixing" something deliberate.
+- **A real trade-off** — something was genuinely given up, so the losing option's case is worth keeping.
-Register it in the *consuming* project's MCP config, pointing at this vault's absolute path, then add a short section to that project's own agent doc telling it the vault exists. **Both steps are required**: measured, a session with the server wired but no repo-side instruction made zero vault calls, because a prohibition propagates into a session reliably while a positive "go look" does not.
+None hold → no record; the tracker and the commit message are enough. The gate is deliberately symmetric: it prescribes records where they are missing today, and it licenses *not* writing one everywhere else, which is what keeps the record set worth reading. Without it, records cluster where writing them was easy rather than where losing them is expensive.
-Do not register the raw `qmd` server in a consuming repo — it searches every note directly, so the repo matches against memories written for unrelated projects. Applying each memory's declared scope on top of the index is what `om` adds. Full details in `CLAUDE.md`.
+Once it clears the gate:
-## Subagents
+1. Create in `work/` using the Decision Record template
+2. Link from the work note(s) that led to the decision
+3. Add to the Decisions Log table in `work/Index.md`
+4. If significant, note in `brain/Key Decisions.md`
-9 subagents in `.claude/agents/` handle isolated tasks (brag spotting, vault auditing, cross-linking, etc.). The prompt content is agent-agnostic markdown.
+### Wins & Achievements
-- **Codex CLI**: as of the [Skills launch (Dec 2025)](https://developers.openai.com/codex/changelog), Codex discovers skills at `.agents/skills/<name>/SKILL.md` (directory-per-skill; frontmatter requires `name` and `description`). Mirror each `.claude/agents/*.md` into a `SKILL.md`, keeping the prompt body intact. See the [Codex Skills docs](https://developers.openai.com/codex/skills) for the full schema.
-- **Gemini CLI**: agents live in `.gemini/agents/`. Copy the files and adapt the YAML frontmatter fields to Gemini's schema.
+When significant work is completed, add to `perf/Brag Doc.md` with links to the work note(s). Categorize under Impact, Technical Growth, Collaboration, or Feedback.
+
+## North Star
+
+`brain/North Star.md` is a living document of goals and focus areas.
+
+- **Read it** at the start of substantial sessions
+- **Reference it** when suggesting priorities or trade-offs
+- **Update it** when the user signals a shift in goals
+- Both the user and the agent write to it
+
+## Tags Convention
+
+Use tags in frontmatter (not inline):
+
+- **Type**: `work-note`, `decision`, `perf`, `thinking`, `north-star`, `competency`, `person`, `team`, `brain`
+- **Index**: `index`, `moc`
+- **Status** (frontmatter field): `active`, `completed`, `archived`, `proposed`, `accepted`, `deprecated`
+- **Team** (frontmatter field on people + work notes): your team names, e.g. `Backend`, `Platform`, `Mobile`
+- **Cycle** (frontmatter field on review-related notes): `h2-2024`, `h1-2025`, etc.
+- **Person** (frontmatter field on evidence notes): full name of the person
+- **Project**: as needed, e.g. `project/auth-refactor`
+
+## Properties for Querying
+
+Beyond tags, use these frontmatter properties to enable search and Bases views:
+
+- `cycle: h2-2024` -- find all review material for a cycle
+- `person: "Jane Smith"` -- find all evidence related to a person
+- `team: Backend` -- find all notes related to a team
+- `status: active` -- find active projects
+- `quarter: Q1-2026` -- find all work for a quarter (used by Work Dashboard Base)
+- `ticket: TICKET-123` -- find incident by ticket number
+- `severity: high` -- incident severity
+- `role: incident-lead` -- your role in an incident
+
+## Memory System
+
+| System | Location | Purpose |
+|--------|----------|---------|
+| **Vault memories** | `brain/` topic notes | Git-tracked, Obsidian-browsable, linked. All durable knowledge lives here. |
+| **Cross-repo memories** | `memories/YYYY/MM/` | Written by sessions in *other* repos over MCP, under an enforced epistemic contract. See below. |
+
+**Which one, when you are working inside the vault:** `brain/`. Always. The `memories/` tree is written by the `om` MCP server on behalf of sessions elsewhere, and the server **refuses** a write from a session running inside the vault — a memory recorded here would be scoped to the vault-as-a-project and reach only the sessions that already read every note directly. Write the note normally and let the hooks file it.
+
+When asked to "remember" something:
+1. Find or create the appropriate `brain/` topic note (Gotchas, Patterns, Key Decisions, etc.)
+2. Add the knowledge there with a wikilink to context
+3. Update `brain/Memories.md` index if a new topic note was created
+
+### When to Consult Brain Topics
+
+Debugging, "how do we usually…", "why did we decide"? Read `.claude/rules/brain-topics.md` first.
+
+## Reaching the Vault From Another Repo
+
+Connecting this vault to another repo? Read `.claude/rules/vault-from-another-repo.md`.
+
+## Agent Guidelines
+
+### Graph-First Thinking
+
+- **Folders group by purpose, links group by meaning.** A note lives in ONE folder (its home) but links to MANY notes (its context).
+- When creating a note, add wikilinks FIRST. A note without links is a bug.
+- Prefer bidirectional links: if A links to B, B should link back to A (unless B is a concept node that receives backlinks passively).
+- Before creating a new subfolder, ask: "Can I solve this with a tag, a property, or a link instead?" Folders are for browsing convenience, not for categorization.
+- After every substantial session, verify new notes have at least one inbound link.
+
+### Where to Put Things
+
+- **Writing about a person?** -- `org/people/`
+- **Writing about a team?** -- `org/teams/`
+- **Writing about how the codebase works?** -- `brain/` (Patterns, Gotchas, Key Decisions)
+- **Writing about what the agent should remember?** -- `brain/Memories.md` topic notes
+- **Capturing a 1:1 meeting?** -- `work/1-1/`
+- **Deep scanning PRs for review?** -- `perf/evidence/`
+- **Creating review briefs?** -- `perf/<cycle>/`
+- **Tracking active project work?** -- `work/active/`
+- **Capturing an incident?** -- `work/incidents/` (use `/om-incident-capture`)
+- **Dumping unstructured info?** -- use `/om-dump` to auto-classify and route everything
+
+### Don't Mix Contexts
+
+When capturing data from Slack, DMs, or meetings:
+- **Project evidence** (PRs, technical decisions, delivery) -- goes to the relevant `work/` note
+- **Review prep** (peer selection, manager strategy, brag framing) -- goes to review-related notes in `perf/` or `work/`
+- **People dynamics** (feedback, relationships, career) -- goes to `org/people/` notes
+- **Personal conversations** -- only capture if review-relevant; otherwise skip
+
+## Hooks
-## What's Claude Code-specific
+Which hook runs on which event, for each agent: `.claude/rules/hooks-per-agent.md`.
-Two things are Claude Code-specific: the `~/.claude/` auto-memory loader, and the `obsidian-mind` mod in `.claude/skills/obsidian-mind/`, which on Claude Code 2.1.287+ delivers the session context as an instruction file and presents the Stop report. Neither is needed elsewhere: the mod only changes how the settings hooks' output reaches a Claude Code session, and every other agent runs those same hooks directly. Everything else (hooks, commands, subagent prompts, vault memory) is portable.
+## Write-Correctness Laws
-## Setup
+Each law exists because its absence caused real correction work in vaults running this template. Violating them re-creates documented failures.
-**Codex CLI**: Reads `AGENTS.md` natively. For direct access to `CLAUDE.md`, add to `~/.codex/config.toml`:
-```toml
-project_doc_fallback_filenames = ["CLAUDE.md"]
-```
+1. **Single-source status.** A project's volatile status (version, counts, released/blocked, dates) lives in exactly ONE place — its note's frontmatter + top status line. Every other note **links** to it and never restates it. *Why: one wrong status statement hardened into ~8 notes downstream and had to be swept out.*
+2. **Correction-sweep protocol.** When a fact is corrected, find every restatement and fix them all in the same pass. **`/om-correct "<the corrected fact>"` is the acting half** — grep alone finds only the notes that copied the wording, and the expensive half is the *paraphrase*: the same claim in different words, invisible to grep and indistinguishable from correct prose to every structural check. It is also the half most likely to survive a manual sweep, because the sweeper stops when grep goes quiet. A correction callout on top of a note whose body still says the wrong thing is NOT a correction — future sessions re-absorb the stain from the body. Notes that correctly record what was believed *at the time* are preserved, never rewritten; see Law 5.
+3. **Mark inference.** Anything not verified against source (code, repo, primary doc, the person) carries an explicit `(TBC)` / `(unverified)` / `(inferred)` marker. Never state inference bare.
+4. **Date-stamp volatile facts.** Counts, versions, org structure, tool maturity: write "as of YYYY-MM-DD" so staleness is self-evident instead of silent.
+5. **Attribution vs. creation dates may differ** (a `quarter:` field vs. the `date:` field's quarter) — that's legitimate, not a bug to "fix".
+6. **No counts in instruction files.** Hardcoded counts ("11 slash commands") in AGENTS.md/README rot silently — describe, don't count.
-**Gemini CLI**: Reads `GEMINI.md` natively. For direct access to `CLAUDE.md`, add to `~/.gemini/settings.json`:
-```json
-{ "context": { "fileName": ["GEMINI.md", "CLAUDE.md"] } }
-```
+## Rules
-**Other agents** (Cursor, Windsurf, Copilot): Read `AGENTS.md` for vault conventions. Hook support varies by agent.
+- **For "what's most recent," use `bases/Recently Touched.base` (real modified time), never filename dates** — a creation-date prefix on a continuously-edited note inverts the recency signal.
-For more information, see the [README](README.md).
+- Never modify `.obsidian/` config files unless explicitly asked.
+- Preserve existing frontmatter when editing notes.
+- Git sync is handled by the user's preferred method (obsidian-git, manual commits, etc.) -- don't configure git hooks or auto-commit.
+- When asked to "remember" something, write to the relevant `brain/` topic note with a link to context.
+- Prefer Obsidian CLI over filesystem when Obsidian is **already** running. On macOS, the first `obsidian` call launches the Electron app (visible window flash) if no instance is running — open Obsidian once at session start, then subsequent calls forward args silently. In non-interactive contexts where you can't guarantee Obsidian is open (background hooks, automation), prefer filesystem reads.
+- Always check for and suggest connections between notes.
+- Every note must have a `description` field (~150 chars). The agent fills this automatically.
+- **Zero data loss**: when reorganizing, always use `git mv`. Never delete without explicit user confirmation.
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 69f805d..100730d 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -2,7 +2,7 @@
This document describes how obsidian-mind fits together — the load-bearing seams, the design choices behind them, and where to extend the system. It is aimed at contributors and anyone forking the template who wants to customize it without breaking the mechanics.
-It is not a folder tour. For the day-to-day layout, read `CLAUDE.md`. For the user-facing story, read `README.md`.
+It is not a folder tour. For the day-to-day layout, read `AGENTS.md`. For the user-facing story, read `README.md`.
---
@@ -28,7 +28,7 @@ flowchart TB
end
subgraph Foreign["Agent session in ANOTHER repo"]
FSession["Coding session"]
- FConfig[".mcp.json entry<br/>+ that repo's own CLAUDE.md"]
+ FConfig[".mcp.json entry<br/>+ that repo's own instruction file"]
end
subgraph Vault["Obsidian vault"]
Manifest["vault-manifest.json<br/>(source of truth)"]
@@ -70,7 +70,7 @@ Two actors do the work, and the boundary between them is the most important desi
**Procedural code owns the environment.** Hooks in `.claude/scripts/` classify messages, validate writes, maintain the QMD index, inject context at session start, and back up transcripts before compaction. None of this logic is in the agent's head. It runs identically whether the agent is Claude Code, Codex, or Gemini, and it produces deterministic, testable behavior — every contract in `.claude/scripts/lib/` is locked by a unit suite, run in CI on every push.
-**The agent owns content.** Writing notes, choosing where to file them, adding wikilinks, updating indexes, promoting thinking drafts, drafting review briefs — these are judgments, not rules, and they live with the agent. `CLAUDE.md` documents the conventions the agent should follow; it does not replace the agent's judgment.
+**The agent owns content.** Writing notes, choosing where to file them, adding wikilinks, updating indexes, promoting thinking drafts, drafting review briefs — these are judgments, not rules, and they live with the agent. `AGENTS.md` documents the conventions the agent should follow; it does not replace the agent's judgment.
The two halves meet at small, well-defined handoffs: hooks inject context and routing hints through stdout, the agent reads the vault and calls Write or Edit. Neither side reaches across the boundary. This is what keeps the hooks portable (no agent-specific logic) and keeps the agent's tokens pointed at judgment rather than bookkeeping.
@@ -100,7 +100,7 @@ Session cost stays flat regardless of vault size because it is **enforced**, not
**The budget has a hard ceiling it cannot be raised past: Claude Code's hook output cap.** Claude Code caps a hook's plain stdout at 10,000 characters, with no setting to raise it. Over the cap, the session gets a file path and the first 2,000 characters, and Claude Code does not ask the model to read the rest. A budget above the cap never binds: nothing degrades, the meter on the last line is the first thing lost, and the meter the user reads still looks healthy (#254). So `session-start.ts` clamps any budget, set or unset, to the cap less room for the meter (9,100 bytes; bytes are never fewer than characters, so this holds the character cap too). When it clamps a configured value, the meter says so. The sections that never degrade (the date, open tasks, hygiene) could still pass the cap on their own, so the whole output is fitted as a backstop: cut on a line, marked where it was cut, the meter still last and saying it was "truncated to fit the hook output cap".
-**Within that ceiling, the budget is a runaway guard, not a squeeze.** The meter is the detector; the budget is the emergency brake. A ceiling low enough to bite in normal use degrades your context every session instead of catching a problem. If the budget starts firing, look at what grew. It can no longer be raised past the cap, so the fix is to make the section smaller or let it degrade to its pointer. Content a session must always have, in full, belongs in an instruction file (`CLAUDE.md` and its `@`-imports), which this cap does not apply to.
+**Within that ceiling, the budget is a runaway guard, not a squeeze.** The meter is the detector; the budget is the emergency brake. A ceiling low enough to bite in normal use degrades your context every session instead of catching a problem. If the budget starts firing, look at what grew. It can no longer be raised past the cap, so the fix is to make the section smaller or let it degrade to its pointer. Content a session must always have, in full, belongs in an instruction file (`AGENTS.md`, plus `.claude/rules/` on Claude Code), which this cap does not apply to.
The same asymmetry decides *what* may degrade. Rank the eager layer by **value density, not size**: filenames are the cheapest bytes (one Glob rebuilds them), so the listing surrenders first. Anything irreplaceable — identity, personal context, correctness guards — carries no fallback and is never traded for plumbing. Optimizing this layer means removing **duplication**, not **information**, which is exactly why re-entry via resume/compact drops the static bulk: it is already in the conversation, so omitting it loses nothing.
@@ -204,7 +204,7 @@ sequenceDiagram
A few specific design choices are worth calling out:
- **`SessionStart` injects, it does not load.** It builds a briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. Its size is bounded by `eager_layer_budget_bytes`, held under Claude Code's 10,000-character hook output cap, and reported by the meter on the last line of every injection, so the cost is visible rather than assumed. When the template's Claude Code mod delivers the same briefing as an instruction file instead, the hook stands down and the briefing is bounded by `eager_layer_instruction_budget_bytes`, since instruction files are not under the hook cap (#264). The same backstop holds there, in bytes: sections that never degrade are cut at the budget plus the meter's room, and the meter says "truncated to fit the instruction budget". The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI — that subprocess flashes the Electron app on macOS when no instance is running (#83).
-- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `CLAUDE.md`, which is editable per-user without touching scripts.
+- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `AGENTS.md`, which is editable per-user without touching scripts.
- **QMD refresh is shared, debounced, and detached.** Three hook entries fire the same refresh helper — `PostToolUse` (after `.md` writes), `PreCompact` (before transcript backup; writes tend to cluster before compaction), and `Stop` (after a response) — sharing one sentinel file so a burst of events produces at most one worker per debounce window. The actual indexing runs in `.claude/scripts/qmd-refresh-run.ts` as a detached, stdio-silent worker (`qmd update` → `qmd embed` → tail-chase `qmd update`), so the parent hook returns in milliseconds and nothing flows to the agent's context.
- **`PreCompact` also backs up the transcript.** In addition to kicking the QMD refresh, it copies the current session transcript out to `thinking/session-logs/` so long conversations remain recoverable after compaction.
- **`Stop` reports once, not every turn.** Claude and Codex fire it whenever the agent finishes a response, not when the session ends (#252). It triggers the shared refresh every time, but shows the checklist and hygiene findings only the first time a session sees that exact report, and again when the findings change; otherwise it returns the empty JSON envelope. A warning that repeats unchanged is one users learn to ignore (#155). The dedupe reuses the classifier's per-session state shape (#107): one self-pruning file, failing open to "show" on a missing `session_id` or unreadable state.
@@ -321,7 +321,7 @@ flowchart TB
CLI --> Store
```
-QMD is technically optional. When it isn't installed at all, the agent falls back through a preference order defined in `CLAUDE.md` and the qmd skill: MCP tools first when registered, then the `qmd` CLI, then Grep/Glob/Read as a last resort. Every fallback step is non-fatal: `.mcp.json` entries that fail to launch are skipped with a harmless warning, the hook scripts detect a missing `qmd` binary and no-op, and the operating manual tells the agent what to reach for next.
+QMD is technically optional. When it isn't installed at all, the agent falls back through a preference order defined in `AGENTS.md` and the qmd skill: MCP tools first when registered, then the `qmd` CLI, then Grep/Glob/Read as a last resort. Every fallback step is non-fatal: `.mcp.json` entries that fail to launch are skipped with a harmless warning, the hook scripts detect a missing `qmd` binary and no-op, and the operating manual tells the agent what to reach for next.
### QMD over MCP — the in-vault retrieval path
@@ -382,7 +382,7 @@ The split between rows 2 and 4 is load-bearing, because of an asymmetry measured
A rule in `instructions` — *"never put a session URL in a commit"* — held under direct pressure and under an authority override. A positive instruction — *"consult the vault before answering questions about past decisions"* — is advisory and gets skipped whenever a nearer source exists. **A server can stop a session doing something; it cannot make one go looking.**
-That is why `prompts` exist (the human invokes them, so no model decision is involved) and why the install requires a pointer in the *consuming repo's own* `CLAUDE.md` — the nearest source wins, so the nearest source has to be the thing that says "go look."
+That is why `prompts` exist (the human invokes them, so no model decision is involved) and why the install requires a pointer in the *consuming repo's own* instruction file (`CLAUDE.md` or `AGENTS.md`) — the nearest source wins, so the nearest source has to be the thing that says "go look."
### The tier ladder
@@ -876,7 +876,7 @@ A stray `VAULT_PATH` was honoured at one point, and that name is too generic to
}
```
-That goes in the **consuming project's** `.mcp.json`. Then add a short section to that project's own `CLAUDE.md` telling it the vault exists and to consult it.
+That goes in the **consuming project's** `.mcp.json`. Then add a short section to that project's own instruction file (`CLAUDE.md` or `AGENTS.md`) telling it the vault exists and to consult it.
Step 2 is not documentation garnish. 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. This follows directly from the prohibition/routing asymmetry above — and it makes the repo-side snippet a shipped deliverable, since a server installed without it is a server that gets ignored.
@@ -905,23 +905,31 @@ flowchart TB
S6["stop-checklist.ts"]
S7["qmd-refresh-run.ts<br/>(detached worker, not a hook)"]
end
- subgraph Manuals["Operating manuals"]
- CM["CLAUDE.md"]
- AM["AGENTS.md"]
- GM["GEMINI.md"]
+ subgraph Manuals["Instruction files"]
+ AM["AGENTS.md<br/>(every agent)"]
+ RM[".claude/rules/*.md<br/>(Claude-only files, and shared<br/>sections AGENTS.md points to)"]
end
Claude --> Shared
Codex --> Shared
Gemini --> Shared
- Claude -.reads.-> CM
+ Claude -.reads.-> AM
+ Claude -.reads.-> RM
+ AM -.points to.-> RM
Codex -.reads.-> AM
- Gemini -.reads.-> GM
+ Gemini -.reads.-> AM
```
Commands in `.claude/commands/` are plain Markdown prompts. Claude Code invokes them as slash commands. Codex and Gemini treat them as regular prompts (users type `om-standup` without the leading slash). No SDK binding is required.
-Adding a fourth agent means writing one more config file and, ideally, one more operating manual if the agent reads context files natively.
+Adding another agent means writing one more config file, and making sure it reads `AGENTS.md`: natively, or through a setting the way Gemini's `context.fileName` does. There is one instruction file, so there is no second manual to keep in sync. `.claude/rules/` holds the Claude-only files and the shared sections `AGENTS.md` points to: Claude Code and Grok load every file there at session start, and other agents read a shared one when a pointer sends them.
+
+### Subagents on other agents
+
+The subagents in `.claude/agents/` handle isolated tasks (brag spotting, vault auditing, cross-linking, etc.). The prompt content is agent-agnostic markdown.
+
+- **Codex CLI**: as of the [Skills launch (Dec 2025)](https://developers.openai.com/codex/changelog), Codex discovers skills at `.agents/skills/<name>/SKILL.md` (directory-per-skill; frontmatter requires `name` and `description`). Mirror each `.claude/agents/*.md` into a `SKILL.md`, keeping the prompt body intact. See the [Codex Skills docs](https://developers.openai.com/codex/skills) for the full schema.
+- **Gemini CLI**: agents live in `.gemini/agents/`. Copy the files and adapt the YAML frontmatter fields to Gemini's schema.
The `om` server sits outside this table on purpose. It speaks MCP over stdio and knows nothing about which harness is on the other end, so it needs no per-agent config at all — any MCP-capable client registers it the same way.
@@ -962,7 +970,7 @@ Two load paths into a session, both landing in the vault:
All actual memory content lives in `brain/` as real Obsidian notes — queryable by QMD, visible in the graph, and shared across every agent (Claude Code, Codex, Gemini) because they all read the same vault.
-The rule that enforces this: "when asked to remember, write to the relevant `brain/` topic note, not to `~/.claude/`." It is restated in `CLAUDE.md` because it is the easiest rule to break and the hardest to detect breaking.
+The rule that enforces this: "when asked to remember, write to the relevant `brain/` topic note, not to `~/.claude/`." It is restated in `AGENTS.md` because it is the easiest rule to break and the hardest to detect breaking.
### Two stores, one vault
@@ -1004,9 +1012,9 @@ The design makes these changes easy:
|--------|------------|
| Add a new note type | `vault-manifest.json` → `frontmatter_required`, and a template in `templates/` |
| Isolate this vault from others on the same machine | automatic (folder-derived); override with `vault-manifest.json` → `qmd_index`, then re-bootstrap |
-| Add a new classification category | `.claude/scripts/classify-message.ts` + `CLAUDE.md` routing rules |
+| Add a new classification category | `.claude/scripts/classify-message.ts` + `AGENTS.md` routing rules |
| Add a new lifecycle behavior | A new script in `.claude/scripts/` wired into all three agent configs |
-| Add a new agent (Cursor, Windsurf, …) | New config file mapping events to existing scripts, optionally a new operating manual |
+| Add a new agent (Cursor, Windsurf, …) | New config file mapping events to existing scripts; the agent reads `AGENTS.md` |
| Add a new subagent | A new Markdown file in `.claude/agents/`, referenced from the command that invokes it |
| Add a new Base view | A new `.base` file in `bases/`, embedded from `Home.md` if it should surface |
| Change which notes `om` serves | `vault-manifest.json` → `mcp_exposed_roots` / `mcp_never_expose`, or tag a note `private` |
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index 0c95ac6..0000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1,474 +0,0 @@
-# Obsidian Mind
-
-Personal Obsidian vault -- an external brain for work notes, decisions, performance tracking, and Claude context.
-
-## Skills & Capabilities
-
-This vault has [obsidian-skills](https://github.com/kepano/obsidian-skills) installed in `.claude/skills/`. Follow these skill conventions:
-
-- **obsidian-markdown**: Obsidian-flavored markdown -- wikilinks, embeds, callouts, properties. See `references/` for callout types, embed syntax, and property specs. Always prefer `[[wikilinks]]` over markdown links.
-- **obsidian-cli**: CLI commands for vault operations when Obsidian is running. See CLI section below.
-- **json-canvas**: Create `.canvas` files with nodes, edges, and visual layouts. See `references/EXAMPLES.md`.
-- **obsidian-bases**: Create `.base` files with views, filters, and formulas. Bases core plugin is enabled. See `references/FUNCTIONS_REFERENCE.md`.
-- **defuddle**: Extract clean markdown from web pages via `defuddle parse <url> --md`.
-- **qmd**: Semantic search across the vault via [QMD](https://github.com/tobi/qmd). Use PROACTIVELY before reading files. **Preference order — pick the highest surface available and stop:**
- 1. **`mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, `mcp__qmd__status`** — registered MCP tools. If you see them in your tool menu, they are live and pre-scoped to this vault's index. Use them first; no `--index` argument needed.
- 2. **`qmd --index <name> query|search|vsearch|get|multi-get`** — CLI fallback for one-off shell checks or when the MCP server is unavailable. Always pass `--index <name>`, where `<name>` is the `qmd_index` field from `vault-manifest.json` when set and otherwise the vault folder name slugified, so the SQLite store stays isolated from other vaults on the machine.
- 3. **Grep / Glob / Read** — last resort, only when QMD is not installed at all.
-
- The MCP server (`.mcp.json` → `.claude/scripts/qmd-mcp.mjs`), the CLI, and the SessionStart hook all read the same manifest field, so every surface scopes to the same store. On a fresh clone, run `node --experimental-strip-types .scripts/qmd-bootstrap.ts` once to build the index. Note: the MCP connect-time banner can read "0 documents" when the server registers before the SessionStart reindex finishes — a stale snapshot, not the dead-search state the self-heal guards; don't diagnose it.
-
-### Custom Slash Commands
-
-Defined in `.claude/commands/`. Claude Code auto-surfaces every command with its description in the session's skills list — **that injected list is the live catalog**. Do not maintain a command table here (it drifts; the injected list can't — see Write-Correctness law 6). **Agents without that injection (Codex, Gemini, Cursor): read `brain/Skills.md`** — it carries the full command catalog plus usage docs and workflow sequences.
-
-## Vault Structure
-
-| Folder | Purpose | Key Files |
-|--------|---------|-----------|
-| `Home.md` | **Vault entry point** -- embedded Base views, quick links | Open this first |
-| `vault-manifest.json` | **Template metadata** -- version, infrastructure vs user content boundaries, frontmatter schemas, version fingerprints | Used by `/om-vault-upgrade` for migration |
-| `CHANGELOG.md` | **Version history** -- tracks template releases (v1--v3.3) with what changed | Reference for upgrade paths |
-| `bases/` | **All Bases centralized** -- dynamic views for navigation | `Work Dashboard` (incl. 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/active/` | **Current projects only** (1-3 files) | Move here when starting, move to archive when done |
-| `work/archive/YYYY/` | Completed work organized by year | Grows over time |
-| `work/incidents/` | Incident docs (main note + RCA + deep dive + drafts) | Per-incident grouping |
-| `work/1-1/` | 1:1 meeting notes (accumulate weekly) | Named `<Person> YYYY-MM-DD.md` |
-| `work/meetings/` | **Meeting notes inbox** -- staging area for raw exports, processed by `/om-intake` | Drop files, run `/om-intake` |
-| `perf/` | Performance framework, brag doc | `Brag Doc.md` (index) |
-| `perf/brag/` | Quarterly brag notes | One per quarter, e.g. `Q1 2025.md` |
-| `perf/competencies/` | Atomic competency notes (link targets) | One note per competency |
-| `perf/evidence/` | PR deep scans, data extracts for reviews | Named `<Person> PRs - <Period>.md` |
-| `perf/<cycle>/` | Review cycle briefs + artifacts | Review briefs (private, manager, peer) |
-| `brain/` | Claude's operational knowledge | `Memories.md`, `Key Decisions.md`, `Patterns.md`, `Gotchas.md`, `Skills.md`, `North Star.md` |
-| `memories/YYYY/MM/` | **Cross-repo agent memory** -- durable lessons recorded over MCP by sessions working in *other* repositories. Time is the only thing in the path; reach is declared in frontmatter | Browse via `bases/Memories.base`; never edit by hand |
-| `org/` | Organizational knowledge index | `People & Context.md` (MOC) |
-| `org/people/` | Atomic person notes | One note per person |
-| `org/teams/` | Team notes as graph nodes | One note per team |
-| `reference/` | Codebase knowledge, architecture maps | Flow docs, architecture docs |
-| `thinking/` | Scratchpad for drafts and reasoning | Named `YYYY-MM-DD-topic.md` |
-| `templates/` | Obsidian templates | `Work Note.md`, `Decision Record.md`, etc. |
-| `.claude/commands/` | Slash commands (auto-surfaced in-session; catalog in `brain/Skills.md`) | One `.md` per command |
-| `.claude/agents/` | Subagents | See subagents table below |
-| `.claude/scripts/` | Hook scripts + the MCP server | `session-start.ts`, `classify-message.ts`, `validate-write.ts`, `pre-compact.ts`, `stop-checklist.ts`, `charcount.ts`, `om-mcp.mjs` (see **Reaching the vault from another repo** below) |
-| `.claude/skills/` | Obsidian + QMD skills, and the `obsidian-mind` Claude Code mod | Skills load via the Skill tool; the mod loads as a plugin on Claude Code 2.1.287+ |
-
-## Obsidian CLI
-
-When Obsidian is running, prefer CLI over raw filesystem — it provides vault-aware search, backlink discovery, and property management. **On macOS, open Obsidian before invoking the CLI**: the first `obsidian` call launches the Electron app (visible window flash) if no instance is running; subsequent calls forward args silently. In non-interactive contexts where you can't guarantee Obsidian is open (background hooks, automation), prefer filesystem reads instead.
-
-```bash
-obsidian read file="Note Name" # Read a note
-obsidian create name="Name" content="..." silent # Create without opening
-obsidian append file="Name" content="..." # Append to note
-obsidian search query="text" limit=10 # Vault-aware search
-obsidian backlinks file="Name" # Discover connections
-obsidian tags sort=count counts # List all tags
-obsidian tasks daily todo # Open tasks
-obsidian daily:read # Today's daily note
-obsidian property:set name="status" value="done" file="Name"
-obsidian orphans # Unlinked notes
-```
-
-`file=` resolves like a wikilink (by name). `path=` for exact path from root. Use `silent` to prevent files from opening. Run `obsidian help` for full reference.
-
-## Session Workflow
-
-### Starting a Substantial Session
-
-The `SessionStart` hook automatically injects rich context: vault file listing, North Star goals, active work, recent git changes, open tasks (aggregated from `work/active/` and the vault root, excluding infrastructure files), vault-hygiene drift flags (act on them or run `/om-tidy`), and triggers a QMD re-index. Most context is already loaded -- you don't need to manually read files.
-
-**Shortcut**: Run `/om-standup` for a structured morning kickoff that reads everything and presents a summary with suggested priorities.
-
-If doing it manually:
-
-1. Read `Home.md` -- vault entry point with embedded dashboards
-2. Read `brain/North Star.md` -- ground suggestions in current goals
-3. Check `work/Index.md` -- see active projects and recent notes
-4. Scan `brain/Memories.md` -- index of memory topics, then read relevant topic notes
-5. `obsidian tasks daily todo` -- see pending items
-
-### Ending a Substantial Session
-
-**When the user says "wrap up", "let's wrap", "wrapping up", or similar -- invoke `/om-wrap-up` automatically.** This runs a full review of the session.
-
-If `/om-wrap-up` is not invoked, at minimum do these before wrapping up:
-
-1. **Archive completed projects**: `git mv` from `work/active/` to `work/archive/YYYY/`, update `status: completed` (or use `/om-project-archive`)
-2. Update `work/Index.md` if new notes or decisions were created
-3. Update the relevant brain topic note (`brain/Key Decisions.md`, `brain/Patterns.md`, `brain/Gotchas.md`) with key learnings
-4. Update `org/People & Context.md` if org knowledge changed
-5. Update `perf/Brag Doc.md` if wins or impact were achieved
-6. Offer to update `brain/North Star.md` if goals shifted or new focus emerged
-7. Verify all new notes link to at least one existing note (orphans are bugs)
-8. If work demonstrates competencies, add competency links to the work note's `## Related`
-9. Run `/om-vault-audit` if the session created many notes
-
-Skip steps that don't apply. The goal is transferring durable knowledge from conversation to vault state.
-
-### Thinking Workflow
-
-Use `thinking/` for drafts, reasoning, and analysis before writing final notes. **Thinking notes are scratchpads, not storage.** They exist to help you reason -- once the reasoning produces durable knowledge, promote it to proper notes and delete the scratchpad.
-
-1. Create a thinking note: `thinking/YYYY-MM-DD-descriptive-name.md`
-2. Use the Thinking Note template
-3. Reason through the problem, analyze options, draft content
-4. Promote findings to atomic notes in the correct folder (not one monolith -- one note per distinct concept)
-5. Delete the thinking note -- it served its purpose
-6. If the thinking process itself is worth preserving (unusual), keep it but link to the promoted notes
-
-### Creating Notes
-
-1. **Always use YAML frontmatter** with at minimum `date`, `description` (~150 chars), `tags`, and type-specific fields. Work notes and incidents also need `quarter` (e.g., `Q1-2026`). Incidents need `ticket`, `severity`, `role`.
-2. **Use templates** from `templates/`. Fill `{{placeholders}}` with real values.
-2b. **Write fully, organize structurally — the vault tidies itself.** Size is a STRUCTURE signal, never a brevity signal: when a note crosses the ~25KB organization threshold (bytes, not lines — giant single-line entries hide in low line counts), the PostToolUse hook flags it at write time and the hygiene scan flags it at session boundaries. The response is always a SPLIT (domain notes, event-log satellites, or a cluster folder — content moved verbatim, one-liner index left behind, inbound links retargeted), never trimming content. The same hook flags write-time topic clusters — token overlap is blind, so judge genuine shared context before grouping. `/om-tidy` is the acting half. Exempt: `*Archive*` notes (bulk is their job).
-3. **Place files correctly**:
- - **Active** work notes, decisions, peer review prep -- `work/active/`
- - **Completed** work notes -- `work/archive/YYYY/` (by year)
- - Incident docs -- `work/incidents/`
- - 1:1 meeting notes -- `work/1-1/`
- - Performance content -- `perf/` (cycle subfolder for review briefs)
- - PR evidence -- `perf/evidence/`
- - Competency definitions -- `perf/competencies/`
- - People -- `org/people/`
- - Teams -- `org/teams/`
- - Claude operational context -- `brain/`
- - Codebase knowledge -- `reference/`
- - Drafts -- `thinking/`
- - Vault root: `Home.md`, `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `vault-manifest.json`, `CHANGELOG.md`, `CONTRIBUTING.md`, `README.md`, `LICENSE`, `.gitignore`. No user notes at root.
-4. **Name files descriptively.** Use the note title as filename. **Date convention:** prefix **point-in-time** notes with a date — 1:1s (`<Person> YYYY-MM-DD.md`), dated captures, meeting exports. **Living and entity notes use a bare title** — work notes, person/team notes, competencies, `brain/`, `reference/`. *Why the split:* a creation-date prefix on a continuously-edited note **inverts the recency signal** (a living doc looks stale while being updated daily). For "what's most recent," use `bases/Recently Touched.base` (real modified time), never filename dates.
-5. **Group multi-note workstreams in a subfolder.** Once a workstream has more than one note, it gets a folder (`work/active/<Topic>/`; the archive mirrors the grouping). Folders are the lifecycle/context axis only — links remain the primary organization (wikilinks resolve by name across folders, so grouping never breaks links, QMD, or the graph). The hygiene scan and write-time cluster sensor flag candidates; `/om-project-archive` moves whole clusters.
-
-### Note Types
-
-| Type | Location | Naming | Key Sections |
-|------|----------|--------|--------------|
-| Work note | `work/active/` (then `archive/YYYY/` when done) | Descriptive title | Context, What/Why, Links, Related |
-| Incident | `work/incidents/` | Ticket number or descriptive title | Context, Root Cause, Timeline, Impact, Analysis, Related |
-| 1:1 note | `work/1-1/` | `<Person> YYYY-MM-DD.md` | Key Takeaways, Action Items, Quotes, What to Watch, Related |
-| PR analysis | `perf/evidence/` | `<Person> PRs - <Period>.md` | PR Count, Projects, Quality, Growth, Full Table |
-| Review brief | `perf/<cycle>/` | `<Cycle> Review Brief.md` | Arc, Impact, Competencies, Documentation Trail |
-| Person note | `org/people/` | Full name | Role & Team, Relationship, Key Moments, Notes |
-| Team note | `org/teams/` | Team name | Members, Scope, Interactions |
-| Competency | `perf/competencies/` | Competency name | Definition, level criteria, Evidence (via backlinks) |
-| Brain note | `brain/` | Topic name | Topic-specific content |
-| Domain note | Beside its family index | `<Index> - <Domain>` (e.g. `Gotchas - Tooling`) | Substance lives here; the family index keeps a one-liner per entry. Born from monolith splits — never re-inline into the index |
-| Event-log satellite | Beside its core note | `<Core> — <Event> Log` or dated title | Chronological bulk offloaded from a person/project core note; the core links it. Dated entries, verbatim moves |
-| Archive note | Beside its live note | `<Live Name> Archive[ — <window>]` | Bulk by design, hygiene-exempt (name contains "Archive"). Verbatim zero-loss moves; live note keeps a one-liner index + link |
-
-### Linking -- This Is Critical
-
-**Graph-first, not folder-first.** Folders help browse in the sidebar. Links help discover through connections. Both matter, but links are the primary organizational tool.
-
-**A note without links is a bug.** When creating a note, the FIRST thing to do after writing content is add wikilinks. Every new note must link to at least one existing note.
-
-**Atomicity rule**: Before writing or appending to any note, ask: "Does this cover multiple distinct concepts that could be separate nodes?" If a note has or would have 3+ independent sections that don't need each other to make sense, split into atomic notes that link to each other.
-
-Note types have graph roles:
-- **Evidence nodes** (work notes, 1:1s, PR analyses): add outbound links to concepts they demonstrate
-- **Concept nodes** (competencies, patterns): stay definitional -- evidence arrives via backlinks
-- **Index nodes** (Index, Brag Doc, Memories, People & Context): actively curate links -- they're navigational
-- **Person nodes** (org/people/): link to projects, teams, evidence. Receive backlinks from work notes.
-
-Link syntax:
-- `[[Note Title]]` -- standard wikilink
-- `[[Note Title|display text]]` -- aliased link
-- `[[Note Title#Heading]]` -- deep link to section
-- `![[Note Title]]` -- embed content inline
-- `[[Note Title#^block-id]]` -- link to specific block
-
-#### When to Link
-
-- **Work note <-> Decision**: bidirectional links
-- **Work note -> Competency**: in `## Related`, link to competencies demonstrated
-- **Work note -> Team**: in `## Related`, link to team(s) involved
-- **Work note -> Person**: link people involved (especially in 1:1 notes)
-- **Person -> PR analysis**: link to their evidence file if one exists
-- **Brag Doc -> Work note**: every entry links to evidence
-- **Memories -> Source**: every memory links to where it was learned
-- **Index -> Everything**: `work/Index.md` links to all work notes
-- **North Star -> Projects**: active focus areas link to project work notes
-
-### Maintaining Indexes
-
-Update these when creating or archiving notes:
-
-- **`work/Index.md`** -- add to Active Projects or Recent Notes, move completed to Archive
-- **`brain/Memories.md`** -- index of memory topics. Add new memories to the relevant topic note, not here.
-- **`brain/Skills.md`** -- register vault-specific workflows and slash commands
-- **`org/People & Context.md`** -- update when people, teams, or org structure changes
-- **`perf/Brag Doc.md`** -- log wins with links to evidence, add new quarters as needed
-
-### Decision Records
-
-**When a decision earns a record.** Any ONE of these holding is enough:
-
-- **Hard to reverse** — undoing it later costs real work (a schema, a public contract, a naming scheme).
-- **Surprising without context** — a competent reader would ask "why is it like this?" and the code alone cannot answer. This is the clause that stops the next contributor from "fixing" something deliberate.
-- **A real trade-off** — something was genuinely given up, so the losing option's case is worth keeping.
-
-None hold → no record; the tracker and the commit message are enough. The gate is deliberately symmetric: it prescribes records where they are missing today, and it licenses *not* writing one everywhere else, which is what keeps the record set worth reading. Without it, records cluster where writing them was easy rather than where losing them is expensive.
-
-Once it clears the gate:
-
-1. Create in `work/` using the Decision Record template
-2. Link from the work note(s) that led to the decision
-3. Add to the Decisions Log table in `work/Index.md`
-4. If significant, note in `brain/Key Decisions.md`
-
-### Wins & Achievements
-
-When significant work is completed, add to `perf/Brag Doc.md` with links to the work note(s). Categorize under Impact, Technical Growth, Collaboration, or Feedback.
-
-## North Star
-
-`brain/North Star.md` is a living document of goals and focus areas.
-
-- **Read it** at the start of substantial sessions
-- **Reference it** when suggesting priorities or trade-offs
-- **Update it** when the user signals a shift in goals
-- Both the user and Claude write to it
-
-## Tags Convention
-
-Use tags in frontmatter (not inline):
-
-- **Type**: `work-note`, `decision`, `perf`, `thinking`, `north-star`, `competency`, `person`, `team`, `brain`
-- **Index**: `index`, `moc`
-- **Status** (frontmatter field): `active`, `completed`, `archived`, `proposed`, `accepted`, `deprecated`
-- **Team** (frontmatter field on people + work notes): your team names, e.g. `Backend`, `Platform`, `Mobile`
-- **Cycle** (frontmatter field on review-related notes): `h2-2024`, `h1-2025`, etc.
-- **Person** (frontmatter field on evidence notes): full name of the person
-- **Project**: as needed, e.g. `project/auth-refactor`
-
-## Properties for Querying
-
-Beyond tags, use these frontmatter properties to enable search and Bases views:
-
-- `cycle: h2-2024` -- find all review material for a cycle
-- `person: "Jane Smith"` -- find all evidence related to a person
-- `team: Backend` -- find all notes related to a team
-- `status: active` -- find active projects
-- `quarter: Q1-2026` -- find all work for a quarter (used by Work Dashboard Base)
-- `ticket: TICKET-123` -- find incident by ticket number
-- `severity: high` -- incident severity
-- `role: incident-lead` -- your role in an incident
-
-## Memory System
-
-**All project memories live in the vault.** The `~/.claude/` MEMORY.md is an auto-loaded index that points to vault locations. The `~/.claude/` MEMORY.md is the only file that should exist there -- it is an auto-loaded index. Never create additional memory files in that directory.
-
-| System | Location | Purpose |
-|--------|----------|---------|
-| **MEMORY.md** | `~/.claude/projects/.../memory/MEMORY.md` | Auto-loaded index only. Pointers to vault notes. |
-| **Vault memories** | `brain/` topic notes | Git-tracked, Obsidian-browsable, linked. All durable knowledge lives here. |
-| **Cross-repo memories** | `memories/YYYY/MM/` | Written by sessions in *other* repos over MCP, under an enforced epistemic contract. See below. |
-
-**Which one, when you are working inside the vault:** `brain/`. Always. The `memories/` tree is written by the `om` MCP server on behalf of sessions elsewhere, and the server **refuses** a write from a session running inside the vault — a memory recorded here would be scoped to the vault-as-a-project and reach only the sessions that already read every note directly. Write the note normally and let the hooks file it.
-
-When asked to "remember" something:
-1. Find or create the appropriate `brain/` topic note (Gotchas, Patterns, Key Decisions, etc.)
-2. Add the knowledge there with a wikilink to context
-3. Update `brain/Memories.md` index if a new topic note was created
-4. Do NOT create additional files in `~/.claude/projects/.../memory/` beyond MEMORY.md -- they are not version-controlled
-
-### When to Consult Brain Topics
-
-The SessionStart hook injects a **Brain Topics (read on demand)** index listing each `brain/` topic note with its description and an `(empty)` marker for stub notes. Treat that index as a menu:
-
-- When the user's message touches a topic from the index (debugging → Gotchas, "how do we usually…" → Patterns, "why did we decide" → Key Decisions, "which command / slash" → Skills), query QMD **first** before answering — call `mcp__qmd__query` with a `query` argument describing the topic (or fall back to `qmd --index <name> query "<topic>"` if MCP is unavailable). The search covers the whole vault, so filter or prioritize results whose `file` path is under `brain/`. Do not assume the topic name alone scopes the search.
-- If QMD is unavailable, read the specific `brain/` note directly with the Read tool. Don't load all of `brain/` — only the one(s) matching the topic.
-- Skip notes marked `(empty)` in the index — they're stubs with no substantive content.
-- After answering, if the conversation produced durable knowledge, update the relevant brain note (see the "remember" workflow above).
-
-## Reaching the Vault From Another Repo
-
-The vault normally only helps while you are sitting in it. The **`om` MCP server** makes it reachable from a coding session running in any other repository: that session can search the vault, read notes, follow the graph, and record back into it.
-
-### The install is two steps, and both are required
-
-**1. Register the server** in the consuming project's `.mcp.json`:
-
-```json
-{
- "mcpServers": {
- "om": {
- "command": "node",
- "args": ["<absolute path to your vault>/.claude/scripts/om-mcp.mjs"]
- }
- }
-}
-```
-
-**2. Add a short section to that project's own `CLAUDE.md`**, telling it the vault exists and to consult it.
-
-> [!warning] Step 2 is not documentation garnish.
-> **Measured:** with the server wired and *no* repo-side instruction, a session made **zero** vault calls and went on to implement a design the vault had recorded as explicitly rejected. With the instruction present, it refused and cited the note.
->
-> The reason is an asymmetry in how MCP `instructions` propagate: a **prohibition** holds reliably, while 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.
-
-> [!warning] Do not register the raw `qmd` server in a consuming repo.
-> It searches every note directly, with no notion of which memories were written for which project — so the repo matches against lessons meant for unrelated ones. Applying each memory's declared scope on top of the index is exactly what `om` adds, and going around it returns the **wrong** things, not merely more of them.
-
-### What it exposes
-
-| tool | purpose |
-|------|---------|
-| `search` | semantic + keyword search over exposed notes |
-| `expand` | a note's graph neighbourhood — links out and backlinks |
-| `recall` | durable lessons scoped to the calling repo, most specific first |
-| `remember` | record a lesson that will still be true in a different repo |
-| `record_work` | record what happened in this repo, filed where it belongs |
-| `reason` | judgement across several notes — spawns a second session, so it takes longer |
-| `health` | is the wiring intact? |
-
-Plus notes as readable **resources**, and `recall_topic` / `prior_art` as **prompts** you invoke yourself from the `/` menu.
-
-### `reason` — judgement across notes
-
-The other tools answer without inference. `reason` reads the vault with a second Claude session, so it is slower and uses more — reach for it when `search` or `recall` returned the notes but not the judgement. It seeds itself from search, so there is no need to search first.
-
-**It runs on your own CLI default model**, so the vault answers at the level you are already working at. MCP gives a server no way to see the calling session's model, so inheriting the CLI default is the closest reachable thing to "the same model I am using".
-
-**Every call is on the record** — including one that produced no answer, since the log is written before any refusal. It lands in `.claude/om-mcp-audit.jsonl` with the question, cost, turns, terminal reason, model asked for, model that ran, wall time, and the roots the spawn was given. `health` reports the day's figure, and says *at least* when the log was too big to read whole rather than quietly under-reporting.
-
-**It reads what this vault serves, and nothing else.** The spawn is handed the same three rules the exposure policy applies to search results: your `mcp_exposed_roots`, your `mcp_never_expose` filenames, and `private:`-tagged notes — the last two matter because they live *inside* exposed roots. Unset, that is simply your `user_content_roots`, so the boundary is whatever you already declared rather than anything this tool adds. It is also told not to read the memory root, since a memory belongs to the project it was scoped to.
-
-**The server stays responsive while it runs.** Other tools answer normally mid-call, and a shutdown ends any spawn still in flight rather than orphaning it.
-
-One optional key, which does not ship set:
-
-```json
-"reason": { "model": "claude-haiku-4-5" } // pin a model instead of inheriting
-```
-
-Left unset — the default — it uses your own Claude settings.
-
-> [!warning] If you pin a model, use a FULL id.
-> `--model haiku` is not honoured by the CLI and does not error — it silently runs `claude-sonnet-5`. Bare aliases (`haiku`, `sonnet`, `opus`) are therefore dropped in favour of inheriting; anything else is passed through as written. Every answer names the model that actually ran, and says whether it was the pinned one.
-
-If a run ends early you get **no answer**, not a truncated one, plus the evidence search already found — a partial synthesis presented as complete is the one outcome worse than none.
-
-Answers land in `.claude/om-reasoning/` (gitignored) marked `confidence: inferred`. They are deliberately **not** recorded as memories — a spawned conclusion is reasoning, not verified knowledge, and the calling session decides whether any of it earns a `remember`.
-
-### Which memories reach which project
-
-This is the part worth understanding, and it is what the layer is for. Every memory declares its reach when written:
-
-- `scope: project`, `projects: [a, b]` — reaches those repos and no others
-- `scope: platform`, `platforms: [ios]` — reaches any repo on that platform
-- `scope: general` — reaches everywhere
-
-A reader never widens what the writer declared, so a sibling app on the same platform does not inherit another app's project-scoped constraints. `recall` with `explain: true` reports why each memory was shown and how many were withheld.
-
-**Getting the reach wrong is corrected the same way any other error is** — `remember` is append-only, so re-file the lesson with the right scope and pass `supersedes: ["<its exact title>"]`. Narrowing takes effect: a superseded memory is served only where its correction can follow it, so the caller the correction excludes stops receiving the wider stale copy rather than receiving it alone with nothing to replace it.
-
-**A repo is identified by its folder name**, which is usually right and occasionally not: two repos both called `api` share one identity, so each receives the other's memories. Write a distinct name into a `.om-project` file at the repo root to separate them — `health` reports which repo it thinks is calling and where that name came from.
-
-### Which notes the server serves
-
-Your vault, your notes, your session. The default is the vault's own `user_content_roots`, at the granularity it declares them (`work/active/`, not all of `work/`). Set `mcp_exposed_roots` only if this vault holds material that is **not yours to share** — employer-confidential notes, a client's data.
-
-| key | default | meaning |
-|-----|---------|---------|
-| `mcp_exposed_roots` | *(empty → `user_content_roots`)* | folders whose notes may be read |
-| `mcp_never_expose` | *(empty)* | filenames withheld regardless of folder |
-| `memory_root` | `memories` | where cross-repo memories live |
-| `mcp_inbox` | `inbox` | fallback destination for `record_work` |
-
-`memories/` is never served as an ordinary note whatever the config says — memories carry their own scope, and the note surface would bypass it. A note tagged `private` in frontmatter is never served either.
-
-That holds on **every** surface, including the one that reads across both. `recall` serves a promoted block out of `brain/` when a capture's `promoted:` marker carries an anchor (`promoted: "brain/Gotchas - Engineering#^om-a1b2c3"`), so a foreign repo gets the corrected version rather than the capture as first written. It asks the same exposure predicate as everything else, so a withheld or `private` note is refused there too, and a marker with no anchor still serves nothing. Write anchors with `/om-tidy` — the block you point at is what a session in another repo reads.
-
-> [!note] Keeping vault material out of repos is the contract's job, not this list's.
-> A session can read the vault directly, so narrowing what the server serves prevents nothing on its own. What works is the prohibition injected into the calling session, plus `.claude/om-mcp-audit.jsonl` (gitignored), which records every read with the calling repo.
-
-Run `health` when something that should be in the vault cannot be found — every failure in this layer presents identically as "no results", and that tool is what tells them apart.
-
-## Agent Guidelines
-
-### Graph-First Thinking
-
-- **Folders group by purpose, links group by meaning.** A note lives in ONE folder (its home) but links to MANY notes (its context).
-- When creating a note, add wikilinks FIRST. A note without links is a bug.
-- Prefer bidirectional links: if A links to B, B should link back to A (unless B is a concept node that receives backlinks passively).
-- Before creating a new subfolder, ask: "Can I solve this with a tag, a property, or a link instead?" Folders are for browsing convenience, not for categorization.
-- After every substantial session, verify new notes have at least one inbound link.
-
-### Where to Put Things
-
-- **Writing about a person?** -- `org/people/`
-- **Writing about a team?** -- `org/teams/`
-- **Writing about how the codebase works?** -- `brain/` (Patterns, Gotchas, Key Decisions)
-- **Writing about what Claude should remember?** -- `brain/Memories.md` topic notes
-- **Capturing a 1:1 meeting?** -- `work/1-1/`
-- **Deep scanning PRs for review?** -- `perf/evidence/`
-- **Creating review briefs?** -- `perf/<cycle>/`
-- **Tracking active project work?** -- `work/active/`
-- **Capturing an incident?** -- `work/incidents/` (use `/om-incident-capture`)
-- **Dumping unstructured info?** -- use `/om-dump` to auto-classify and route everything
-
-### Don't Mix Contexts
-
-When capturing data from Slack, DMs, or meetings:
-- **Project evidence** (PRs, technical decisions, delivery) -- goes to the relevant `work/` note
-- **Review prep** (peer selection, manager strategy, brag framing) -- goes to review-related notes in `perf/` or `work/`
-- **People dynamics** (feedback, relationships, career) -- goes to `org/people/` notes
-- **Personal conversations** -- only capture if review-relevant; otherwise skip
-
-## Subagents
-
-Specialized agents in `.claude/agents/` for heavy operations. They run in isolated context windows.
-
-| 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 |
-| `correction-sweep` | Finds every note restating a corrected fact; classifies each as authoritative, restatement, or historical. Never edits | `/om-correct` |
-| `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` | Verifies every claim in a review draft against vault sources | `/om-self-review`, `/om-review-peer` |
-| `vault-migrator` | Classifies, transforms, and migrates content from a source vault | `/om-vault-upgrade` |
-
-## Hooks
-
-Five lifecycle hooks in `.claude/settings.json`:
-
-| Hook | When | What |
-|------|------|------|
-| SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star, active work, recent changes, tasks, file listing (folders past a note-count threshold collapse to one line), vault-hygiene drift flags (completed-not-archived, ungrouped clusters, 25KB oversize, stale open loops, meetings-inbox pressure); the whole injection is held under a byte budget that fits Claude Code's 10,000-character hook output cap — over it, low-priority sections degrade to pointers and the closing injection-size meter names each one it dropped |
-| UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints; also hands the agent a Stop report saved since the last prompt |
-| PostToolUse | After writing `.md` | Validates frontmatter + wikilinks, blocks misplaced memory files, flags notes crossing the 25KB organization threshold (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 vault-hygiene drift findings (same scan as SessionStart), shown once per session and again only when the findings change; hands drift to `om-tidy`. A Stop `systemMessage` reaches only the user, and every Stop output that reaches the agent is also printed in full for the user. So a changed report shows the user a one-line-per-section summary and saves the full report for the next prompt, where the UserPromptSubmit hook hands it to the agent unseen; the agent deals with the user's message first, then acts, asks, or leaves it. If the report cannot be saved, it goes out as Stop feedback instead. SessionEnd and a Stop without a session id show the full report. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |
-
-**On Claude Code 2.1.287+, the `obsidian-mind` mod** (`.claude/skills/obsidian-mind/`) delivers the SessionStart context as an instruction file instead: it runs `session-start.ts` itself and passes the settings hook `om_mod: "standdown"` for that event. The context then survives compaction whole and reaches general-purpose subagents (Explore and Plan skip instruction files by design); `/memory` shows it as `.claude/session-context.md`. It also presents the Stop report: it runs `stop-checklist.ts` with `om_mod: "report"`, stands the Stop hook down, draws one line under the answer when the findings changed, and hands you the full report with the user's next prompt (typed, over Remote Control, through the SDK or a Slack ping; a peer message, a notification or a scheduled prompt does not consume it), or with the mod's own prompt for an urgent finding, at most one per prompt the user sends. Wherever the mod does not load (Codex, Gemini, older Claude Code, an untrusted folder, a session started in a vault subfolder), the hooks above run unchanged.
-
-## Write-Correctness Laws
-
-Each law exists because its absence caused real correction work in vaults running this template. Violating them re-creates documented failures.
-
-1. **Single-source status.** A project's volatile status (version, counts, released/blocked, dates) lives in exactly ONE place — its note's frontmatter + top status line. Every other note **links** to it and never restates it. *Why: one wrong status statement hardened into ~8 notes downstream and had to be swept out.*
-2. **Correction-sweep protocol.** When a fact is corrected, find every restatement and fix them all in the same pass. **`/om-correct "<the corrected fact>"` is the acting half** — grep alone finds only the notes that copied the wording, and the expensive half is the *paraphrase*: the same claim in different words, invisible to grep and indistinguishable from correct prose to every structural check. It is also the half most likely to survive a manual sweep, because the sweeper stops when grep goes quiet. A correction callout on top of a note whose body still says the wrong thing is NOT a correction — future sessions re-absorb the stain from the body. Notes that correctly record what was believed *at the time* are preserved, never rewritten; see Law 5.
-3. **Mark inference.** Anything not verified against source (code, repo, primary doc, the person) carries an explicit `(TBC)` / `(unverified)` / `(inferred)` marker. Never state inference bare.
-4. **Date-stamp volatile facts.** Counts, versions, org structure, tool maturity: write "as of YYYY-MM-DD" so staleness is self-evident instead of silent.
-5. **Attribution vs. creation dates may differ** (a `quarter:` field vs. the `date:` field's quarter) — that's legitimate, not a bug to "fix".
-6. **No counts in instruction files.** Hardcoded counts ("11 slash commands") in CLAUDE.md/README rot silently — describe, don't count.
-
-## Rules
-
-- **For "what's most recent," use `bases/Recently Touched.base` (real modified time), never filename dates** — a creation-date prefix on a continuously-edited note inverts the recency signal.
-
-- Never modify `.obsidian/` config files unless explicitly asked.
-- Preserve existing frontmatter when editing notes.
-- Git sync is handled by the user's preferred method (obsidian-git, manual commits, etc.) -- don't configure git hooks or auto-commit.
-- When asked to "remember" something, write to the relevant `brain/` topic note with a link to context. Never create memory files in `~/.claude/` -- they are not git-tracked.
-- Prefer Obsidian CLI over filesystem when Obsidian is **already** running. On macOS, the first `obsidian` call launches the Electron app (visible window flash) if no instance is running — open Obsidian once at session start, then subsequent calls forward args silently. In non-interactive contexts where you can't guarantee Obsidian is open (background hooks, automation), prefer filesystem reads.
-- **Always invoke Obsidian skills via the Skill tool** before doing vault work. Load `obsidian-markdown` when creating/editing `.md` files. Load `obsidian-cli` when running vault commands. Load `obsidian-bases` or `json-canvas` when working with those file types.
-- Always check for and suggest connections between notes.
-- Every note must have a `description` field (~150 chars). Claude fills this automatically.
-- **Zero data loss**: when reorganizing, always use `git mv`. Never delete without explicit user confirmation.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9c2ec05..95690c9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -55,7 +55,7 @@ The route:
- **Code is separate.** If the ruling is "build it", the build is a new issue that the ruling unblocks. A ruling must not wait behind an implementation.
- **A ruling that cannot be made yet is a finding, not a failure.** If it needs a measurement or usage data nobody has, say so on the issue and record what would settle it. That is a complete answer, not a deferral.
-This is not a rule about when a decision earns a durable record. That gate lives in [CLAUDE.md](CLAUDE.md) under Decision Records and decides whether to write one at all. This is only about giving question-shaped issues a way through, so they stop masquerading as tasks.
+This is not a rule about when a decision earns a durable record. That gate lives in [AGENTS.md](AGENTS.md) under Decision Records and decides whether to write one at all. This is only about giving question-shaped issues a way through, so they stop masquerading as tasks.
## PR Title Format
@@ -71,7 +71,7 @@ type: short description
|--------|-------------|-----------|
| `feat` | New command, agent, hook, or capability | Added |
| `fix` | Bug fix | Fixed |
-| `docs` | Documentation only (README, translations, CLAUDE.md) | Changed |
+| `docs` | Documentation only (README, translations, AGENTS.md) | Changed |
| `refactor` | Code restructuring without behavior change | Changed |
| `chore` | Maintenance, cleanup | Changed |
| `build` | Build system or packaging changes | Changed |
@@ -99,7 +99,9 @@ When adding or modifying commands, agents, hooks, or vault structure, **all of t
| File | What to update |
|------|---------------|
-| `CLAUDE.md` | Command table, agent table, vault structure table, counts |
+| `AGENTS.md` | Vault structure table (no command table and no counts: Write-Correctness law 6) |
+| `.claude/rules/subagents.md` | Agent table |
+| `.claude/rules/hooks-per-agent.md`, `.claude/rules/hooks-and-mod.md` | Hook tables, when a hook or its event changes |
| `README.md` | Command table, agent table, vault structure diagram, counts |
| `README.ja.md`, `README.ko.md`, `README.zh-CN.md` | Same as README, in the respective language |
| `brain/Skills.md` | Command tables (by category), subagents table, workflows |
@@ -117,7 +119,7 @@ The release pipeline handles these automatically — **do not include in your PR
- [ ] PR title follows `type: description` format
- [ ] Counts match everywhere (commands, agents) if you added/removed any
-- [ ] New command/agent appears in ALL doc tables (CLAUDE.md + README + Skills.md)
+- [ ] New command/agent appears in ALL doc tables (README + Skills.md, and `.claude/rules/subagents.md` for an agent)
- [ ] Translations flagged if you changed README.md (maintainer can handle these)
- [ ] Tests pass: `cd .claude/scripts && npm test`
- [ ] Any NEW guard, check, or config constraint has [demonstrated a red](#new-guards-must-demonstrate-a-red), recorded in the PR
diff --git a/GEMINI.md b/GEMINI.md
deleted file mode 100644
index 646b549..0000000
--- a/GEMINI.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# Obsidian Mind
-
-This vault is built for [Claude Code](https://claude.ai/code) with a full operating manual in `CLAUDE.md`.
-
-**Read `CLAUDE.md` for all vault conventions** — structure, note types, linking rules, frontmatter schemas, indexes, and workflows. Most of the content is agent-agnostic.
-
-## Hooks
-
-The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell, executed natively by Node via `--experimental-strip-types` — no build step, no runtime dependencies, no Claude SDK. Hook configs are provided for three agents:
-
-| Agent | Config | Status |
-|-------|--------|--------|
-| Claude Code | `.claude/settings.json` | Full support |
-| Codex CLI | `.codex/hooks.json` | Shared hook scripts |
-| Gemini CLI | `.gemini/settings.json` | Shared hook scripts |
-
-| Script | Purpose | Claude event | Codex event | Gemini event |
-|--------|---------|--------------|-------------|--------------|
-| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
-| `classify-message.ts` | Classify messages, inject routing hints, hand over the last Stop report (Claude Code and Codex: Gemini's checklist runs on SessionEnd and saves none) | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
-| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
-| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
-
-## Commands
-
-Commands live in `.claude/commands/` — agent-agnostic markdown with YAML frontmatter. `brain/Skills.md` is the catalog.
-
-- **Claude Code / Gemini CLI**: invoke as `/om-standup`, `/om-dump`, etc.
-- **Codex CLI**: type the command name as a regular prompt without the `/` prefix (e.g. `om-standup`). Codex will find and execute the command file.
-
-## Memory
-
-The vault's memory lives in `brain/` — `Memories.md`, `Patterns.md`, `Key Decisions.md`, `Gotchas.md`. These are plain markdown files that any agent can read and write. When you learn something worth remembering, write it to the relevant `brain/` topic note with a wikilink to context.
-
-The `~/.claude/` auto-loaded memory index is Claude Code-specific — skip that section in `CLAUDE.md`. The vault-side `brain/` notes are the source of truth.
-
-## Reaching this vault from another repo
-
-The `om` MCP server (`.claude/scripts/om-mcp.mjs`) exposes this vault over MCP, so a session running in a **different repository** can search it, read notes, follow the graph, and record durable lessons back into it. It speaks plain MCP over stdio, so any MCP-capable agent can register it — nothing about it is Claude Code-specific.
-
-Register it in the *consuming* project's MCP config, pointing at this vault's absolute path, then add a short section to that project's own agent doc telling it the vault exists. **Both steps are required**: measured, a session with the server wired but no repo-side instruction made zero vault calls, because a prohibition propagates into a session reliably while a positive "go look" does not.
-
-Do not register the raw `qmd` server in a consuming repo — it searches every note directly, so the repo matches against memories written for unrelated projects. Applying each memory's declared scope on top of the index is what `om` adds. Full details in `CLAUDE.md`.
-
-## Subagents
-
-9 subagents in `.claude/agents/` handle isolated tasks (brag spotting, vault auditing, cross-linking, etc.). The prompt content is agent-agnostic markdown.
-
-- **Codex CLI**: as of the [Skills launch (Dec 2025)](https://developers.openai.com/codex/changelog), Codex discovers skills at `.agents/skills/<name>/SKILL.md` (directory-per-skill; frontmatter requires `name` and `description`). Mirror each `.claude/agents/*.md` into a `SKILL.md`, keeping the prompt body intact. See the [Codex Skills docs](https://developers.openai.com/codex/skills) for the full schema.
-- **Gemini CLI**: agents live in `.gemini/agents/`. Copy the files and adapt the YAML frontmatter fields to Gemini's schema.
-
-## What's Claude Code-specific
-
-Two things are Claude Code-specific: the `~/.claude/` auto-memory loader, and the `obsidian-mind` mod in `.claude/skills/obsidian-mind/`, which on Claude Code 2.1.287+ delivers the session context as an instruction file and presents the Stop report. Neither is needed elsewhere: the mod only changes how the settings hooks' output reaches a Claude Code session, and every other agent runs those same hooks directly. Everything else (hooks, commands, subagent prompts, vault memory) is portable.
-
-## Setup
-
-**Codex CLI**: Reads `AGENTS.md` natively. For direct access to `CLAUDE.md`, add to `~/.codex/config.toml`:
-```toml
-project_doc_fallback_filenames = ["CLAUDE.md"]
-```
-
-**Gemini CLI**: Reads `GEMINI.md` natively. For direct access to `CLAUDE.md`, add to `~/.gemini/settings.json`:
-```json
-{ "context": { "fileName": ["GEMINI.md", "CLAUDE.md"] } }
-```
-
-**Other agents** (Cursor, Windsurf, Copilot): Read `AGENTS.md` for vault conventions. Hook support varies by agent.
-
-For more information, see the [README](README.md).
diff --git a/README.md b/README.md
index 9fbc5ad..d4d003f 100644
--- a/README.md
+++ b/README.md
@@ -127,7 +127,7 @@ Or use it as a **GitHub template**. Skip the wizard, get the bare template. Then
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.** Claude is instructed (via `CLAUDE.md`) to consult `brain/` guidance through QMD when the conversation touches a listed topic.
+- **Brain topics available on demand.** Your agent is instructed (via `AGENTS.md`, which points to `.claude/rules/brain-topics.md`) to consult `brain/` 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](https://modelcontextprotocol.io) server in `.mcp.json` — when QMD is installed, `mcp__qmd__query`, `mcp__qmd__get`, and `mcp__qmd__multi_get` appear 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.
@@ -193,11 +193,11 @@ The `om` server sends a lexical *and* a vector sub-query, so retrieval finds the
**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 `CLAUDE.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.
+**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
-Five lifecycle hooks handle routing automatically:
+The lifecycle hooks handle routing automatically:
| Hook | When | What |
|------|------|------|
@@ -214,7 +214,7 @@ Five lifecycle hooks handle routing automatically:
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 `CLAUDE.md` does. 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 is `eager_layer_instruction_budget_bytes` in `vault-manifest.json`; sections that never shrink, such as open tasks, can still take it past that. `/memory` lists it as `.claude/session-context.md`.
+- **Session context arrives as an instruction file**, the way `AGENTS.md` does. 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 is `eager_layer_instruction_budget_bytes` in `vault-manifest.json`; sections that never shrink, such as open tasks, can still take it past that. `/memory` lists it as `.claude/session-context.md`.
- **The Stop report becomes one line under the answer.** When the findings change you see `obsidian-mind: vault check: …` beneath Claude's reply, and 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.
@@ -236,7 +236,7 @@ obsidian-mind does **not** dump your entire vault into context. It uses tiered l
| Tier | What | When | Cost |
|------|------|------|------|
-| **Always** | `CLAUDE.md` + 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 |
+| **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 |
@@ -246,18 +246,30 @@ SessionStart loads **lightweight context** — small excerpts from key files, fi
### 🌐 Using with Other Agents
-obsidian-mind works with Claude Code, Codex CLI, and Gemini CLI. The vault conventions in `CLAUDE.md`, the hook scripts in `.claude/scripts/`, and the commands in `.claude/commands/` are all agent-agnostic — pure Markdown, TypeScript, and shell with no SDK dependencies.
+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](#-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](#-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](#-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](https://github.com/breferrari/obsidian-mind/issues/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** — reads `AGENTS.md` natively. 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 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).
+
+**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 CLI** — reads `GEMINI.md` natively. Hook config at `.gemini/settings.json` maps Gemini's event names to the shared hook scripts.
+**Antigravity** and **Grok** — read `AGENTS.md` for vault conventions. Their hook, skill and command layers are tracked in [#322](https://github.com/breferrari/obsidian-mind/issues/322) and [#323](https://github.com/breferrari/obsidian-mind/issues/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 is Claude Code-specific. See `AGENTS.md` for the full portability guide.
+> Hooks, commands, subagent prompts, and vault memory (`brain/`) are all agent-agnostic. Only the `~/.claude/` auto-memory loader and the `obsidian-mind` mod are Claude Code-specific. `.claude/rules/hooks-per-agent.md` maps each hook to each agent's event.
---
@@ -296,7 +308,7 @@ Note the cost: that path is **absolute and machine-specific**, so committing it
### Step 2 — point the consuming project at the vault
-Add this to that project's own `CLAUDE.md`, filling in the triggers:
+Add this to that project's own instruction file (`CLAUDE.md` or `AGENTS.md`), filling in the triggers:
```markdown
## Where design decisions live
@@ -491,9 +503,7 @@ The `bases/` folder contains database views that query your notes' frontmatter p
```
Home.md Vault entry point — embedded Base views, quick links
-CLAUDE.md Operating manual — read by your agent every session
-AGENTS.md Multi-agent guide — Codex, Cursor, Windsurf, etc.
-GEMINI.md Multi-agent guide — Gemini CLI
+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
@@ -535,8 +545,9 @@ thinking/ Scratchpad for drafts — promote findings, then delete
templates/ Obsidian templates with YAML frontmatter
.claude/
- commands/ 18 slash commands
- agents/ 9 subagents
+ 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
@@ -595,11 +606,11 @@ This is a starting point. Adapt it to how you work:
| 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 | `CLAUDE.md` — the operating manual, evolve it as you go |
+| 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]
-> `CLAUDE.md` is the operating manual. When you change conventions, update it — your agent reads it every session.
+> `AGENTS.md` is the operating manual. When you change conventions, update it — your agent reads it every session.
---
@@ -624,7 +635,7 @@ cd your-vault
git pull origin main
```
-New files (`AGENTS.md`, `GEMINI.md`, `.codex/`, `.gemini/`) appear automatically and hook scripts are updated in place.
+New 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](#-troubleshooting) describes, then delete it.
### Updating a fork
@@ -636,7 +647,7 @@ git fetch upstream
git merge upstream/main
```
-Resolve any conflicts in files you customized (typically `CLAUDE.md`, `brain/` notes). Infrastructure files (`.claude/scripts/`, `.codex/`, `.gemini/`) should merge cleanly.
+Resolve any conflicts in files you customized (typically `AGENTS.md`, `brain/` notes; a `CLAUDE.md` you edited conflicts with its deletion, see [Troubleshooting](#-troubleshooting)). Infrastructure files (`.claude/scripts/`, `.codex/`, `.gemini/`) should merge cleanly.
### Adopting an existing clone into ShardMind (v5.x → v6)
@@ -678,6 +689,21 @@ Your old vault is **never modified**. Use `--dry-run` to preview the plan withou
---
+## 🩺 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.md` in the vault.** An update keeps a `CLAUDE.md` you edited. The session hygiene flags say `CLAUDE.md present beside AGENTS.md`, and `/om-vault-upgrade` lists it under **Move out**. Move what you added to `.claude/rules/local.md` (or into `AGENTS.md` if every agent needs it, keeping `AGENTS.md` under 23 KB, where the hygiene flags start: Antigravity stops reading it at ~24,000 bytes), then delete `CLAUDE.md`. Nothing is merged automatically.
+- **A `CLAUDE.md` in a folder above the vault.** Claude Code reads that one too, and `AGENTS.md` is 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
**Contributions welcome.** Open an issue first for anything bigger than a one-file change. Especially anything that touches the hooks, the install, or what people need installed. Saves you from building something that can't be merged.
diff --git a/brain/Skills.md b/brain/Skills.md
index 58755a5..7b73dca 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -8,7 +8,7 @@ tags:
# Skills
-Custom slash commands, subagents, and reusable workflows. Defined in `.claude/commands/` and `.claude/agents/`. **This note is the canonical command catalog** for agents that don't get the in-session skills injection (Codex, Gemini, Cursor) — keep it current when commands change; CLAUDE.md deliberately carries no command table.
+Custom slash commands, subagents, and reusable workflows. Defined in `.claude/commands/` and `.claude/agents/`. **This note is the canonical command catalog** for agents that don't get the in-session skills injection (Codex, Gemini, Cursor) — keep it current when commands change; AGENTS.md deliberately carries no command table.
## Slash Commands
@@ -141,7 +141,7 @@ Two prompts you invoke yourself from the `/` menu: `recall_topic`, `prior_art`.
**Two guards worth knowing:** memories are never served as ordinary notes (they carry their own declared scope), and a memory that would reach nobody is refused rather than silently widened to `general`.
-Full setup, which notes the server serves, and the required repo-side snippet: `CLAUDE.md` § *Reaching the Vault From Another Repo*. How the whole layer works — the four MCP surfaces, the identity handshake, a `search` call end to end, memory-visibility evaluation, the write path: `ARCHITECTURE.md` § *Reaching the Vault From Another Repo*.
+Full setup, which notes the server serves, and the required repo-side snippet: `.claude/rules/vault-from-another-repo.md`. How the whole layer works — the four MCP surfaces, the identity handshake, a `search` call end to end, memory-visibility evaluation, the write path: `ARCHITECTURE.md` § *Reaching the Vault From Another Repo*.
## Workflow: Weekly Review
diff --git a/vault-manifest.json b/vault-manifest.json
index 67efd15..0b3f395 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -22,9 +22,7 @@
"mcp_inbox": "inbox",
"qmd_context": "Engineer's work vault built on obsidian-mind. Active projects and archive, 1:1 notes, incidents, brag log with quarterly evidence, competency map, people and teams, decisions and patterns in brain/, reference docs and runbooks. Multi-agent (Claude Code, Codex, Gemini) with lifecycle hooks and QMD semantic search. Ground for 'what did I ship?' reviews, project status, and personal knowledge management.",
"infrastructure": [
- "CLAUDE.md",
"AGENTS.md",
- "GEMINI.md",
"Home.md",
"README.md",
"README.*.md",
@@ -235,6 +233,16 @@
"v9.1": {
"exists": [
".claude/scripts/upgrade-plan.ts"
+ ],
+ "missing": [
+ ".claude/rules/skills.md"
+ ]
+ },
+ "v10.0": {
+ "exists": [
+ ".claude/rules/skills.md",
+ ".claude/rules/hooks-and-mod.md",
+ "AGENTS.md"
]
}
},