Skip to content

Fastest way to scaffold your LLM powered personal knowledge base - Obsidian, Claude Code, qmd, Github

feat: CLI path/qmd subcommands, skill versioning, config rename

jessepinkman990037ff7f4d5355
diff --git a/.claude/skills/pack-test/SKILL.md b/.claude/skills/pack-test/SKILL.md
index 25c841f..b37b494 100644
--- a/.claude/skills/pack-test/SKILL.md
+++ b/.claude/skills/pack-test/SKILL.md
@@ -1,109 +1,205 @@
---
name: pack-test
-description: "Test the claude-second-brain npm package by packing it into a tarball and running it via npx. This is the definitive test — it catches npm's .gitignore stripping behavior and validates the full scaffold. Trigger phrases: /pack-test, test the package, test the CLI, test the tarball."
+description: "Test the claude-second-brain npm package by packing it into a tarball and running it via npx. Exercises the full multi-brain scaffold flow end-to-end: scaffolds a brain, verifies config.toml, global skills, and local patches, then scaffolds a second brain to validate config upsert. Trigger phrases: /pack-test, test the package, test the CLI, test the tarball."
argument-hint: "No arguments needed"
---
# Pack Test
-Tests the npm package as it behaves when published. Uses `npx` to run from the local tarball — `pnpm dlx` doesn't support local tarball paths (it tries to resolve them as scoped package names). After publishing, `pnpm dlx claude-second-brain` from the registry works fine. Runs all steps, reports a checklist, then cleans up.
+Tests the npm package as it behaves when published. Uses `npx` to run from the local tarball — `pnpm dlx` doesn't support local tarball paths (it tries to resolve them as scoped package names). After publishing, `pnpm dlx claude-second-brain` from the registry works fine.
+
+Multi-brain architecture: brains live at `~/.claude-second-brain/<name>/` and are registered in `~/.claude-second-brain/config.toml`. Global skills (`~/.claude/skills/brain-*`) are plain SKILL.md files with a sibling `.csb-version` sidecar. They resolve paths at call time via the `claude-second-brain path` and `claude-second-brain qmd` subcommands — no paths are baked into the skills themselves.
+
+**Important:** This test mutates `~/.claude-second-brain/` and `~/.claude/skills/brain-*`. If the user has real brains registered, warn them before running — cleanup removes `config.toml` and the test brains, which does NOT delete their real brain folders but DOES remove their registry entries and overwrite their global skills.
## Steps
-Run each command in order. Stop and report if any step fails.
+Run each step in order. Stop and report if any step fails.
+
+### Step 1 — Pre-flight: back up existing state
+
+```bash
+# If the user has existing brains, these are affected:
+ls -la ~/.claude-second-brain/ 2>/dev/null || echo "(no existing brains)"
+cat ~/.claude-second-brain/config.toml 2>/dev/null || echo "(no existing config)"
+```
+
+If `config.toml` exists with real brains, back it up so the test cleanup doesn't lose them:
+
+```bash
+cp ~/.claude-second-brain/config.toml ~/.claude-second-brain/config.toml.bak 2>/dev/null || true
+```
-**Step 1 — Pack**
+### Step 2 — Pack
```bash
npm pack
```
-Produces `claude-second-brain-<version>.tgz` in the repo root, where `<version>` comes from `package.json`. Verify the tarball appears before continuing.
+Produces `claude-second-brain-<version>.tgz` in the repo root. Verify the tarball appears before continuing.
-**Step 2 — Scaffold via npx**
+### Step 3 — Scaffold first brain
```bash
-npx -y claude-second-brain-$(node -p "require('./package.json').version").tgz test-vault
+npx -y claude-second-brain-$(node -p "require('./package.json').version").tgz test-brain-a
```
-Use `npx` to run from the local tarball — `pnpm dlx` doesn't support local tarball paths. Pass `test-vault` as the target dir argument to skip the interactive folder name prompt. When stdin is not a TTY (non-interactive), the CLI automatically uses defaults for the qmd path (`~/.cache/qmd/index.sqlite`) and skips the GitHub repo prompt. No `printf` pipe needed. The vault is created in the repo root and cleaned up in Step 4.
+Pass `test-brain-a` as the brain name argument to skip the interactive prompt. Non-TTY stdin skips the GitHub prompt. The brain is created at `~/.claude-second-brain/test-brain-a/`.
-**Step 3 — Verify checklist**
+**Assertion:** The CLI output should include `cd ~/.claude-second-brain/test-brain-a` in the Next steps section — not `cd test-brain-a`.
-Run each of the following and confirm the expected output:
+### Step 4 — Verify single-brain scaffold
```bash
-# Root structure
-ls -la test-vault/
+VAULT_A=~/.claude-second-brain/test-brain-a
-# .gitignore must exist (not .gitignore.template — npm strips .gitignore from packages)
-cat test-vault/.gitignore
+# Brain is in the correct location (NOT in CWD)
+[ -d "$VAULT_A" ] && echo "PASS: brain at $VAULT_A" || echo "FAIL: brain not at $VAULT_A"
+[ ! -d "./test-brain-a" ] && echo "PASS: brain not in CWD" || echo "FAIL: brain leaked into CWD"
-# Wiki stubs
-ls test-vault/wiki/
+# .gitignore renamed from .gitignore.template
+[ -f "$VAULT_A/.gitignore" ] && echo "PASS: .gitignore present" || echo "FAIL: .gitignore missing"
-# Raw sources dirs
-ls test-vault/raw-sources/
+# Wiki stubs, raw-sources dirs, local skills, scripts
+ls $VAULT_A/wiki/ $VAULT_A/raw-sources/ $VAULT_A/.claude/skills/ $VAULT_A/scripts/qmd/
-# Claude Code skills (expect: brain-ingest, brain-search, brain-refresh, brain-rebuild, lint, qmd-cli, setup)
-ls test-vault/.claude/skills/
+# Scripts use a relative .qmd path — no absolute path substitution
+grep "\.qmd/index\.sqlite" $VAULT_A/scripts/qmd/setup.ts
+grep "\.qmd/index\.sqlite" $VAULT_A/scripts/qmd/reindex.ts
-# qmd scripts
-ls test-vault/scripts/qmd/
+# CLAUDE.md references the relative path too
+grep "INDEX_PATH=\.qmd/index\.sqlite" $VAULT_A/CLAUDE.md | head -1
-# INDEX_PATH in CLAUDE.md must be an absolute path, not relative "qmd.sqlite"
-grep "INDEX_PATH=" test-vault/CLAUDE.md
+# No lingering tokens anywhere in the vault
+! grep -r "__QMD_PATH__\|__CSB_CONFIG__\|__BRAIN_NAME__" $VAULT_A/ 2>/dev/null \
+ && echo "PASS: no unpatched tokens" \
+ || echo "FAIL: unpatched tokens found above"
+```
+
+### Step 5 — Verify config.toml was created
-# setup.ts DB must be a hardcoded absolute path, not join(VAULT, "qmd.sqlite")
-grep "const DB" test-vault/scripts/qmd/setup.ts
+```bash
+CONFIG=~/.claude-second-brain/config.toml
-# Global skills must be installed
-ls ~/.claude/skills/brain-ingest/
-ls ~/.claude/skills/brain-search/
-ls ~/.claude/skills/brain-refresh/
+[ -f "$CONFIG" ] && echo "PASS: config.toml created" || echo "FAIL: config.toml missing"
+cat $CONFIG
-# Global skill content must have the absolute INDEX_PATH
-grep "INDEX_PATH=" ~/.claude/skills/brain-ingest/SKILL.md
-grep "INDEX_PATH=" ~/.claude/skills/brain-refresh/SKILL.md
+# Assertions on content
+grep -q 'default = "test-brain-a"' $CONFIG && echo "PASS: default brain set" || echo "FAIL: default not set"
+grep -q 'name = "test-brain-a"' $CONFIG && echo "PASS: brain entry exists" || echo "FAIL: no brain entry"
+grep -q "path = \"$HOME/.claude-second-brain/test-brain-a\"" $CONFIG && echo "PASS: path correct" || echo "FAIL: path wrong"
+grep -q "qmd_index = \"$HOME/.claude-second-brain/test-brain-a/.qmd/index.sqlite\"" $CONFIG && echo "PASS: qmd_index correct" || echo "FAIL: qmd_index wrong"
```
-Report results against this checklist:
+### Step 6 — Verify global skills are CLI-backed
+
+```bash
+for skill in brain-ingest brain-search brain-refresh; do
+ FILE=~/.claude/skills/$skill/SKILL.md
+ SIDECAR=~/.claude/skills/$skill/.csb-version
+ [ -f "$FILE" ] || { echo "FAIL: $FILE missing"; continue; }
+
+ # Must reference the `claude-second-brain` CLI for path / qmd resolution
+ grep -q "claude-second-brain path" $FILE && echo "PASS: $skill uses \`claude-second-brain path\`" || echo "FAIL: $skill missing CLI path resolution"
+ grep -q "claude-second-brain qmd" $FILE && echo "PASS: $skill uses \`claude-second-brain qmd\`" || echo "FAIL: $skill missing CLI qmd proxy"
+
+ # No lingering tokens, no baked absolute paths
+ ! grep -q "__QMD_PATH__\|__CSB_CONFIG__\|INDEX_PATH=\$QMD_INDEX\|INDEX_PATH=/" $FILE && echo "PASS: $skill clean" || echo "FAIL: $skill still has legacy substitutions"
+
+ # Version sidecar exists and matches package version
+ [ -f "$SIDECAR" ] && echo "PASS: $skill .csb-version present" || echo "FAIL: $skill missing .csb-version"
+ PKG_VER=$(node -p "require('./package.json').version")
+ grep -q "\"version\": \"$PKG_VER\"" $SIDECAR && echo "PASS: $skill version matches package" || echo "FAIL: $skill version mismatch"
+done
+```
+
+### Step 7 — Scaffold second brain (multi-brain upsert test)
+
+```bash
+npx -y claude-second-brain-$(node -p "require('./package.json').version").tgz test-brain-b
+```
+
+### Step 8 — Verify config.toml upsert
+
+```bash
+CONFIG=~/.claude-second-brain/config.toml
+cat $CONFIG
+
+# default should STILL be test-brain-a (first brain stays default)
+grep -q 'default = "test-brain-a"' $CONFIG && echo "PASS: default unchanged" || echo "FAIL: default was overwritten"
+
+# Both brains should be registered
+grep -c '^\[\[brains\]\]' $CONFIG
+[ "$(grep -c '^\[\[brains\]\]' $CONFIG)" = "2" ] && echo "PASS: 2 brains registered" || echo "FAIL: expected 2 brain entries"
+
+grep -q 'name = "test-brain-a"' $CONFIG && echo "PASS: brain-a entry exists" || echo "FAIL: brain-a missing"
+grep -q 'name = "test-brain-b"' $CONFIG && echo "PASS: brain-b entry exists" || echo "FAIL: brain-b missing"
+```
+
+### Step 9 — Verify CLI subcommands resolve the default brain
+
+```bash
+RESOLVED_ROOT=$(npx -y claude-second-brain-$(node -p "require('./package.json').version").tgz path)
+[ "$RESOLVED_ROOT" = "$HOME/.claude-second-brain/test-brain-a" ] && echo "PASS: path resolves default brain" || echo "FAIL: path returned '$RESOLVED_ROOT'"
+
+RESOLVED_QMD=$(npx -y claude-second-brain-$(node -p "require('./package.json').version").tgz path --qmd)
+[ "$RESOLVED_QMD" = "$HOME/.claude-second-brain/test-brain-a/.qmd/index.sqlite" ] && echo "PASS: path --qmd resolves default brain" || echo "FAIL: path --qmd returned '$RESOLVED_QMD'"
+
+RESOLVED_B=$(npx -y claude-second-brain-$(node -p "require('./package.json').version").tgz path --brain test-brain-b)
+[ "$RESOLVED_B" = "$HOME/.claude-second-brain/test-brain-b" ] && echo "PASS: --brain overrides default" || echo "FAIL: --brain returned '$RESOLVED_B'"
+```
+
+### Step 10 — Final checklist
| Item | Expected | Pass? |
-|------|----------|-------|
-| `.gitignore` | Present (not `.gitignore.template`) | |
-| `wiki/index.md`, `log.md`, `overview.md` | All present | |
-| `wiki/sources/` and `wiki/qa/` | Present | |
-| `raw-sources/articles/`, `pdfs/`, `personal/` | Present | |
+|---|---|---|
+| `~/.claude-second-brain/test-brain-a/` | Present | |
+| `~/.claude-second-brain/test-brain-b/` | Present | |
+| Brain NOT leaked into CWD | `./test-brain-a` does not exist | |
+| `.gitignore` (not `.gitignore.template`) | Present in both brains | |
+| `wiki/{index,log,overview}.md`, `sources/`, `qa/` | Present in both brains | |
+| `raw-sources/{articles,pdfs,personal}/` | Present in both brains | |
| `.claude/skills/` — 7 subdirs | brain-ingest, brain-search, brain-refresh, brain-rebuild, lint, qmd-cli, setup | |
-| `scripts/qmd/setup.ts`, `reindex.ts` | All present | |
-| `package.json` (vault root) | Present with `pnpm` packageManager | |
-| `CLAUDE.md`, `mise.toml` | Present | |
-| `CLAUDE.md` INDEX_PATH | Absolute path (not `qmd.sqlite`) | |
-| `scripts/qmd/setup.ts` DB const | Hardcoded absolute path (not `join(VAULT, ...)`) | |
-| `~/.claude/skills/brain-ingest/SKILL.md` | Present with absolute INDEX_PATH | |
-| `~/.claude/skills/brain-search/SKILL.md` | Present with absolute INDEX_PATH | |
-| `~/.claude/skills/brain-refresh/SKILL.md` | Present with absolute INDEX_PATH | |
+| `scripts/qmd/{setup,reindex}.ts` | Present in both brains, DB hardcoded to `.qmd/index.sqlite` relative | |
+| `CLAUDE.md`, `mise.toml`, `package.json` | Present in both brains | |
+| `CLAUDE.md` INDEX_PATH | Relative `INDEX_PATH=.qmd/index.sqlite` (no absolute substitution) | |
+| No unpatched tokens | No `__QMD_PATH__`, `__CSB_CONFIG__`, `__BRAIN_NAME__` anywhere in vault | |
+| `~/.claude-second-brain/config.toml` | Present with `default = "test-brain-a"` and 2 `[[brains]]` entries | |
+| Global skills (`~/.claude/skills/brain-{ingest,search,refresh}/SKILL.md`) | Present; reference `claude-second-brain path` + `claude-second-brain qmd`; `.csb-version` sidecar matches package version | |
-**Step 4 — Clean up**
+### Step 11 — Clean up
```bash
-rm -rf test-vault
+rm -rf ~/.claude-second-brain/test-brain-a
+rm -rf ~/.claude-second-brain/test-brain-b
+rm -f ~/.claude-second-brain/config.toml
+rm -rf ~/.claude/skills/brain-ingest ~/.claude/skills/brain-search ~/.claude/skills/brain-refresh
rm claude-second-brain-$(node -p "require('./package.json').version").tgz
-rm -rf ~/.claude/skills/brain-ingest
-rm -rf ~/.claude/skills/brain-search
-rm -rf ~/.claude/skills/brain-refresh
-gh repo delete test-vault --yes
+
+# Restore backed-up config if it existed
+[ -f ~/.claude-second-brain/config.toml.bak ] && mv ~/.claude-second-brain/config.toml.bak ~/.claude-second-brain/config.toml
+
+# Remove the parent dir only if empty
+rmdir ~/.claude-second-brain/ 2>/dev/null || true
+
+# Clean up GitHub test repos (if any were created — normally no, since non-TTY skips the prompt)
+gh repo delete test-brain-a --yes 2>/dev/null || true
+gh repo delete test-brain-b --yes 2>/dev/null || true
```
-> **Note:** If you had pre-existing `brain-ingest` / `brain-search` / `brain-refresh` global skills from a real vault, they were overwritten by this test. Re-run `/setup` inside your real vault to restore them.
+> **Note:** If the user had pre-existing `brain-ingest` / `brain-search` / `brain-refresh` global skills from a real vault, they were overwritten by this test. They need to re-run `npx claude-second-brain` or manually re-scaffold a brain to restore them. The config backup in Step 1 protects their brain registry but not their global skills.
## What failure means
- **`.gitignore.template` present instead of `.gitignore`** — npm stripped `.gitignore` from the tarball but the rename in `bin/create.js` didn't fire; check the `try/catch` rename block
+- **Brain leaked into CWD** — `targetDir` in `main()` still uses `process.cwd()`; check `bin/create.js` uses `join(CSB_ROOT, targetName)`
- **Missing skill dirs** — template copy failed or `.claude/` hidden dir wasn't included; check `npm pack --dry-run` output
- **`npx` fails to run the bin** — shebang or `bin` field in `package.json` is wrong; check `#!/usr/bin/env node` on line 1 of `bin/create.js`
-- **`qmd.sqlite` still in CLAUDE.md or skill files** — `patchVault()` didn't run (CLI exited early, often due to a non-TTY prompt hanging) or the replaceAll target string didn't match; check the `isInteractive` guard in `bin/create.js` and the patch target strings
-- **Global skills not installed** — `installGlobalSkills()` failed; check that `~/.claude/skills/` is writable and template skill dirs are named `brain-ingest`/`brain-search`
-- **`join(VAULT, ...)` still in setup.ts** — the DB line patch didn't match; verify the exact string `const DB = join(VAULT, "qmd.sqlite")` exists in the template
+- **`__QMD_PATH__` or `__CSB_CONFIG__` still in any file** — those substitutions were removed; any hit means a template file still has a legacy placeholder that should be replaced with a relative path or CLI invocation
+- **Global skills still reference `$QMD_INDEX`** — the old Brain Discovery preamble wasn't dropped; regenerate from the new `template/.claude/skills/brain-*/SKILL.md` sources
+- **`.csb-version` missing** — `installGlobalSkills()` didn't write the sidecar; check the sidecar write in `bin/create.js`
+- **`config.toml` missing** — `writeConfig()` not called or failed; check the call at the end of `main()`
+- **`default` changed after second brain was created** — `writeConfig()` upsert logic is overwriting `default`; it should only set `default` when the config file doesn't exist yet
+- **Only one `[[brains]]` entry after second scaffold** — `writeConfig()` upsert is replacing instead of appending; check the split/filter/join logic
+- **`claude-second-brain path` returns wrong brain** — `parseConfig` regex failing to pick up `default = …` (or legacy `active = …`); inspect the regex
- **Note:** `pnpm dlx` cannot run local tarballs — use `npx` for this test. After publishing, `pnpm dlx claude-second-brain` from the registry works fine.
diff --git a/.github/workflows/pack-test.yml b/.github/workflows/pack-test.yml
index 06abafa..94ec7c5 100644
--- a/.github/workflows/pack-test.yml
+++ b/.github/workflows/pack-test.yml
@@ -46,30 +46,35 @@ jobs:
fi
}
- check ".gitignore (not .gitignore.template)" test-vault/.gitignore
- check "wiki/index.md" test-vault/wiki/index.md
- check "wiki/log.md" test-vault/wiki/log.md
- check "wiki/overview.md" test-vault/wiki/overview.md
- check "wiki/sources/" test-vault/wiki/sources
- check "wiki/qa/" test-vault/wiki/qa
- check "raw-sources/articles/" test-vault/raw-sources/articles
- check "raw-sources/pdfs/" test-vault/raw-sources/pdfs
- check "raw-sources/personal/" test-vault/raw-sources/personal
- check ".claude/skills/setup" test-vault/.claude/skills/setup
- check ".claude/skills/brain-ingest" test-vault/.claude/skills/brain-ingest
- check ".claude/skills/brain-search" test-vault/.claude/skills/brain-search
- check ".claude/skills/brain-refresh" test-vault/.claude/skills/brain-refresh
- check ".claude/skills/brain-rebuild" test-vault/.claude/skills/brain-rebuild
- check ".claude/skills/lint" test-vault/.claude/skills/lint
- check ".claude/skills/qmd-cli" test-vault/.claude/skills/qmd-cli
- check "scripts/qmd/setup.ts" test-vault/scripts/qmd/setup.ts
- check "scripts/qmd/reindex.ts" test-vault/scripts/qmd/reindex.ts
- check "package.json" test-vault/package.json
- check "CLAUDE.md" test-vault/CLAUDE.md
- check "mise.toml" test-vault/mise.toml
- check "~/.claude/skills/brain-ingest/SKILL.md" "$HOME/.claude/skills/brain-ingest/SKILL.md"
- check "~/.claude/skills/brain-search/SKILL.md" "$HOME/.claude/skills/brain-search/SKILL.md"
- check "~/.claude/skills/brain-refresh/SKILL.md" "$HOME/.claude/skills/brain-refresh/SKILL.md"
+ VAULT="$HOME/.claude-second-brain/test-vault"
+ check ".gitignore (not .gitignore.template)" "$VAULT/.gitignore"
+ check "wiki/index.md" "$VAULT/wiki/index.md"
+ check "wiki/log.md" "$VAULT/wiki/log.md"
+ check "wiki/overview.md" "$VAULT/wiki/overview.md"
+ check "wiki/sources/" "$VAULT/wiki/sources"
+ check "wiki/qa/" "$VAULT/wiki/qa"
+ check "raw-sources/articles/" "$VAULT/raw-sources/articles"
+ check "raw-sources/pdfs/" "$VAULT/raw-sources/pdfs"
+ check "raw-sources/personal/" "$VAULT/raw-sources/personal"
+ check ".claude/skills/setup" "$VAULT/.claude/skills/setup"
+ check ".claude/skills/brain-ingest" "$VAULT/.claude/skills/brain-ingest"
+ check ".claude/skills/brain-search" "$VAULT/.claude/skills/brain-search"
+ check ".claude/skills/brain-refresh" "$VAULT/.claude/skills/brain-refresh"
+ check ".claude/skills/brain-rebuild" "$VAULT/.claude/skills/brain-rebuild"
+ check ".claude/skills/lint" "$VAULT/.claude/skills/lint"
+ check ".claude/skills/qmd-cli" "$VAULT/.claude/skills/qmd-cli"
+ check "scripts/qmd/setup.ts" "$VAULT/scripts/qmd/setup.ts"
+ check "scripts/qmd/reindex.ts" "$VAULT/scripts/qmd/reindex.ts"
+ check "package.json" "$VAULT/package.json"
+ check "CLAUDE.md" "$VAULT/CLAUDE.md"
+ check "mise.toml" "$VAULT/mise.toml"
+ check "~/.claude-second-brain/config.toml" "$HOME/.claude-second-brain/config.toml"
+ check "~/.claude/skills/brain-ingest/SKILL.md" "$HOME/.claude/skills/brain-ingest/SKILL.md"
+ check "~/.claude/skills/brain-search/SKILL.md" "$HOME/.claude/skills/brain-search/SKILL.md"
+ check "~/.claude/skills/brain-refresh/SKILL.md" "$HOME/.claude/skills/brain-refresh/SKILL.md"
+ check "~/.claude/skills/brain-ingest/.csb-version" "$HOME/.claude/skills/brain-ingest/.csb-version"
+ check "~/.claude/skills/brain-search/.csb-version" "$HOME/.claude/skills/brain-search/.csb-version"
+ check "~/.claude/skills/brain-refresh/.csb-version" "$HOME/.claude/skills/brain-refresh/.csb-version"
grep_check() {
local label="$1"
@@ -83,11 +88,27 @@ jobs:
fi
}
- grep_check "CLAUDE.md INDEX_PATH is absolute" "INDEX_PATH=/" test-vault/CLAUDE.md
- grep_check "setup.ts DB is hardcoded absolute path" 'const DB = "/' test-vault/scripts/qmd/setup.ts
- grep_check "global brain-ingest INDEX_PATH is absolute" "INDEX_PATH=/" "$HOME/.claude/skills/brain-ingest/SKILL.md"
- grep_check "global brain-search INDEX_PATH is absolute" "INDEX_PATH=/" "$HOME/.claude/skills/brain-search/SKILL.md"
- grep_check "global brain-refresh INDEX_PATH is absolute" "INDEX_PATH=/" "$HOME/.claude/skills/brain-refresh/SKILL.md"
+ absent_check() {
+ local label="$1"
+ local pattern="$2"
+ local file="$3"
+ if grep -q "$pattern" "$file" 2>/dev/null; then
+ echo "FAIL: $label — pattern '$pattern' should be absent from $file"
+ fail=1
+ else
+ echo "PASS: $label"
+ fi
+ }
+
+ grep_check "CLAUDE.md uses relative INDEX_PATH" 'INDEX_PATH=\.qmd/index\.sqlite' "$VAULT/CLAUDE.md"
+ grep_check "setup.ts DB uses relative .qmd path" '\.qmd.*index\.sqlite' "$VAULT/scripts/qmd/setup.ts"
+ grep_check "config.toml uses `default` field" '^default = ' "$HOME/.claude-second-brain/config.toml"
+ for skill in brain-ingest brain-search brain-refresh; do
+ grep_check "global $skill uses claude-second-brain path" 'claude-second-brain path' "$HOME/.claude/skills/$skill/SKILL.md"
+ grep_check "global $skill uses claude-second-brain qmd" 'claude-second-brain qmd' "$HOME/.claude/skills/$skill/SKILL.md"
+ absent_check "global $skill has no legacy QMD_INDEX" 'INDEX_PATH=\$QMD_INDEX' "$HOME/.claude/skills/$skill/SKILL.md"
+ absent_check "global $skill has no unpatched tokens" '__QMD_PATH__\|__CSB_CONFIG__' "$HOME/.claude/skills/$skill/SKILL.md"
+ done
if [ "$fail" -ne 0 ]; then
echo ""
@@ -101,7 +122,8 @@ jobs:
- name: Clean up
if: always()
run: |
- rm -rf test-vault
+ rm -rf "$HOME/.claude-second-brain/test-vault"
+ rm -f "$HOME/.claude-second-brain/config.toml"
VERSION=$(node -p "require('./package.json').version")
rm -f "claude-second-brain-${VERSION}.tgz"
gh repo delete test-vault --yes 2>/dev/null || true
diff --git a/CLAUDE.md b/CLAUDE.md
index c2efbd1..acd2d13 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -240,12 +240,14 @@ Whenever you **add, remove, or rename a skill** under `template/.claude/skills/`
1. **`README.md`** (root) — the "Claude Code skills included" section and the "Installing and updating skills" block. Bump the skill count ("N wiki skills") in the install commands.
2. **`template/README.md`** — the "Your Claude Code skills" section and the "Installing and updating skills" block. Bump the skill count.
-3. **`bin/create.js`** — the skill-name array inside `installGlobalSkills()` if the skill should be installed globally (`~/.claude/skills/`). `brain-ingest`, `brain-search`, `brain-refresh` are global today; `brain-rebuild`, `lint`, `setup`, `qmd-cli` are vault-local.
-4. **`.github/workflows/pack-test.yml`** — add a `check` line for the new vault-local skill directory, and if the skill is global, add a `check` line for `$HOME/.claude/skills/<name>/SKILL.md` plus a `grep_check` for `INDEX_PATH=/`.
+3. **`bin/create.js`** — the `GLOBAL_SKILLS` array (top of the file) if the skill should be installed globally (`~/.claude/skills/`). `brain-ingest`, `brain-search`, `brain-refresh` are global today; `brain-rebuild`, `lint`, `setup`, `qmd-cli` are vault-local.
+4. **`.github/workflows/pack-test.yml`** — add a `check` line for the new vault-local skill directory, and if the skill is global, add `check` lines for `$HOME/.claude/skills/<name>/SKILL.md` and `$HOME/.claude/skills/<name>/.csb-version`, plus `grep_check` lines for `claude-second-brain path` and `claude-second-brain qmd` (global skills use the CLI proxy, not a baked INDEX_PATH).
5. **`.claude/skills/pack-test/SKILL.md`** — update the expected-skills comment, the `ls` and `grep` commands in Step 3, the checklist table (including the "N subdirs" count), and the cleanup / overwrite-warning note in Step 4.
Whenever you **change a qmd collection name, context path, or CLI invocation** in `scripts/qmd/setup.ts` or in skill workflows, you MUST also update every `-c <collection>` reference in `template/CLAUDE.md`, all `SKILL.md` files under `template/.claude/skills/`, and both READMEs.
Whenever you **add, remove, or rename a skill, or change the wiki schema, page types, or frontmatter format**, you MUST also update the corresponding page under `docs/pages/` — skill pages at `docs/pages/skills/`, schema summary at `docs/pages/concepts/schema.mdx`, and the sidebar in `vocs.config.ts` if page paths change. The docs site is built from `docs/` and deployed to GitHub Pages on merge to `main`.
-Use `__QMD_PATH__` as the placeholder in any template file that references the qmd index path — `bin/create.js::patchVault()` substitutes it at scaffold time.
+Template files must **not** contain build-time placeholders for paths. The only remaining placeholder is `__BRAIN_NAME__` in `template/README.md`, substituted by `bin/create.js::patchVault()`. All path resolution happens at invocation time:
+- **Global skills** (shipped to `~/.claude/skills/`) call `npx claude-second-brain path` / `npx claude-second-brain qmd -- …`, which resolve the default brain from `~/.claude-second-brain/config.toml`.
+- **Vault-local skills and scripts** use the relative path `.qmd/index.sqlite` from the vault root (`scripts/qmd/{setup,reindex}.ts` compute the absolute path from `import.meta.url`).
diff --git a/README.md b/README.md
index 55bde08..bdbafdf 100644
--- a/README.md
+++ b/README.md
@@ -59,16 +59,15 @@ npx claude-second-brain
```
The CLI will ask:
-- **Folder name** — where to create your vault (default: `my-brain`)
-- **qmd index path** — where to store the local search index (default: `~/.cache/qmd/index.sqlite`)
+- **Brain name** — what to call this brain (default: `my-brain`)
- **GitHub repo** — optionally create a private repo and push automatically (requires `gh` CLI)
-Then scaffolds the vault, installs `mise` + `node` + `pnpm`, runs `pnpm install`, and `git init`.
+Creates the brain at `~/.claude-second-brain/my-brain/`, registers it in `~/.claude-second-brain/config.toml`, installs `mise` + `node` + `pnpm`, runs `pnpm install`, and `git init`.
**Step 2 — Initialize inside Claude Code**
```bash
-cd my-brain && claude
+cd ~/.claude-second-brain/my-brain && claude
```
Then run:
@@ -90,7 +89,7 @@ git remote add origin https://github.com/you/my-brain.git
git push -u origin main
```
-Open `my-brain/` as a vault in Obsidian — the folder is already a valid Obsidian vault. The Git plugin is pre-configured — enable it and sync is automatic.
+Open `~/.claude-second-brain/my-brain/` as a vault in Obsidian — the folder is already a valid Obsidian vault. The Git plugin is pre-configured — enable it and sync is automatic.
---
@@ -223,20 +222,39 @@ All pages cross-link with Obsidian `[[wikilinks]]`. Contradictions are flagged w
## Directory layout
+All brains live under `~/.claude-second-brain/`. A central `config.toml` tracks them.
+
+```
+~/.claude-second-brain/
+├── config.toml ← Brain registry (default brain, paths, git remotes)
+└── my-brain/
+ ├── CLAUDE.md ← The schema. Claude reads this every session.
+ ├── raw-sources/ ← Your raw inputs. Claude never modifies these.
+ │ ├── articles/
+ │ ├── pdfs/
+ │ └── personal/
+ ├── wiki/ ← Claude owns this entirely.
+ │ ├── index.md
+ │ ├── log.md
+ │ ├── overview.md
+ │ ├── sources/
+ │ └── qa/
+ ├── scripts/qmd/ ← Semantic search setup and re-indexing
+ └── .qmd/ ← qmd index (gitignored)
```
-my-brain/
-├── CLAUDE.md ← The schema. Claude reads this every session.
-├── raw-sources/ ← Your raw inputs. Claude never modifies these.
-│ ├── articles/
-│ ├── pdfs/
-│ └── personal/
-├── wiki/ ← Claude owns this entirely.
-│ ├── index.md
-│ ├── log.md
-│ ├── overview.md
-│ ├── sources/
-│ └── qa/
-└── scripts/qmd/ ← Semantic search setup and re-indexing
+
+## Multiple brains
+
+Run `npx claude-second-brain` again to create additional brains. Each gets its own folder, its own qmd index, and its own git remote — fully isolated. The global skills (`/brain-ingest`, `/brain-search`, `/brain-refresh`) always operate on the **default brain** declared in `config.toml`. The first brain you create is set as the default automatically.
+
+Manage brains from the CLI:
+
+```bash
+npx claude-second-brain ls # list all brains (default marked with *)
+npx claude-second-brain rm <name> # remove a brain (deletes its folder + config entry)
+npx claude-second-brain path # print the default brain's directory
+npx claude-second-brain path --qmd # print the default brain's qmd index path
+npx claude-second-brain qmd -- query -c wiki "<terms>" # run qmd against the default brain
```
---
diff --git a/bin/create.js b/bin/create.js
index 53b6d7e..449d570 100644
--- a/bin/create.js
+++ b/bin/create.js
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-import { cp, rename, access, readFile, writeFile, mkdir } from "fs/promises"
-import { readdirSync, readFileSync } from "fs"
+import { cp, rename, access, readFile, writeFile, mkdir, rm } from "fs/promises"
+import { readFileSync } from "fs"
import { join, dirname } from "path"
import { fileURLToPath } from "url"
import { spawnSync } from "child_process"
@@ -11,6 +11,8 @@ import pc from "picocolors"
const __dirname = dirname(fileURLToPath(import.meta.url))
const TEMPLATE = join(__dirname, "../template")
const { version } = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf8"))
+const CSB_ROOT = join(homedir(), ".claude-second-brain")
+const CSB_CONFIG = join(CSB_ROOT, "config.toml")
// Non-interactive commands — output piped (won't corrupt spinner)
function run(cmd, cwd) {
@@ -29,32 +31,9 @@ function commandExists(cmd) {
return result.status === 0
}
-async function patchVault(targetDir, qmdPath, brainName) {
- const filesToPatch = [
- join(targetDir, "scripts/qmd/setup.ts"),
- join(targetDir, "scripts/qmd/reindex.ts"),
- join(targetDir, "CLAUDE.md"),
- ]
-
- const skillsDir = join(targetDir, ".claude/skills")
- try {
- for (const skill of readdirSync(skillsDir)) {
- filesToPatch.push(join(skillsDir, skill, "SKILL.md"))
- }
- } catch (err) {
- if (err.code !== "ENOENT") throw err
- }
-
- await Promise.all(filesToPatch.map(async file => {
- try {
- let content = await readFile(file, "utf8")
- content = content.replaceAll("__QMD_PATH__", qmdPath)
- await writeFile(file, content, "utf8")
- } catch (err) {
- if (err.code !== "ENOENT") throw err
- }
- }))
-
+async function patchVault(targetDir, brainName) {
+ // Only __BRAIN_NAME__ is substituted — all path resolution happens at
+ // invocation time via the `claude-second-brain` CLI subcommands.
const readmePath = join(targetDir, "README.md")
try {
let readme = await readFile(readmePath, "utf8")
@@ -246,27 +225,364 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
return { repoToken, remote }
}
-async function installGlobalSkills(qmdPath) {
- const globalSkillsDir = join(homedir(), ".claude", "skills")
+const GLOBAL_SKILLS = ["brain-ingest", "brain-search", "brain-refresh"]
+
+async function readSkillVersion(skillDir) {
+ try {
+ const raw = await readFile(join(skillDir, ".csb-version"), "utf8")
+ return JSON.parse(raw).version || null
+ } catch {
+ return null
+ }
+}
- await Promise.all(["brain-ingest", "brain-search", "brain-refresh"].map(async skillName => {
- const srcFile = join(TEMPLATE, ".claude/skills", skillName, "SKILL.md")
- const destDir = join(globalSkillsDir, skillName)
+// Decide whether to (re)install each global skill. Returns a map name→"install"|"skip".
+// Interactive mismatch prompts once per run with update-all / skip-all / ask-per-skill.
+async function planGlobalSkillInstall({ isInteractive }) {
+ const decisions = {}
+ const mismatches = []
+
+ for (const name of GLOBAL_SKILLS) {
+ const destDir = join(homedir(), ".claude", "skills", name)
+ const installed = await readSkillVersion(destDir)
+ if (!installed) {
+ decisions[name] = "install"
+ } else if (installed === version) {
+ decisions[name] = "skip"
+ } else {
+ mismatches.push({ name, installed })
+ }
+ }
+
+ if (mismatches.length === 0) return decisions
- let content = await readFile(srcFile, "utf8")
- content = content.replaceAll("__QMD_PATH__", qmdPath)
+ // CI / non-interactive / opt-out: silently update.
+ if (!isInteractive || process.env.CSB_SKIP_SKILL_UPDATES === "1") {
+ for (const m of mismatches) decisions[m.name] = "install"
+ return decisions
+ }
+
+ const mode = await p.select({
+ message: `${mismatches.length} global skill${mismatches.length === 1 ? "" : "s"} at a different version than this release (v${version}). Update?`,
+ options: [
+ { value: "update-all", label: "Update all" },
+ { value: "skip-all", label: "Keep existing (skip all)" },
+ { value: "ask", label: "Ask per skill" },
+ ],
+ initialValue: "update-all",
+ })
+ if (p.isCancel(mode)) {
+ for (const m of mismatches) decisions[m.name] = "skip"
+ return decisions
+ }
+
+ if (mode === "update-all") {
+ for (const m of mismatches) decisions[m.name] = "install"
+ } else if (mode === "skip-all") {
+ for (const m of mismatches) decisions[m.name] = "skip"
+ } else {
+ for (const m of mismatches) {
+ const ok = await p.confirm({
+ message: `Update "${m.name}" from v${m.installed} → v${version}?`,
+ initialValue: true,
+ })
+ decisions[m.name] = p.isCancel(ok) || !ok ? "skip" : "install"
+ }
+ }
+ return decisions
+}
+
+async function installGlobalSkills({ isInteractive }) {
+ const globalSkillsDir = join(homedir(), ".claude", "skills")
+ const decisions = await planGlobalSkillInstall({ isInteractive })
+
+ const installed = []
+ const skipped = []
+ const sameVersion = []
+
+ await Promise.all(GLOBAL_SKILLS.map(async name => {
+ const destDir = join(globalSkillsDir, name)
+ const decision = decisions[name]
+
+ if (decision === "skip") {
+ // Differentiate "already at this version" from "user declined update" for logging.
+ const current = await readSkillVersion(destDir)
+ if (current === version) sameVersion.push(name)
+ else skipped.push(name)
+ return
+ }
+
+ const srcFile = join(TEMPLATE, ".claude/skills", name, "SKILL.md")
+ const content = await readFile(srcFile, "utf8")
await mkdir(destDir, { recursive: true })
await writeFile(join(destDir, "SKILL.md"), content, "utf8")
+ await writeFile(
+ join(destDir, ".csb-version"),
+ JSON.stringify({ version, installed: new Date().toISOString() }, null, 2) + "\n",
+ "utf8",
+ )
+ installed.push(name)
}))
+
+ return { installed, skipped, sameVersion }
}
-async function main() {
+function parseConfig(content) {
+ if (!content) return { defaultBrain: null, brains: [], header: "" }
+ const blocks = content.split(/\n(?=\[\[brains\]\])/)
+ const header = blocks[0] || ""
+ // Prefer `default = …` over legacy `active = …` so existing configs upgrade
+ // transparently on the next write.
+ const defaultMatch =
+ header.match(/^default\s*=\s*"([^"]+)"/m) ||
+ header.match(/^active\s*=\s*"([^"]+)"/m)
+ const brains = blocks.slice(1).map(block => {
+ const get = re => (block.match(re) || [])[1] || ""
+ return {
+ raw: block,
+ name: get(/^name\s*=\s*"([^"]+)"/m),
+ path: get(/^path\s*=\s*"([^"]+)"/m),
+ qmd_index: get(/^qmd_index\s*=\s*"([^"]*)"/m),
+ created: get(/^created\s*=\s*"([^"]*)"/m),
+ git_remote: get(/^git_remote\s*=\s*"([^"]*)"/m),
+ }
+ }).filter(b => b.name)
+ return { defaultBrain: defaultMatch ? defaultMatch[1] : null, brains, header }
+}
+
+function printHelp() {
+ const lines = [
+ `${pc.bold("claude-second-brain")} v${version}`,
+ "",
+ "Usage:",
+ ` ${pc.cyan("claude-second-brain")} create a new brain (interactive)`,
+ ` ${pc.cyan("claude-second-brain <name>")} create a new brain named <name>`,
+ ` ${pc.cyan("claude-second-brain ls")} list all brains`,
+ ` ${pc.cyan("claude-second-brain rm <name>")} remove a brain (directory + config entry)`,
+ ` ${pc.cyan("claude-second-brain path [--brain N] [flag]")} print a path (flags: --root, --qmd, --config)`,
+ ` ${pc.cyan("claude-second-brain qmd [--brain N] -- …")} run qmd against the resolved brain`,
+ ` ${pc.cyan("claude-second-brain help")} show this message`,
+ ]
+ console.log(lines.join("\n"))
+}
+
+// Resolve a brain entry from config. Name defaults to the `default` field.
+async function resolveBrain(name) {
+ let content
+ try {
+ content = await readFile(CSB_CONFIG, "utf8")
+ } catch {
+ throw new Error(`No config at ${CSB_CONFIG}. Run \`claude-second-brain <name>\` to create your first brain.`)
+ }
+ const { defaultBrain, brains } = parseConfig(content)
+ const target = name || defaultBrain
+ if (!target) throw new Error("No default brain set in config.toml.")
+ const entry = brains.find(b => b.name === target)
+ if (!entry) throw new Error(`No brain named "${target}". Run \`claude-second-brain ls\` to see registered brains.`)
+ return entry
+}
+
+async function cmdPath(args) {
+ // Parse flags: --brain <name>, --root | --qmd | --config (default: --root)
+ let name = null
+ let mode = "root"
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]
+ if (a === "--brain") { name = args[++i]; continue }
+ if (a === "--root") { mode = "root"; continue }
+ if (a === "--qmd") { mode = "qmd"; continue }
+ if (a === "--config") { mode = "config"; continue }
+ throw new Error(`Unknown path arg: ${a}`)
+ }
+ if (mode === "config") {
+ process.stdout.write(CSB_CONFIG + "\n")
+ return
+ }
+ const brain = await resolveBrain(name)
+ const out = mode === "qmd" ? brain.qmd_index : brain.path
+ process.stdout.write(out + "\n")
+}
+
+async function cmdQmd(args) {
+ // `claude-second-brain qmd [--brain N] [--] <qmd args…>`
+ let name = null
+ const rest = []
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]
+ if (a === "--brain") { name = args[++i]; continue }
+ if (a === "--") { rest.push(...args.slice(i + 1)); break }
+ rest.push(a)
+ }
+ const brain = await resolveBrain(name)
+ const result = spawnSync("npx", ["-y", "@tobilu/qmd", ...rest], {
+ stdio: "inherit",
+ env: { ...process.env, INDEX_PATH: brain.qmd_index },
+ })
+ process.exit(result.status ?? 1)
+}
+
+async function listBrains() {
+ const toDisplayPath = p => p && p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
+ let content
+ try {
+ content = await readFile(CSB_CONFIG, "utf8")
+ } catch {
+ p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
+ p.log.info("No brains yet. Run `claude-second-brain <name>` to create one.")
+ p.outro("")
+ return
+ }
+
+ const { defaultBrain, brains } = parseConfig(content)
+ p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
+
+ if (brains.length === 0) {
+ p.log.info("No brains registered in config.toml.")
+ p.outro("")
+ return
+ }
+
+ const rows = brains.map(b => {
+ const marker = b.name === defaultBrain ? pc.green("*") : " "
+ const name = b.name === defaultBrain ? pc.bold(b.name) : b.name
+ const remote = b.git_remote || pc.dim("—")
+ return `${marker} ${name}\n path: ${pc.dim(toDisplayPath(b.path))}\n created: ${pc.dim(b.created || "—")}\n remote: ${pc.dim(remote)}`
+ })
+
+ p.note(rows.join("\n\n"), `${brains.length} brain${brains.length === 1 ? "" : "s"}`)
+ p.outro(defaultBrain ? `default: ${pc.cyan(defaultBrain)}` : "no default brain")
+}
+
+async function removeBrain(name, { yes = false } = {}) {
+ p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
+
+ let content
+ try {
+ content = await readFile(CSB_CONFIG, "utf8")
+ } catch {
+ p.cancel(`No config at ${CSB_CONFIG} — nothing to remove.`)
+ process.exit(1)
+ }
+
+ const { defaultBrain, brains, header } = parseConfig(content)
+
+ if (brains.length === 0) {
+ p.cancel("No brains registered in config.toml.")
+ process.exit(1)
+ }
+
+ const toDisplayPath = p => p && p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
+
+ if (!name) {
+ const pick = await p.select({
+ message: "Which brain to remove?",
+ options: brains.map(b => ({
+ value: b.name,
+ label: b.name === defaultBrain ? `${b.name} ${pc.dim("(default)")}` : b.name,
+ hint: toDisplayPath(b.path),
+ })),
+ })
+ if (p.isCancel(pick)) { p.cancel("Cancelled."); process.exit(0) }
+ name = pick
+ }
+
+ const target = brains.find(b => b.name === name)
+ if (!target) {
+ p.cancel(`No brain named "${name}". Run \`claude-second-brain ls\` to see registered brains.`)
+ process.exit(1)
+ }
+
+ if (!yes) {
+ const ok = await p.confirm({
+ message: `Remove brain "${name}"? This deletes ${toDisplayPath(target.path)} and removes it from config.toml.`,
+ initialValue: false,
+ })
+ if (p.isCancel(ok) || !ok) {
+ p.cancel("Cancelled.")
+ process.exit(0)
+ }
+ }
+
+ const spin = p.spinner()
+
+ // Delete brain directory first — config removal is cheap even if this fails.
+ spin.start(`Deleting ${toDisplayPath(target.path)}`)
+ if (target.path) {
+ try {
+ await rm(target.path, { recursive: true, force: true })
+ spin.stop(`Removed ${pc.dim(toDisplayPath(target.path))}`)
+ } catch (err) {
+ spin.stop(`Failed to remove directory: ${err.message}`, 1)
+ }
+ } else {
+ spin.stop("No path on config entry — skipping directory removal", 1)
+ }
+
+ // Rewrite config.toml without the removed brain.
+ const remaining = brains.filter(b => b.name !== name)
+ // Strip both legacy `active = …` and current `default = …` from the header;
+ // we rewrite it from scratch below.
+ let newHeader = header
+ .replace(/^active\s*=\s*"[^"]*"\s*\n?/m, "")
+ .replace(/^default\s*=\s*"[^"]*"\s*\n?/m, "")
+ .replace(/^\s+|\s+$/g, "")
+ if (name === defaultBrain) {
+ if (remaining.length > 0) {
+ newHeader = `default = "${remaining[0].name}"${newHeader ? "\n" + newHeader : ""}`
+ }
+ } else if (defaultBrain) {
+ newHeader = `default = "${defaultBrain}"${newHeader ? "\n" + newHeader : ""}`
+ }
+
+ const entries = remaining.map(b => b.raw.replace(/^\s+|\s+$/g, ""))
+ const out = [newHeader, ...entries].filter(Boolean).join("\n\n").trimEnd() + "\n"
+ await writeFile(CSB_CONFIG, out, "utf8")
+
+ const defaultNow = parseConfig(out).defaultBrain
+ p.outro(
+ name === defaultBrain
+ ? (defaultNow ? `Removed. Default brain is now ${pc.cyan(defaultNow)}.` : "Removed. No brains left.")
+ : "Removed."
+ )
+}
+
+async function writeConfig(brainName, brainPath, qmdPath, gitRemote) {
+ const entry = [
+ `[[brains]]`,
+ `name = "${brainName}"`,
+ `path = "${brainPath}"`,
+ `qmd_index = "${qmdPath}"`,
+ `created = "${new Date().toISOString().slice(0, 10)}"`,
+ `git_remote = "${gitRemote}"`,
+ ].join("\n")
+
+ let existing = null
+ try {
+ existing = await readFile(CSB_CONFIG, "utf8")
+ } catch {
+ // Config doesn't exist yet — create fresh
+ }
+
+ if (!existing) {
+ await writeFile(CSB_CONFIG, `default = "${brainName}"\n\n${entry}\n`, "utf8")
+ return
+ }
+
+ // Upsert: remove existing entry for this brain name, then append updated entry.
+ // Also migrate legacy `active = …` to `default = …` on any write.
+ const blocks = existing.split(/\n(?=\[\[brains\]\])/)
+ const header = blocks[0].replace(/^active\s*=/m, "default =")
+ const otherBrains = blocks.slice(1).filter(b => !b.includes(`name = "${brainName}"`))
+ await writeFile(CSB_CONFIG, [header, ...otherBrains, entry].join("\n").trimEnd() + "\n", "utf8")
+}
+
+async function createBrain(initialName) {
const isInteractive = Boolean(process.stdin.isTTY)
p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
- let targetName = process.argv[2]
+ let targetName = initialName
if (!targetName) {
const answer = await p.text({
message: "Where to create your brain?",
@@ -277,25 +593,8 @@ async function main() {
targetName = answer
}
- const defaultQmdPath = join(
- process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
- "qmd", "index.sqlite"
- )
const toDisplayPath = p => p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
- const expandHome = p => p.startsWith("~/") || p === "~" ? join(homedir(), p.slice(1)) : p
- const displayQmdPath = toDisplayPath(defaultQmdPath)
- let qmdPath
- if (isInteractive) {
- const answer = await p.text({
- message: "Where to store the qmd index?",
- placeholder: displayQmdPath,
- defaultValue: displayQmdPath,
- })
- if (p.isCancel(answer)) { p.cancel("Setup cancelled."); process.exit(0) }
- qmdPath = expandHome(answer)
- } else {
- qmdPath = defaultQmdPath
- }
+ const qmdPath = join(CSB_ROOT, targetName, ".qmd", "index.sqlite")
let remoteProvider = "none"
let repoName = null
@@ -334,7 +633,8 @@ async function main() {
}
}
- const targetDir = join(process.cwd(), targetName)
+ await mkdir(CSB_ROOT, { recursive: true })
+ const targetDir = join(CSB_ROOT, targetName)
// Fail fast if target already exists
try {
@@ -358,12 +658,13 @@ async function main() {
} catch {
// .gitignore.template not present (e.g. running locally where npm didn't strip it)
}
- spin.stop(`${targetName}/ created`)
+ spin.stop(`${pc.dim(toDisplayPath(targetDir))} created`)
- // Patch vault files with chosen qmd path
- spin.start("Configuring qmd index path")
- await patchVault(targetDir, qmdPath, targetName)
- spin.stop(`qmd index → ${pc.dim(toDisplayPath(qmdPath))}`)
+ // Patch vault README (__BRAIN_NAME__). All other paths are resolved at
+ // runtime via `claude-second-brain path` / `claude-second-brain qmd`.
+ spin.start("Patching README")
+ await patchVault(targetDir, targetName)
+ spin.stop("README patched")
// Install mise if not present
if (!commandExists("mise")) {
@@ -386,10 +687,16 @@ async function main() {
if (pnpmOk) spin.stop("dependencies installed")
else spin.stop("pnpm install failed — run it manually inside your vault", 1)
- // Install global skills
+ // Install global skills (version-aware — prompts to update when versions differ)
spin.start("Installing global Claude skills")
- await installGlobalSkills(qmdPath)
- spin.stop(`Global skills installed → ${pc.dim(toDisplayPath(join(homedir(), ".claude", "skills")))}`)
+ const skillResult = await installGlobalSkills({ isInteractive })
+ const installedCount = skillResult.installed.length
+ const skippedCount = skillResult.skipped.length
+ const summary = [
+ installedCount > 0 ? `installed ${installedCount}` : null,
+ skippedCount > 0 ? `kept ${skippedCount}` : null,
+ ].filter(Boolean).join(", ") || "already up to date"
+ spin.stop(`Global skills ${summary} → ${pc.dim(toDisplayPath(join(homedir(), ".claude", "skills")))}`)
// Git init
spin.start("Initializing git repo")
@@ -431,14 +738,27 @@ async function main() {
}
// Cloudflare Artifacts repo (optional)
+ let gitRemote = remoteProvider === "github"
+ ? (() => {
+ const r = spawnSync("git", ["remote", "get-url", "origin"], { cwd: targetDir, stdio: "pipe" })
+ return r.status === 0 ? r.stdout.toString().trim() : ""
+ })()
+ : ""
if (remoteProvider === "cloudflare") {
const result = await setupCloudflareRemote({ targetDir, repoName, namespace: cfNamespace, spin })
if (result?.repoToken) {
p.log.warn(`Save your Artifacts repo token — it expires and you'll need to mint a new one:\n ${result.repoToken}`)
}
+ gitRemote = result?.remote || ""
}
+ // Write central config
+ spin.start("Registering brain in config")
+ await writeConfig(targetName, targetDir, qmdPath, gitRemote)
+ spin.stop(`Config updated → ${pc.dim(toDisplayPath(CSB_CONFIG))}`)
+
// Next steps
+ const brainDisplayPath = toDisplayPath(targetDir)
const remoteSteps = remoteProvider === "cloudflare"
? [
`${pc.dim("# Mint a fresh git push/pull token when the current one expires:")}`,
@@ -456,7 +776,7 @@ async function main() {
: []
const nextSteps = [
- `${pc.cyan(`cd ${targetName}`)}`,
+ `${pc.cyan(`cd ${brainDisplayPath}`)}`,
`${pc.cyan("claude")} open Claude Code, then run ${pc.bold("/setup")}`,
...remoteSteps,
].join("\n")
@@ -465,6 +785,34 @@ async function main() {
p.outro("Happy knowledge building!")
}
+async function main() {
+ const [, , cmd, ...rest] = process.argv
+
+ if (cmd === "help" || cmd === "--help" || cmd === "-h") {
+ printHelp()
+ return
+ }
+ if (cmd === "ls" || cmd === "list") {
+ await listBrains()
+ return
+ }
+ if (cmd === "rm" || cmd === "remove") {
+ const name = rest.find(a => !a.startsWith("-"))
+ const yes = rest.some(a => a === "-y" || a === "--yes")
+ await removeBrain(name, { yes })
+ return
+ }
+ if (cmd === "path") {
+ await cmdPath(rest)
+ return
+ }
+ if (cmd === "qmd") {
+ await cmdQmd(rest)
+ return
+ }
+ await createBrain(cmd)
+}
+
main().catch(err => {
p.cancel(err.message)
process.exit(1)
diff --git a/docs/pages/getting-started.mdx b/docs/pages/getting-started.mdx
index 537364e..d2abfe7 100644
--- a/docs/pages/getting-started.mdx
+++ b/docs/pages/getting-started.mdx
@@ -14,16 +14,15 @@ npx claude-second-brain
The CLI will ask:
-- **Folder name** — where to create your vault (default: `my-brain`)
-- **qmd index path** — where to store the local search index (default: `~/.cache/qmd/index.sqlite`)
+- **Brain name** — what to call this brain (default: `my-brain`)
- **Git remote** — optionally host your vault on **[GitHub](/remotes/github)** (requires `gh` CLI) or **[Cloudflare Artifacts](/remotes/cloudflare-artifacts)** (requires a Cloudflare account + wrangler)
-Then scaffolds the vault, installs `mise` + `node` + `pnpm`, runs `pnpm install`, and `git init`.
+Creates the brain at `~/.claude-second-brain/my-brain/`, registers it in `~/.claude-second-brain/config.toml`, installs `mise` + `node` + `pnpm`, runs `pnpm install`, and `git init`.
## Step 2 — Initialize inside Claude Code
```bash
-cd my-brain && claude
+cd ~/.claude-second-brain/my-brain && claude
```
Then run:
@@ -45,7 +44,11 @@ git remote add origin https://github.com/you/my-brain.git
git push -u origin main
```
-Open `my-brain/` as a vault in Obsidian — the folder is already a valid Obsidian vault. The Git plugin is pre-configured — enable it and sync is automatic.
+Open `~/.claude-second-brain/my-brain/` as a vault in Obsidian — the folder is already a valid Obsidian vault. The Git plugin is pre-configured — enable it and sync is automatic.
+
+## Multiple brains
+
+Run `npx claude-second-brain` again to create additional brains. Each gets its own folder under `~/.claude-second-brain/` and its own isolated qmd index. The global skills (`/brain-ingest`, `/brain-search`, `/brain-refresh`) always operate on the **default brain** in `~/.claude-second-brain/config.toml`. The first brain created is set as the default automatically.
## Access from anywhere
diff --git a/docs/pages/ship-log.mdx b/docs/pages/ship-log.mdx
index 9377d32..bdd0e46 100644
--- a/docs/pages/ship-log.mdx
+++ b/docs/pages/ship-log.mdx
@@ -2,6 +2,16 @@
A running record of every released version of `claude-second-brain` on npm. Newest releases first. For auto-generated notes and tags, see the [GitHub releases](https://github.com/jessepinkman9900/claude-second-brain/releases) page.
+## Unreleased
+
+**CLI:**
+- Added `claude-second-brain path [--brain N] [--root|--qmd|--config]` and `claude-second-brain qmd [--brain N] -- …` subcommands. The global skills now resolve paths at call time via these commands instead of having absolute paths baked in at scaffold time.
+- `config.toml`'s `active` field renamed to `default`. Existing configs with `active = …` are still read transparently and rewritten to `default = …` on the next write.
+- Global skills (`brain-ingest`, `brain-search`, `brain-refresh`) now ship with a `.csb-version` sidecar file. Re-running `npx claude-second-brain <name>` detects version mismatches and prompts before overwriting; `CSB_SKIP_SKILL_UPDATES=1` disables the prompt.
+
+**Refactors:**
+- Removed the `__QMD_PATH__` and `__CSB_CONFIG__` placeholder substitutions. `scripts/qmd/{setup,reindex}.ts` now compute the index path from `import.meta.url`; CLAUDE.md and vault-local skills use a relative `.qmd/index.sqlite` path.
+
## v0.6.0 — 2026-04-17
**Features:**
diff --git a/docs/pages/skills/brain-ingest.mdx b/docs/pages/skills/brain-ingest.mdx
index 7de603d..f245044 100644
--- a/docs/pages/skills/brain-ingest.mdx
+++ b/docs/pages/skills/brain-ingest.mdx
@@ -11,4 +11,4 @@ Drop a file into `raw-sources/articles/`, `raw-sources/pdfs/`, or `raw-sources/p
5. **Flag contradictions** with `[!WARNING]` callouts on any page where the new source disagrees with existing claims.
6. **Log** the ingest in `wiki/log.md`.
-Scope: global skill, installed at `~/.claude/skills/brain-ingest/SKILL.md`. Source: [template/.claude/skills/brain-ingest/SKILL.md](https://github.com/jessepinkman9900/claude-second-brain/blob/main/template/.claude/skills/brain-ingest/SKILL.md).
+Scope: global skill, installed at `~/.claude/skills/brain-ingest/SKILL.md`. Paths resolve at call time via `npx claude-second-brain path` and `npx claude-second-brain qmd` — both read `~/.claude-second-brain/config.toml` to find the default brain. Source: [template/.claude/skills/brain-ingest/SKILL.md](https://github.com/jessepinkman9900/claude-second-brain/blob/main/template/.claude/skills/brain-ingest/SKILL.md).
diff --git a/docs/pages/skills/brain-refresh.mdx b/docs/pages/skills/brain-refresh.mdx
index 926cb7a..fd4cd37 100644
--- a/docs/pages/skills/brain-refresh.mdx
+++ b/docs/pages/skills/brain-refresh.mdx
@@ -6,4 +6,4 @@ Re-scans all collections for new or changed files and regenerates vector embeddi
Pass `force` to re-embed every chunk — useful after changing the embedding model.
-Scope: global skill, installed at `~/.claude/skills/brain-refresh/SKILL.md`. Source: [template/.claude/skills/brain-refresh/SKILL.md](https://github.com/jessepinkman9900/claude-second-brain/blob/main/template/.claude/skills/brain-refresh/SKILL.md).
+Scope: global skill, installed at `~/.claude/skills/brain-refresh/SKILL.md`. Paths resolve at call time via `npx claude-second-brain path` and `npx claude-second-brain qmd` — both read `~/.claude-second-brain/config.toml` to find the default brain. Source: [template/.claude/skills/brain-refresh/SKILL.md](https://github.com/jessepinkman9900/claude-second-brain/blob/main/template/.claude/skills/brain-refresh/SKILL.md).
diff --git a/docs/pages/skills/brain-search.mdx b/docs/pages/skills/brain-search.mdx
index b26785f..539f2b9 100644
--- a/docs/pages/skills/brain-search.mdx
+++ b/docs/pages/skills/brain-search.mdx
@@ -6,4 +6,4 @@ Runs hybrid search (vector + BM25) across the entire wiki, reads the 2–5 most
If the answer pulls together multiple pages in a novel way, it offers to file it as a permanent `wiki/qa/[slug].md` entry — so the synthesis compounds next time.
-Scope: global skill, installed at `~/.claude/skills/brain-search/SKILL.md`. Source: [template/.claude/skills/brain-search/SKILL.md](https://github.com/jessepinkman9900/claude-second-brain/blob/main/template/.claude/skills/brain-search/SKILL.md).
+Scope: global skill, installed at `~/.claude/skills/brain-search/SKILL.md`. Paths resolve at call time via `npx claude-second-brain path` and `npx claude-second-brain qmd` — both read `~/.claude-second-brain/config.toml` to find the default brain. Source: [template/.claude/skills/brain-search/SKILL.md](https://github.com/jessepinkman9900/claude-second-brain/blob/main/template/.claude/skills/brain-search/SKILL.md).
diff --git a/template/.claude/skills/brain-ingest/SKILL.md b/template/.claude/skills/brain-ingest/SKILL.md
index 004c1ec..dfe2421 100644
--- a/template/.claude/skills/brain-ingest/SKILL.md
+++ b/template/.claude/skills/brain-ingest/SKILL.md
@@ -8,6 +8,23 @@ argument-hint: "File path (e.g. raw-sources/articles/my-article.md), URL, or lea
Runs the full 9-step ingest workflow defined in CLAUDE.md. Do not skip steps.
+## Brain Discovery
+
+All commands target the **default brain** registered in `~/.claude-second-brain/config.toml`.
+Resolve paths at call time via the `claude-second-brain` CLI — do not bake paths into this file:
+
+```bash
+BRAIN_PATH=$(npx -y claude-second-brain path) # absolute path to the default brain's directory
+```
+
+qmd commands go through the CLI proxy, which sets `INDEX_PATH` for you:
+
+```bash
+npx -y claude-second-brain qmd -- query -c wiki "<terms>"
+```
+
+Pass `--brain <name>` before the `--` to target a non-default brain.
+
## Inputs
- **File path** — a file in `raw-sources/articles/`, `raw-sources/pdfs/`, or `raw-sources/personal/`
@@ -27,7 +44,7 @@ Runs the full 9-step ingest workflow defined in CLAUDE.md. Do not skip steps.
- Let the user's response shape which topics get deep treatment before proceeding
**Step 3 — Create source summary page**
-- File: `wiki/sources/[slug].md` (slug = kebab-case from title)
+- File: `$BRAIN_PATH/wiki/sources/[slug].md` (slug = kebab-case from title)
- Sections: title, author/date, one-paragraph abstract, key claims (bulleted), notable quotes (max 3), synthesis note, links to wiki pages this source touches
- Frontmatter: `type: source-summary`, `tags`, `updated: YYYY-MM-DD`
@@ -35,8 +52,8 @@ Runs the full 9-step ingest workflow defined in CLAUDE.md. Do not skip steps.
- Add the new source to the Sources Ingested section: one-line description + `[[wiki/sources/slug]]` link
**Step 5 — Identify affected wiki pages**
-- Run: `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "<source topic and key claims>"`
-- Also Glob `wiki/*.md` and `wiki/sources/*.md` to catch anything qmd missed
+- Run: `npx -y claude-second-brain qmd -- query -c wiki "<source topic and key claims>"`
+- Also Glob `$BRAIN_PATH/wiki/*.md` and `$BRAIN_PATH/wiki/sources/*.md` to catch anything qmd missed
- List all pages to create or update before proceeding
**Step 6 — Update or create wiki pages**
@@ -54,7 +71,7 @@ Runs the full 9-step ingest workflow defined in CLAUDE.md. Do not skip steps.
- Otherwise skip this step
**Step 9 — Append to log**
-- Append to `wiki/log.md` (never overwrite):
+- Append to `$BRAIN_PATH/wiki/log.md` (never overwrite):
```
## [YYYY-MM-DD] ingest | Source Title
diff --git a/template/.claude/skills/brain-rebuild/SKILL.md b/template/.claude/skills/brain-rebuild/SKILL.md
index cbcd0bd..91904bc 100644
--- a/template/.claude/skills/brain-rebuild/SKILL.md
+++ b/template/.claude/skills/brain-rebuild/SKILL.md
@@ -25,9 +25,9 @@ All commands run from the vault root.
- Read `CLAUDE.md` to understand the documented schema and any references to collection names
- List current state from qmd:
```bash
- INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection list
- INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context list
- INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd status
+ INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection list
+ INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context list
+ INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd status
```
### Step 2 — Analyze the wiki
@@ -74,13 +74,13 @@ If collection names changed:
For each existing collection that no longer fits the new schema:
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection remove <old-name>
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection remove <old-name>
```
For each obsolete context:
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context rm <path>
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context rm <path>
```
### Step 8 — Register the new schema
@@ -104,9 +104,9 @@ This indexes all files under the new collections and generates fresh embeddings.
### Step 10 — Verify and report
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection list
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context list
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd status
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection list
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context list
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd status
```
Confirm the new collections appear, contexts match the plan, and document/embedding counts are non-zero. Report a summary of what changed (collections added/removed/renamed, contexts updated, files re-indexed, references updated in CLAUDE.md and skills).
diff --git a/template/.claude/skills/brain-refresh/SKILL.md b/template/.claude/skills/brain-refresh/SKILL.md
index dfad146..473d824 100644
--- a/template/.claude/skills/brain-refresh/SKILL.md
+++ b/template/.claude/skills/brain-refresh/SKILL.md
@@ -8,6 +8,18 @@ argument-hint: "Optional: 'force' to force re-embedding of every chunk (slow, us
Refreshes the qmd index so search reflects the current state of the vault. Wraps `pnpm qmd:reindex` (incremental) and the qmd CLI's force-embed flag.
+## Brain Discovery
+
+All commands target the **default brain** registered in `~/.claude-second-brain/config.toml`.
+Resolve the brain root via the CLI and run qmd through the CLI proxy:
+
+```bash
+BRAIN_PATH=$(npx -y claude-second-brain path)
+npx -y claude-second-brain qmd -- status
+```
+
+Pass `--brain <name>` before the `--` to target a non-default brain.
+
## When to Use
- After a `/brain-ingest` session (or several) — batch the refresh, don't run after every file edit
@@ -17,13 +29,13 @@ Refreshes the qmd index so search reflects the current state of the vault. Wraps
## Procedure
-All commands run from the vault root.
+All `pnpm qmd:*` commands must run from `$BRAIN_PATH`; the CLI proxy (`claude-second-brain qmd`) works from anywhere.
### Default — Incremental Refresh
Run:
```bash
-pnpm qmd:reindex
+cd "$BRAIN_PATH" && pnpm qmd:reindex
```
This script does two things:
@@ -38,10 +50,10 @@ When the user passes `force`, re-embed **every** chunk — not just the changed
```bash
# Step 1 — update the file index first
-pnpm qmd:reindex
+cd "$BRAIN_PATH" && pnpm qmd:reindex
# Step 2 — force re-embed everything
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd embed -f
+npx -y claude-second-brain qmd -- embed -f
```
Force mode is slow — confirm with the user before proceeding if the wiki is large.
@@ -51,7 +63,7 @@ Force mode is slow — confirm with the user before proceeding if the wiki is la
After refresh, confirm with:
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd status
+npx -y claude-second-brain qmd -- status
```
Document and embedding counts should be non-zero and reflect recent activity. If embeddings show as `0` or far below document count, re-run the refresh.
diff --git a/template/.claude/skills/brain-search/SKILL.md b/template/.claude/skills/brain-search/SKILL.md
index 28f3624..a5a5a5b 100644
--- a/template/.claude/skills/brain-search/SKILL.md
+++ b/template/.claude/skills/brain-search/SKILL.md
@@ -8,12 +8,24 @@ argument-hint: "The question or topic to query (e.g. 'what do I know about trans
Runs the 4-step query workflow defined in CLAUDE.md. Answers come with inline `[[wiki/page]]` citations — not a list of files.
+## Brain Discovery
+
+All commands target the **default brain** registered in `~/.claude-second-brain/config.toml`.
+Resolve paths and run qmd via the `claude-second-brain` CLI — do not bake paths into this file:
+
+```bash
+BRAIN_PATH=$(npx -y claude-second-brain path) # absolute path to the default brain's directory
+npx -y claude-second-brain qmd -- query -c wiki "<question>"
+```
+
+Pass `--brain <name>` before the `--` to target a non-default brain.
+
## Workflow
**Step 1 — Search the wiki**
-- Run hybrid search: `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "<question>"`
-- Read `wiki/index.md` to confirm coverage and catch any pages qmd didn't surface
-- Read the 2–5 most relevant pages in full before synthesizing
+- Run hybrid search: `npx -y claude-second-brain qmd -- query -c wiki "<question>"`
+- Read `$BRAIN_PATH/wiki/index.md` to confirm coverage and catch any pages qmd didn't surface
+- Read the 2–5 most relevant pages in full before synthesizing (paths relative to `$BRAIN_PATH`)
**Step 2 — Synthesize an answer**
- Write the answer with inline `[[wiki/page]]` citations throughout
@@ -24,12 +36,12 @@ Runs the 4-step query workflow defined in CLAUDE.md. Answers come with inline `[
- If the answer draws together multiple pages in a novel way, ask:
> "This answer synthesizes several pages in a useful way — want me to file it as a Q&A page?"
- If yes:
- - Create `wiki/qa/[slug].md` with frontmatter `type: qa`
+ - Create `$BRAIN_PATH/wiki/qa/[slug].md` with frontmatter `type: qa`
- Add to the Q&A section in `wiki/index.md`
- Add `[[wiki/qa/slug]]` cross-links from the relevant topic pages
**Step 4 — Log (if significant)**
-- For queries that reveal new understanding or surface a gap worth tracking, append to `wiki/log.md`:
+- For queries that reveal new understanding or surface a gap worth tracking, append to `$BRAIN_PATH/wiki/log.md`:
```
## [YYYY-MM-DD] query | Brief question summary
diff --git a/template/.claude/skills/qmd-cli/SKILL.md b/template/.claude/skills/qmd-cli/SKILL.md
index 41e861c..2ed7409 100644
--- a/template/.claude/skills/qmd-cli/SKILL.md
+++ b/template/.claude/skills/qmd-cli/SKILL.md
@@ -10,10 +10,10 @@ Local semantic document index with hybrid search (BM25 + vector), collection man
## Vault DB
-This vault keeps its index at `__QMD_PATH__`. All CLI commands **must** prefix with `INDEX_PATH=__QMD_PATH__`:
+This vault keeps its index at `.qmd/index.sqlite` (relative to the vault root). All CLI commands below run from the vault root and **must** prefix with `INDEX_PATH=.qmd/index.sqlite`:
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "..."
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query -c wiki "..."
```
The scripts `pnpm qmd:setup` and `pnpm qmd:reindex` write to this same file. The CLI must match.
@@ -24,40 +24,40 @@ The scripts `pnpm qmd:setup` and `pnpm qmd:reindex` write to this same file. The
```bash
# Create/index a collection
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection add <path> --name <name> --mask <glob-pattern>
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection add <path> --name <name> --mask <glob-pattern>
# e.g.:
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection add wiki --name wiki --mask "**/*.md"
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection add wiki --name wiki --mask "**/*.md"
# List all collections with details
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection list
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection list
# Remove a collection
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection remove <name>
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection remove <name>
# Rename a collection
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection rename <old-name> <new-name>
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection rename <old-name> <new-name>
```
## Listing Files
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd ls
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd ls [collection[/path]]
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd ls
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd ls [collection[/path]]
```
## Context
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context add [path] "description text"
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context list
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context rm <path>
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context add [path] "description text"
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context list
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context rm <path>
```
## Retrieving Documents
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd get <file>[:line] [-l N] [--from N]
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd multi-get <pattern> [-l N] [--max-bytes N]
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd get <file>[:line] [-l N] [--from N]
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd multi-get <pattern> [-l N] [--max-bytes N]
```
**Multi-get format flags:** `--json`, `--csv`, `--md`, `--xml`, `--files`
@@ -66,16 +66,16 @@ INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd multi-get <pattern> [-l N] [--max-b
```bash
# Show index status and collections
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd status
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd status
# Re-index all collections
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd update [--pull]
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd update [--pull]
# Create vector embeddings (900 tokens/chunk, 15% overlap)
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd embed [-f]
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd embed [-f]
# Remove cache and orphaned data, vacuum DB
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd cleanup
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd cleanup
```
> After bulk ingest sessions, run `update` then `embed` to keep the index fresh.
@@ -108,28 +108,28 @@ INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd cleanup
```bash
# Hybrid search across all collections
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query "distributed systems consensus"
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query "distributed systems consensus"
# Search only the wiki collection, JSON output
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "transformer architecture" --json
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query -c wiki "transformer architecture" --json
# Keyword-only search, top 10, markdown output
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd search -c wiki "kafka" -n 10 --md
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd search -c wiki "kafka" -n 10 --md
# Vector search with full documents
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd vsearch "attention mechanism" --full
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd vsearch "attention mechanism" --full
# Filter by score threshold
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query "machine learning" --all --min-score 0.7
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query "machine learning" --all --min-score 0.7
```
## MCP Server
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd mcp
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd mcp --http [--port N]
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd mcp --http --daemon
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd mcp stop
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd mcp
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd mcp --http [--port N]
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd mcp --http --daemon
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd mcp stop
```
## Global Options
@@ -151,18 +151,18 @@ pnpm qmd:reindex
### After a bulk ingest session
```bash
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd update
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd embed
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd update
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd embed
```
### Research workflow
```bash
# Discover relevant pages
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "<topic>"
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query -c wiki "<topic>"
# Get a specific file
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd get wiki/distributed-systems.md
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd get wiki/distributed-systems.md
# Get multiple related files
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd multi-get "wiki/kafka.md,wiki/distributed-systems.md" --md
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd multi-get "wiki/kafka.md,wiki/distributed-systems.md" --md
```
diff --git a/template/.claude/skills/setup/SKILL.md b/template/.claude/skills/setup/SKILL.md
index ab1885e..029487f 100644
--- a/template/.claude/skills/setup/SKILL.md
+++ b/template/.claude/skills/setup/SKILL.md
@@ -48,15 +48,17 @@ Do **not** re-run after every single file edit — batch it after a session.
Run these three commands to confirm everything is working:
+Run from the vault root so the relative `.qmd/index.sqlite` path resolves correctly:
+
```bash
# List registered collections (expect: wiki, raw-sources)
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd collection list
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd collection list
# List registered contexts
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd context list
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd context list
# Show index status and embedding counts
-INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd status
+INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd status
```
Both collections should appear in `collection list`. `status` should show non-zero document and embedding counts — if embeddings are 0, re-run step 2.
diff --git a/template/CLAUDE.md b/template/CLAUDE.md
index 89b26d0..6c53055 100644
--- a/template/CLAUDE.md
+++ b/template/CLAUDE.md
@@ -111,7 +111,7 @@ Run this workflow whenever the user adds a new source. Do not skip steps.
- Add the new source to the Sources section with a one-line description and link.
**Step 5 — Identify affected wiki pages**
-- Run `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "<source topic and key claims>"` to surface related existing wiki pages.
+- Run `INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query -c wiki "<source topic and key claims>"` to surface related existing wiki pages.
- Also Glob `wiki/*.md` and `wiki/sources/*.md` to ensure completeness.
- List all pages to create or update.
@@ -142,7 +142,7 @@ Run this workflow whenever the user adds a new source. Do not skip steps.
Run this workflow when the user asks a question against the wiki.
**Step 1 — Search the wiki**
-- Run `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "<question>"` to surface semantically relevant pages.
+- Run `INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query -c wiki "<question>"` to surface semantically relevant pages.
- Read `wiki/index.md` to confirm coverage and catch any pages qmd didn't surface.
- Read the 2-5 most relevant pages fully.
@@ -212,15 +212,15 @@ N issues found, N fixed. [Brief summary of notable findings.]
## Search Tool
This vault uses **qmd** (`pnpm dlx @tobilu/qmd`) for local semantic and full-text search.
-Collections and contexts are registered via `pnpm qmd:setup` and stored at `__QMD_PATH__` (gitignored).
+Collections and contexts are registered via `pnpm qmd:setup` and stored at `.qmd/index.sqlite` (gitignored, relative to vault root).
-Key commands:
+Key commands (run from the vault root):
| Command | Use |
|---------|-----|
-| `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd query -c wiki "<question>"` | Hybrid search — best for topic discovery |
-| `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd search -c wiki "<terms>"` | Fast keyword search (BM25, no LLM) |
-| `INDEX_PATH=__QMD_PATH__ pnpm dlx @tobilu/qmd vsearch -c wiki "<question>"` | Pure vector/semantic search |
+| `INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd query -c wiki "<question>"` | Hybrid search — best for topic discovery |
+| `INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd search -c wiki "<terms>"` | Fast keyword search (BM25, no LLM) |
+| `INDEX_PATH=.qmd/index.sqlite pnpm dlx @tobilu/qmd vsearch -c wiki "<question>"` | Pure vector/semantic search |
Add `--json` for structured output. Omit `-c wiki` to search all collections (wiki, raw-sources, human, daily-notes).
diff --git a/template/README.md b/template/README.md
index fcfbd46..c520d7d 100644
--- a/template/README.md
+++ b/template/README.md
@@ -192,6 +192,17 @@ This wraps `pnpm qmd:reindex` — you can also run that command directly if you'
---
+## Managing brains
+
+From anywhere:
+
+```bash
+npx claude-second-brain ls # list all brains
+npx claude-second-brain rm <name> # remove a brain
+```
+
+---
+
## License
MIT
diff --git a/template/scripts/qmd/reindex.ts b/template/scripts/qmd/reindex.ts
index 21e5569..4676b34 100644
--- a/template/scripts/qmd/reindex.ts
+++ b/template/scripts/qmd/reindex.ts
@@ -11,8 +11,11 @@
*/
import { createStore } from "@tobilu/qmd"
+import { dirname, join } from "node:path"
+import { fileURLToPath } from "node:url"
-const DB = "__QMD_PATH__"
+const VAULT = join(dirname(fileURLToPath(import.meta.url)), "../..")
+const DB = join(VAULT, ".qmd", "index.sqlite")
const store = await createStore({ dbPath: DB })
diff --git a/template/scripts/qmd/setup.ts b/template/scripts/qmd/setup.ts
index 7d2515c..6a10412 100644
--- a/template/scripts/qmd/setup.ts
+++ b/template/scripts/qmd/setup.ts
@@ -14,7 +14,7 @@ import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
const VAULT = join(dirname(fileURLToPath(import.meta.url)), "../..")
-const DB = "__QMD_PATH__"
+const DB = join(VAULT, ".qmd", "index.sqlite")
const store = await createStore({ dbPath: DB })