A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
feat: ARCHITECTURE.md, Obsidian-QMD ignore sync, lib cleanup, MCP-first (#65)
Brenno Ferraric98195d13ed7
diff --git a/.claude/scripts/lib/frontmatter.ts b/.claude/scripts/lib/frontmatter.tsindex 300146e..98ff22b 100644--- a/.claude/scripts/lib/frontmatter.ts+++ b/.claude/scripts/lib/frontmatter.ts@@ -10,6 +10,7 @@ const ROOT_FILES: ReadonlySet<string> = new Set(["README.md","CHANGELOG.md","CONTRIBUTING.md",+ "ARCHITECTURE.md","CLAUDE.md","AGENTS.md","GEMINI.md",diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.tsindex 0d0c45d..1830c27 100644--- a/.claude/scripts/lib/hook-io.ts+++ b/.claude/scripts/lib/hook-io.ts@@ -16,6 +16,15 @@ export function debug(msg: string): void {}}+/**+ * Emit a user-facing warning to stderr with the standard `⚠` prefix. Use for+ * non-fatal conditions the user should see (missing config, unexpected input+ * shape, etc.) so warning formatting stays consistent across scripts.+ */+export function warn(msg: string): void {+ process.stderr.write(` ⚠ ${msg}\n`);+}+export async function readStdinJson<T = unknown>(): Promise<T | null> {try {const chunks: Buffer[] = [];diff --git a/.claude/scripts/lib/main-guard.ts b/.claude/scripts/lib/main-guard.tsnew file mode 100644index 0000000..6df7c58--- /dev/null+++ b/.claude/scripts/lib/main-guard.ts@@ -0,0 +1,21 @@+/**+ * Detect whether the current ESM module was invoked directly as a script+ * (rather than imported). Use to gate side-effecting `main()` calls so the+ * module stays importable from tests and other modules.+ *+ * if (isMainModule(import.meta.url)) main();+ *+ * Equivalent of CommonJS's `require.main === module`. `fileURLToPath` strips+ * the `file://` prefix and URL-encoded segments so the comparison against+ * `process.argv[1]` (which is already an absolute resolved path) is+ * apples-to-apples on every platform.+ */++import { fileURLToPath } from "node:url";++export function isMainModule(importMetaUrl: string): boolean {+ return (+ process.argv[1] !== undefined &&+ fileURLToPath(importMetaUrl) === process.argv[1]+ );+}diff --git a/.claude/scripts/lib/matcher.ts b/.claude/scripts/lib/matcher.tsindex 77e786d..630c12c 100644--- a/.claude/scripts/lib/matcher.ts+++ b/.claude/scripts/lib/matcher.ts@@ -7,12 +7,9 @@* lookarounds enforce Latin word boundaries while allowing CJK adjacency.*/+import { escapeRegex } from "./regex.ts";import { SIGNALS } from "./signals.ts";-function escapeRegex(s: string): string {- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");-}-function compileMatcher(phrases: readonly string[]): RegExp {const body = phrases.map(escapeRegex).join("|");return new RegExp(`(?<![a-zA-Z])(?:${body})(?![a-zA-Z])`);diff --git a/.claude/scripts/lib/qmd-ignore.ts b/.claude/scripts/lib/qmd-ignore.tsnew file mode 100644index 0000000..ebd6b64--- /dev/null+++ b/.claude/scripts/lib/qmd-ignore.ts@@ -0,0 +1,194 @@+/**+ * Sync `.obsidian/app.json` userIgnoreFilters into QMD's per-index YAML+ * config so both engines hide the same files from search. Called during+ * bootstrap; the QMD mid-session refresh hook picks up the result the next+ * time `qmd update` runs (which reads the YAML on every invocation).+ *+ * Split into a pure YAML transform (`upsertIgnoreInYaml`) plus file-IO+ * wrappers (`readObsidianIgnore`, `writeQmdIgnore`, `qmdConfigPath`) so the+ * surgical YAML editing logic is unit-testable without temp files.+ *+ * The YAML surgery is a targeted regex edit rather than a full YAML rewrite:+ * QMD owns the file schema and exposes advanced fields (update command,+ * includeByDefault) we don't want to silently strip on round-trip.+ */++import { readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import { warn } from "./hook-io.ts";+import { escapeRegex } from "./regex.ts";++/**+ * YAML indent widths used by QMD's serializer. Defined once here so the strip+ * regex, header regex, and block builder all use the same values — a schema+ * change only needs to update these constants.+ */+const COLLECTION_INDENT = " "; // 2 spaces — ` <collection-name>:`+const FIELD_INDENT = " "; // 4 spaces — ` pattern: …`, ` ignore:`+const LIST_ITEM_INDENT = " "; // 6 spaces — ` - pattern`++/**+ * Matches a full `ignore:` block inside a QMD collection entry: the field-indent+ * `ignore:` header plus one or more list-item-indent entries. Used to strip any+ * existing block before re-injecting, keeping the YAML transform idempotent.+ */+const IGNORE_BLOCK_RE = new RegExp(+ `^${FIELD_INDENT}ignore:\\n(?:${LIST_ITEM_INDENT}- .*\\n)+`,+ "gm",+);++/**+ * Obsidian's app.json `userIgnoreFilters` is the single source of truth for+ * what's hidden from both Obsidian and QMD search. Bootstrap reads it and+ * writes the patterns to the QMD YAML so `qmd update` skips the same files.+ *+ * Returns:+ * - `[]` when the file is absent (ENOENT) or present but has no filters.+ * These are the "user has no ignore list" cases — correct to treat alike.+ * - `null` when the file exists but can't be read or parsed (bad JSON,+ * permission error, I/O). Coercing these to `[]` would silently cause+ * `writeQmdIgnore([])` to strip an existing QMD ignore block on the next+ * bootstrap run — a user typo in app.json should not re-expose previously+ * hidden files. Callers MUST treat null as "skip propagation, leave the+ * YAML alone." A warn() is emitted so the drift is visible.+ *+ * Path defaults to `.obsidian/app.json` resolved against the current working+ * directory — the script is expected to run from the vault root. Tests inject+ * a temp path through the parameter.+ */+export function readObsidianIgnore(+ appJsonPath: string = ".obsidian/app.json",+): readonly string[] | null {+ let raw: string;+ try {+ raw = readFileSync(appJsonPath, "utf-8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ warn(+ `Failed to read ${appJsonPath}: ${(err as Error).message}. Skipping ignore propagation to avoid clearing the existing QMD ignore list.`,+ );+ return null;+ }+ let parsed: { userIgnoreFilters?: unknown };+ try {+ parsed = JSON.parse(raw) as { userIgnoreFilters?: unknown };+ } catch (err) {+ warn(+ `Failed to parse ${appJsonPath}: ${(err as Error).message}. Skipping ignore propagation to avoid clearing the existing QMD ignore list.`,+ );+ return null;+ }+ const filters = parsed.userIgnoreFilters;+ if (!Array.isArray(filters)) return [];+ return filters.filter((v): v is string => typeof v === "string");+}++/**+ * Translate one Obsidian `userIgnoreFilters` entry into a fastGlob pattern.+ *+ * Obsidian's format: plain strings match as "path startsWith"; strings wrapped+ * in `/…/` are regex. fastGlob (QMD's walker) doesn't speak regex, so regex+ * entries return null and the caller drops them. Plain filenames pass through+ * — they match identically in both engines. A bare `foo/` becomes `foo/**`+ * so glob semantics cover everything under the folder.+ */+export function translateToGlob(pattern: string): string | null {+ if (pattern.startsWith("/") && pattern.endsWith("/") && pattern.length > 1) {+ return null;+ }+ if (pattern.endsWith("/")) return `${pattern}**`;+ return pattern;+}++export function qmdConfigPath(indexName: string): string {+ return join(homedir(), ".config", "qmd", `${indexName}.yml`);+}++/**+ * Pure YAML transform: given the current file content, return new content with+ * the named collection's `ignore:` block set to the supplied patterns. Empty+ * patterns strips the block within that collection only. Returns null when the+ * named collection isn't present — distinct from "no change needed" so callers+ * can warn on drift.+ *+ * The strip-and-reinject is scoped to the target collection's block, bounded+ * by the next sibling-collection header or EOF. A naive global strip would+ * silently delete ignore entries from unrelated collections in the same+ * per-index YAML (QMD allows multi-collection configs), which would be silent+ * data loss on every bootstrap run.+ */+export function upsertIgnoreInYaml(+ content: string,+ collectionName: string,+ patterns: readonly string[],+): string | null {+ // Match the entire target collection block: its header line plus every+ // subsequent line that is NOT another sibling-collection header (2-space+ // indent + non-space). The negative lookahead keeps the match scoped to+ // this collection only.+ const blockRe = new RegExp(+ `^${COLLECTION_INDENT}${escapeRegex(collectionName)}:\\n(?:(?!^${COLLECTION_INDENT}\\S).*\\n)*`,+ "m",+ );+ const match = blockRe.exec(content);+ if (!match) return null;+ const blockStart = match.index;+ const blockEnd = blockStart + match[0].length;+ let block = match[0];++ // Strip any existing ignore: block within THIS collection only. Other+ // collections in the same file keep whatever they had.+ block = block.replace(IGNORE_BLOCK_RE, "");++ if (patterns.length > 0) {+ const patternLineRe = new RegExp(+ `(^${FIELD_INDENT}pattern: [^\\n]*\\n)`,+ "m",+ );+ if (!patternLineRe.test(block)) return null;+ const injected =+ `${FIELD_INDENT}ignore:\n` ++ patterns+ .map((p) => `${LIST_ITEM_INDENT}- ${JSON.stringify(p)}`)+ .join("\n") ++ "\n";+ block = block.replace(patternLineRe, `$1${injected}`);+ }++ return content.slice(0, blockStart) + block + content.slice(blockEnd);+}++/**+ * File-IO wrapper around upsertIgnoreInYaml. Reports via stderr when the+ * config file is missing or the named collection isn't present so bootstrap+ * runs surface configuration drift without aborting.+ */+export function writeQmdIgnore(+ configPath: string,+ collectionName: string,+ patterns: readonly string[],+): boolean {+ let before: string;+ try {+ before = readFileSync(configPath, "utf-8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {+ warn(+ `QMD config not found at ${configPath}; skipping ignore propagation.`,+ );+ return false;+ }+ throw err;+ }+ const next = upsertIgnoreInYaml(before, collectionName, patterns);+ if (next === null) {+ warn(+ `Could not locate collection '${collectionName}' in ${configPath}; ignore not applied.`,+ );+ return false;+ }+ if (next !== before) writeFileSync(configPath, next, "utf-8");+ return true;+}diff --git a/.claude/scripts/lib/regex.ts b/.claude/scripts/lib/regex.tsnew file mode 100644index 0000000..c1259eb--- /dev/null+++ b/.claude/scripts/lib/regex.ts@@ -0,0 +1,11 @@+/**+ * Small regex utilities used across scripts and hooks.+ */++/**+ * Escape regex metacharacters in a string so it can be embedded safely+ * inside a `new RegExp(...)` pattern as a literal.+ */+export function escapeRegex(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.tsindex 9a6e88f..4fd4d7b 100644--- a/.claude/scripts/lib/session-start.ts+++ b/.claude/scripts/lib/session-start.ts@@ -4,6 +4,8 @@* system, or invoking the Obsidian CLI.*/+import { escapeRegex } from "./regex.ts";+export function take(stdout: string, n: number): string {return stdout.split("\n").slice(0, n).join("\n");}@@ -62,14 +64,6 @@ export function isSkippedPath();}-/**- * Escape regex metacharacters in a string so it can be embedded safely- * inside a `new RegExp(...)` pattern as a literal.- */-function escapeRegex(s: string): string {- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");-}-/*** Find the closing `---` delimiter of a YAML frontmatter block. The input* is assumed to start with `---` (caller checks). Returns the index of thediff --git a/.claude/scripts/pre-compact.ts b/.claude/scripts/pre-compact.tsindex cb411fe..bc2daa4 100644--- a/.claude/scripts/pre-compact.ts+++ b/.claude/scripts/pre-compact.ts@@ -18,6 +18,7 @@ import {import { dirname, join, resolve as resolvePath } from "node:path";import { fileURLToPath } from "node:url";import { debug, readStdinJson } from "./lib/hook-io.ts";+import { isMainModule } from "./lib/main-guard.ts";import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";type HookInput = {@@ -58,10 +59,7 @@ export function pruneBackups(dir: string, retain: number): void {}}-// Only run main when invoked as a script (not when imported by tests).-// fileURLToPath handles the file:// prefix and any URL-encoded segments;-// process.argv[1] is already the absolute resolved script path at invocation.-if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {+if (isMainModule(import.meta.url)) {const input = await readStdinJson<HookInput>();if (!input) process.exit(0);diff --git a/.claude/scripts/tests/_helpers.ts b/.claude/scripts/tests/_helpers.tsindex cae0b0d..2e08a2a 100644--- a/.claude/scripts/tests/_helpers.ts+++ b/.claude/scripts/tests/_helpers.ts@@ -5,9 +5,19 @@* `node --experimental-strip-types <script>` with JSON on stdin. Used by* classify-message.test.ts and validate-write.test.ts to exercise the* full stdin → stdout pipeline under the real runtime.+ *+ * hostPath normalizes POSIX-style literal test paths (e.g. `"/Users/x/foo"`)+ * to the host platform via path.resolve. Needed on Windows, where the raw+ * string is treated as drive-relative and pathToFileURL prepends the current+ * drive letter — so a round trip stops matching the literal argv[1] value.*/import { spawnSync } from "node:child_process";+import { resolve } from "node:path";++export function hostPath(literal: string): string {+ return resolve(literal);+}export type RunResult = {readonly stdout: string;diff --git a/.claude/scripts/tests/frontmatter.test.ts b/.claude/scripts/tests/frontmatter.test.tsindex 8c1cbe4..3f67555 100644--- a/.claude/scripts/tests/frontmatter.test.ts+++ b/.claude/scripts/tests/frontmatter.test.ts@@ -25,8 +25,14 @@ describe("shouldSkipFile — skip rules", () => {test("skips CHANGELOG.md", () => {assert.equal(shouldSkipFile("/some/path/CHANGELOG.md"), true);});- test("skips CLAUDE / AGENTS / GEMINI / CONTRIBUTING", () => {- for (const f of ["CLAUDE.md", "AGENTS.md", "GEMINI.md", "CONTRIBUTING.md"]) {+ test("skips CLAUDE / AGENTS / GEMINI / CONTRIBUTING / ARCHITECTURE", () => {+ for (const f of [+ "CLAUDE.md",+ "AGENTS.md",+ "GEMINI.md",+ "CONTRIBUTING.md",+ "ARCHITECTURE.md",+ ]) {assert.equal(shouldSkipFile(`/vault/${f}`), true);}});diff --git a/.claude/scripts/tests/hook-io.test.ts b/.claude/scripts/tests/hook-io.test.tsnew file mode 100644index 0000000..058bd11--- /dev/null+++ b/.claude/scripts/tests/hook-io.test.ts@@ -0,0 +1,85 @@+/**+ * Unit tests for lib/hook-io — stderr helpers shared across hooks and scripts.+ * readStdinJson is exercised via integration tests; here we lock the tiny+ * stderr formatters so message shape stays consistent.+ */++import { test, describe, afterEach } from "node:test";+import assert from "node:assert/strict";++import { debug, warn } from "../lib/hook-io.ts";++/**+ * Replace process.stderr.write with a capturer that records calls and returns+ * true (matching the real write() signature). Returns a restorer that+ * reinstates the original, plus the captured lines.+ */+function captureStderr(): {+ lines: string[];+ restore: () => void;+} {+ const lines: string[] = [];+ const original = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => {+ lines.push(typeof chunk === "string" ? chunk : chunk.toString());+ return true;+ }) as typeof process.stderr.write;+ return { lines, restore: () => (process.stderr.write = original) };+}++describe("warn", () => {+ let capture: ReturnType<typeof captureStderr>;++ afterEach(() => capture?.restore());++ test("prefixes the message with ` ⚠ ` and appends a newline", () => {+ capture = captureStderr();+ warn("something went wrong");+ assert.deepEqual(capture.lines, [" ⚠ something went wrong\n"]);+ });++ test("writes nothing else when called with empty string", () => {+ capture = captureStderr();+ warn("");+ assert.deepEqual(capture.lines, [" ⚠ \n"]);+ });+});++describe("debug", () => {+ const originalFlag = process.env["HOOK_DEBUG"];+ let capture: ReturnType<typeof captureStderr>;++ afterEach(() => {+ capture?.restore();+ if (originalFlag === undefined) {+ delete process.env["HOOK_DEBUG"];+ } else {+ process.env["HOOK_DEBUG"] = originalFlag;+ }+ });++ test("silent when HOOK_DEBUG is unset", () => {+ delete process.env["HOOK_DEBUG"];+ capture = captureStderr();+ debug("should not appear");+ assert.deepEqual(capture.lines, []);+ });++ test("silent when HOOK_DEBUG is not exactly '1'", () => {+ process.env["HOOK_DEBUG"] = "true";+ capture = captureStderr();+ debug("should not appear");+ assert.deepEqual(capture.lines, []);+ });++ test("writes a tagged line to stderr when HOOK_DEBUG=1", () => {+ process.env["HOOK_DEBUG"] = "1";+ capture = captureStderr();+ debug("taking path A");+ assert.equal(capture.lines.length, 1);+ assert.match(+ capture.lines[0] ?? "",+ /^\[hook-debug \d{4}-\d{2}-\d{2}T[^\]]+\] taking path A\n$/,+ );+ });+});diff --git a/.claude/scripts/tests/main-guard.test.ts b/.claude/scripts/tests/main-guard.test.tsnew file mode 100644index 0000000..d46b6be--- /dev/null+++ b/.claude/scripts/tests/main-guard.test.ts@@ -0,0 +1,59 @@+/**+ * Unit tests for lib/main-guard — detect direct-script invocation vs import.+ *+ * The function compares `fileURLToPath(importMetaUrl)` against `process.argv[1]`.+ * We can't mutate `import.meta.url`, but we can pass a synthetic value and+ * stage `process.argv[1]` to cover the matrix.+ */++import { test, describe, afterEach } from "node:test";+import assert from "node:assert/strict";+import { pathToFileURL } from "node:url";++import { isMainModule } from "../lib/main-guard.ts";+import { hostPath } from "./_helpers.ts";++const ORIGINAL_ARGV1: string | undefined = process.argv[1];++afterEach(() => {+ // Restore argv so a failing test can't cascade into unrelated ones.+ if (ORIGINAL_ARGV1 === undefined) {+ process.argv.length = 1;+ } else {+ process.argv[1] = ORIGINAL_ARGV1;+ }+});++describe("isMainModule", () => {+ test("true when argv[1] matches the module path", () => {+ const path = hostPath("/Users/dev/scripts/foo.ts");+ process.argv[1] = path;+ assert.equal(isMainModule(pathToFileURL(path).href), true);+ });++ test("false when argv[1] differs from the module path", () => {+ process.argv[1] = hostPath("/Users/dev/scripts/other.ts");+ assert.equal(+ isMainModule(pathToFileURL(hostPath("/Users/dev/scripts/foo.ts")).href),+ false,+ );+ });++ test("false when argv[1] is undefined (node -e or repl)", () => {+ // Truncating argv represents the absent-entry case from node -e / repl+ // without tripping tsc's rejection of `delete` on non-optional indexes.+ process.argv.length = 1;+ assert.equal(+ isMainModule(pathToFileURL(hostPath("/Users/dev/scripts/foo.ts")).href),+ false,+ );+ });++ test("handles URL-encoded segments (spaces in path)", () => {+ const path = hostPath("/Users/dev/my scripts/foo.ts");+ process.argv[1] = path;+ // pathToFileURL encodes the space as %20; isMainModule must decode+ // before comparing against the raw argv path.+ assert.equal(isMainModule(pathToFileURL(path).href), true);+ });+});diff --git a/.claude/scripts/tests/qmd-ignore.test.ts b/.claude/scripts/tests/qmd-ignore.test.tsnew file mode 100644index 0000000..19998bd--- /dev/null+++ b/.claude/scripts/tests/qmd-ignore.test.ts@@ -0,0 +1,343 @@+/**+ * Unit tests for lib/qmd-ignore — ignore-propagation helpers. The functions+ * are pure (readObsidianIgnore, translateToGlob, upsertIgnoreInYaml) plus one+ * file-IO wrapper (writeQmdIgnore) that we exercise against tmp files.+ *+ * The bootstrap itself is an integration seam (spawns qmd subprocesses) and is+ * covered by the manual re-run during release; these tests lock the contracts+ * that make the seam correct.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ readObsidianIgnore,+ translateToGlob,+ upsertIgnoreInYaml,+ writeQmdIgnore,+ qmdConfigPath,+} from "../lib/qmd-ignore.ts";++const YAML_BASE = `collections:+ obsidian-mind:+ path: /Users/dev/obsidian-mind+ pattern: "**/*.md"+ context:+ "": "Engineer's work vault"+`;++const YAML_WITH_IGNORE = `collections:+ obsidian-mind:+ path: /Users/dev/obsidian-mind+ pattern: "**/*.md"+ ignore:+ - "ARCHITECTURE.md"+ - "CHANGELOG.md"+ context:+ "": "Engineer's work vault"+`;++describe("translateToGlob", () => {+ test("plain filename passes through unchanged", () => {+ assert.equal(translateToGlob("ARCHITECTURE.md"), "ARCHITECTURE.md");+ });++ test("glob with wildcard passes through unchanged", () => {+ assert.equal(translateToGlob("**/draft-*.md"), "**/draft-*.md");+ });++ test("trailing-slash folder expands to recursive glob", () => {+ assert.equal(translateToGlob("work/"), "work/**");+ assert.equal(translateToGlob("perf/brag/"), "perf/brag/**");+ });++ test("regex pattern (/.../) returns null to be dropped by caller", () => {+ assert.equal(translateToGlob("/README\\..*\\.md/"), null);+ assert.equal(translateToGlob("/draft/"), null);+ });++ test("single '/' is not treated as regex", () => {+ // A one-character '/' at start + end is the same character; guarding+ // on length avoids false-positive regex detection.+ assert.equal(translateToGlob("/"), "/**");+ });++ test("empty string passes through unchanged", () => {+ assert.equal(translateToGlob(""), "");+ });+});++describe("readObsidianIgnore", () => {+ const tmp = mkdtempSync(join(tmpdir(), "qmd-bootstrap-obsidian-"));++ test.after(() => rmSync(tmp, { recursive: true, force: true }));++ test("missing file (ENOENT) returns empty array — user has no filters", () => {+ assert.deepEqual(readObsidianIgnore(join(tmp, "does-not-exist.json")), []);+ });++ test("valid file returns the patterns array", () => {+ const path = join(tmp, "valid.json");+ writeFileSync(+ path,+ JSON.stringify({ userIgnoreFilters: ["ARCHITECTURE.md", "foo/"] }),+ );+ assert.deepEqual(readObsidianIgnore(path), ["ARCHITECTURE.md", "foo/"]);+ });++ test("missing userIgnoreFilters field returns empty array", () => {+ const path = join(tmp, "empty.json");+ writeFileSync(path, JSON.stringify({ otherField: "x" }));+ assert.deepEqual(readObsidianIgnore(path), []);+ });++ test("userIgnoreFilters not an array returns empty array", () => {+ const path = join(tmp, "not-array.json");+ writeFileSync(path, JSON.stringify({ userIgnoreFilters: "not an array" }));+ assert.deepEqual(readObsidianIgnore(path), []);+ });++ test("non-string array entries are dropped", () => {+ const path = join(tmp, "mixed.json");+ writeFileSync(+ path,+ JSON.stringify({ userIgnoreFilters: ["ok.md", 42, null, "also-ok.md"] }),+ );+ assert.deepEqual(readObsidianIgnore(path), ["ok.md", "also-ok.md"]);+ });++ test("malformed JSON returns null so the caller skips propagation", () => {+ // Coercing a parse error to [] would cause writeQmdIgnore([]) to strip+ // the existing QMD ignore block — a user typo in app.json shouldn't+ // silently re-expose hidden files. null signals "skip, leave YAML."+ const path = join(tmp, "broken.json");+ writeFileSync(path, "{not valid json");+ assert.equal(readObsidianIgnore(path), null);+ });+});++describe("upsertIgnoreInYaml — pure transform", () => {+ test("injects ignore block after pattern line in clean YAML", () => {+ const next = upsertIgnoreInYaml(YAML_BASE, "obsidian-mind", [+ "ARCHITECTURE.md",+ ]);+ assert.ok(next !== null);+ assert.ok(next.includes(' ignore:\n - "ARCHITECTURE.md"\n'));+ // Block sits between pattern and context — preserves schema order.+ const patternIdx = next.indexOf(' pattern: "**/*.md"');+ const ignoreIdx = next.indexOf(" ignore:");+ const contextIdx = next.indexOf(" context:");+ assert.ok(patternIdx < ignoreIdx && ignoreIdx < contextIdx);+ });++ test("re-running with the same patterns is idempotent", () => {+ const once = upsertIgnoreInYaml(YAML_BASE, "obsidian-mind", [+ "ARCHITECTURE.md",+ ]);+ assert.ok(once !== null);+ const twice = upsertIgnoreInYaml(once, "obsidian-mind", [+ "ARCHITECTURE.md",+ ]);+ assert.equal(twice, once);+ });++ test("re-running with different patterns replaces the block", () => {+ const first = upsertIgnoreInYaml(YAML_BASE, "obsidian-mind", [+ "ARCHITECTURE.md",+ ]);+ assert.ok(first !== null);+ const second = upsertIgnoreInYaml(first, "obsidian-mind", [+ "CHANGELOG.md",+ ]);+ assert.ok(second !== null);+ assert.ok(second.includes(' - "CHANGELOG.md"'));+ assert.ok(!second.includes(' - "ARCHITECTURE.md"'));+ // Only one ignore: block in the file.+ assert.equal(second.match(/^ ignore:$/gm)?.length, 1);+ });++ test("empty patterns strips existing ignore block", () => {+ const next = upsertIgnoreInYaml(YAML_WITH_IGNORE, "obsidian-mind", []);+ assert.ok(next !== null);+ assert.ok(!next.includes(" ignore:"));+ // Preserves the other fields intact.+ assert.ok(next.includes(' pattern: "**/*.md"'));+ assert.ok(next.includes(" context:"));+ });++ test("unknown collection returns null (distinct from 'no change needed')", () => {+ assert.equal(+ upsertIgnoreInYaml(YAML_BASE, "other-name", ["ARCHITECTURE.md"]),+ null,+ );+ });++ test("patterns with special regex chars in name are safely quoted", () => {+ // Backslashes and brackets inside the pattern must not break the+ // surrounding regex used to locate the collection header.+ const next = upsertIgnoreInYaml(YAML_BASE, "obsidian-mind", [+ "path[with].weird*chars.md",+ ]);+ assert.ok(next !== null);+ assert.ok(next.includes(' - "path[with].weird*chars.md"'));+ });++ test("multi-collection YAML only targets the named collection", () => {+ const multi = `collections:+ other-vault:+ path: /other+ pattern: "**/*.md"+ context:+ "": "other"+ obsidian-mind:+ path: /mine+ pattern: "**/*.md"+ context:+ "": "mine"+`;+ const next = upsertIgnoreInYaml(multi, "obsidian-mind", [+ "ARCHITECTURE.md",+ ]);+ assert.ok(next !== null);+ // Only one ignore block added.+ assert.equal(next.match(/^ ignore:$/gm)?.length, 1);+ // The block is inside obsidian-mind, not other-vault.+ const obsidianMindStart = next.indexOf(" obsidian-mind:");+ const ignoreIdx = next.indexOf(" ignore:");+ assert.ok(ignoreIdx > obsidianMindStart);+ });++ test("preserves other collections' existing ignore blocks when editing one", () => {+ // Regression test: a previous version used a global IGNORE_BLOCK_RE+ // strip that would silently delete other-vault's ignore entries on+ // every bootstrap run against a multi-collection file.+ const multi = `collections:+ other-vault:+ path: /other+ pattern: "**/*.md"+ ignore:+ - "SECRETS.md"+ - "private/"+ context:+ "": "other"+ obsidian-mind:+ path: /mine+ pattern: "**/*.md"+ context:+ "": "mine"+`;+ const next = upsertIgnoreInYaml(multi, "obsidian-mind", [+ "ARCHITECTURE.md",+ ]);+ assert.ok(next !== null);+ // other-vault's ignore list is untouched.+ assert.ok(next.includes(' - "SECRETS.md"'));+ assert.ok(next.includes(' - "private/"'));+ // obsidian-mind got its own ignore block.+ assert.ok(next.includes(' - "ARCHITECTURE.md"'));+ // Exactly two ignore blocks in the file (one per collection).+ assert.equal(next.match(/^ ignore:$/gm)?.length, 2);+ });++ test("empty patterns strips only the target collection's ignore block", () => {+ const multi = `collections:+ other-vault:+ path: /other+ pattern: "**/*.md"+ ignore:+ - "SECRETS.md"+ context:+ "": "other"+ obsidian-mind:+ path: /mine+ pattern: "**/*.md"+ ignore:+ - "ARCHITECTURE.md"+ context:+ "": "mine"+`;+ const next = upsertIgnoreInYaml(multi, "obsidian-mind", []);+ assert.ok(next !== null);+ // other-vault's ignore survives.+ assert.ok(next.includes(' - "SECRETS.md"'));+ // obsidian-mind's ignore was stripped.+ assert.ok(!next.includes(' - "ARCHITECTURE.md"'));+ // Exactly one ignore block remains.+ assert.equal(next.match(/^ ignore:$/gm)?.length, 1);+ });+});++describe("writeQmdIgnore — file IO wrapper", () => {+ const tmp = mkdtempSync(join(tmpdir(), "qmd-bootstrap-yaml-"));++ test.after(() => rmSync(tmp, { recursive: true, force: true }));++ test("writes the transformed YAML when patterns are non-empty", () => {+ const path = join(tmp, "write.yml");+ writeFileSync(path, YAML_BASE);+ const ok = writeQmdIgnore(path, "obsidian-mind", ["ARCHITECTURE.md"]);+ assert.equal(ok, true);+ const after = readFileSync(path, "utf-8");+ assert.ok(after.includes(' ignore:\n - "ARCHITECTURE.md"\n'));+ });++ test("is idempotent: second call with same patterns doesn't change bytes", () => {+ const path = join(tmp, "idempotent.yml");+ writeFileSync(path, YAML_BASE);+ writeQmdIgnore(path, "obsidian-mind", ["ARCHITECTURE.md"]);+ const first = readFileSync(path, "utf-8");+ writeQmdIgnore(path, "obsidian-mind", ["ARCHITECTURE.md"]);+ const second = readFileSync(path, "utf-8");+ assert.equal(second, first);+ });++ test("empty patterns on a file with existing block strips it", () => {+ const path = join(tmp, "strip.yml");+ writeFileSync(path, YAML_WITH_IGNORE);+ const ok = writeQmdIgnore(path, "obsidian-mind", []);+ assert.equal(ok, true);+ const after = readFileSync(path, "utf-8");+ assert.ok(!after.includes(" ignore:"));+ });++ test("empty patterns on a file with no block is a no-op", () => {+ const path = join(tmp, "noop.yml");+ writeFileSync(path, YAML_BASE);+ const ok = writeQmdIgnore(path, "obsidian-mind", []);+ assert.equal(ok, true);+ assert.equal(readFileSync(path, "utf-8"), YAML_BASE);+ });++ test("missing file returns false (no throw)", () => {+ const ok = writeQmdIgnore(+ join(tmp, "does-not-exist.yml"),+ "obsidian-mind",+ ["ARCHITECTURE.md"],+ );+ assert.equal(ok, false);+ });++ test("unknown collection returns false and leaves file unchanged", () => {+ const path = join(tmp, "unknown.yml");+ writeFileSync(path, YAML_BASE);+ const ok = writeQmdIgnore(path, "not-a-collection", ["ARCHITECTURE.md"]);+ assert.equal(ok, false);+ assert.equal(readFileSync(path, "utf-8"), YAML_BASE);+ });+});++describe("qmdConfigPath", () => {+ test("composes path from homedir, .config/qmd, and index name", () => {+ const p = qmdConfigPath("obsidian-mind");+ // Normalize separators so the assertion works on both POSIX (`/`) and+ // Windows (`\`). path.join picks the platform-native separator.+ const normalized = p.replaceAll("\\", "/");+ assert.ok(normalized.endsWith("/.config/qmd/obsidian-mind.yml"));+ // Absolute path, not relative.+ assert.ok(p.startsWith("/") || /^[A-Za-z]:[/\\]/.test(p));+ });+});diff --git a/.claude/scripts/tests/regex.test.ts b/.claude/scripts/tests/regex.test.tsnew file mode 100644index 0000000..a1a6a43--- /dev/null+++ b/.claude/scripts/tests/regex.test.ts@@ -0,0 +1,48 @@+/**+ * Unit tests for lib/regex — regex metacharacter escaping.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";++import { escapeRegex } from "../lib/regex.ts";++describe("escapeRegex", () => {+ test("passes plain letters and digits unchanged", () => {+ assert.equal(escapeRegex("abcXYZ123"), "abcXYZ123");+ });++ test("escapes every regex metacharacter", () => {+ // All 13 special chars from the escape class: . * + ? ^ $ { } ( ) | [ ] \+ assert.equal(+ escapeRegex(".*+?^${}()|[]\\"),+ "\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\",+ );+ });++ test("escaped output is safe inside new RegExp()", () => {+ const literal = "a.b*c+d?";+ const re = new RegExp(escapeRegex(literal));+ assert.ok(re.test("a.b*c+d?"));+ assert.ok(!re.test("axbXcYdZ"));+ });++ test("preserves non-meta characters adjacent to meta characters", () => {+ assert.equal(escapeRegex("foo.bar"), "foo\\.bar");+ assert.equal(escapeRegex("a(b)c"), "a\\(b\\)c");+ });++ test("empty string passes through unchanged", () => {+ assert.equal(escapeRegex(""), "");+ });++ test("already-escaped sequences get double-escaped (literal preservation)", () => {+ // Input is the literal two-character sequence backslash-dot.+ // Both characters are meta; both must be escaped so the resulting+ // regex matches a literal backslash followed by a literal dot.+ assert.equal(escapeRegex("\\."), "\\\\\\.");+ const re = new RegExp(escapeRegex("\\."));+ assert.ok(re.test("\\."));+ assert.ok(!re.test("."));+ });+});diff --git a/.claude/skills/qmd/SKILL.md b/.claude/skills/qmd/SKILL.mdindex b8c5f94..6ac4865 100644--- a/.claude/skills/qmd/SKILL.md+++ b/.claude/skills/qmd/SKILL.md@@ -1,12 +1,22 @@---name: qmd-description: "Search the vault using QMD semantic search. Use PROACTIVELY before reading files directly — whenever the user asks about past decisions, incidents, people, meetings, architecture, patterns, or any vault content. Always prefer QMD over Grep/Glob for vault queries. Also use after creating/editing notes to check for duplicates and related content."+description: "Search the vault using QMD semantic search. Use PROACTIVELY before reading files. Preference order: (1) MCP tools — mcp__qmd__query, mcp__qmd__get, mcp__qmd__multi_get, mcp__qmd__status — if they appear in your tool menu, use them first; (2) CLI `qmd --index <name> ...` as fallback; (3) Grep/Glob only when QMD is not installed. Trigger proactively for past decisions, incidents, people, meetings, architecture, patterns, or any vault content — and after creating/editing notes to check for duplicates and related content."---# QMD — Vault Semantic SearchBefore reading vault files directly, search with QMD first. It returns relevant snippets without burning context on full file reads.+## Tool Surfaces — Preference Order++Pick the highest surface available and stop. All three read the same SQLite store (scoped by `qmd_index` in `vault-manifest.json`), so they return the same results; the choice is about interface ergonomics and context cost.++1. **MCP tools (preferred when registered)** — `mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, `mcp__qmd__status`. If these appear in your tool menu, the MCP server is live and pre-scoped to this vault. Call them directly — no `--index` argument needed, no shell involved, typed arguments. This is the intended path during a session.+2. **CLI fallback** — `qmd --index <name> query|search|vsearch|get|multi-get`. Use when the MCP server isn't registered (older vault clones, Windows install drift, disabled in `.mcp.json`), or for one-off shell checks outside a session. Always pass `--index <name>`.+3. **Grep / Glob / Read** — last resort, only when QMD is not installed at all. These burn context on full file reads and don't rank by relevance.++Never fall through surfaces without cause — if MCP is registered, calling the CLI in a Bash tool is just a slower path to the same result.+## Named Index (This Vault)This vault declares a **named QMD index** in `vault-manifest.json` under `qmd_index`. Every QMD command in this document uses `--index <name>` so queries, updates, and context strings stay scoped to this vault — not blended with any other vault that shares the machine.@@ -28,18 +38,20 @@ In-session, substitute the value of `qmd_index` directly in your commands (the i## Commands+Each operation lists the MCP call first, then the CLI equivalent. Prefer MCP when available.+### Search (pick one per query)-- `qmd --index <name> query "..." --json -n 10` — Best quality. Hybrid BM25 + vector + LLM reranking. Use for complex or conceptual queries.-- `qmd --index <name> search "..." --json -n 10` — Fast BM25 keyword. Use for exact terms, names, ticket numbers, dates.-- `qmd --index <name> vsearch "..." --json -n 5` — Semantic only. Use for exploratory queries where you don't know the exact words.+- **Hybrid (best quality)** — `mcp__qmd__query` with `searches=[{type:"lex", query:"..."}, {type:"vec", query:"..."}]` and an `intent` arg. CLI: `qmd --index <name> query "..." --json -n 10`. Use for complex or conceptual queries.+- **Keyword (fast BM25)** — `mcp__qmd__query` with `searches=[{type:"lex", query:"..."}]`. CLI: `qmd --index <name> search "..." --json -n 10`. Use for exact terms, names, ticket numbers, dates.+- **Semantic only** — `mcp__qmd__query` with `searches=[{type:"vec", query:"..."}]`. CLI: `qmd --index <name> vsearch "..." --json -n 5`. Use for exploratory queries where you don't know the exact words.### Retrieve-- `qmd --index <name> get "path/to/file.md"` — Full document by path.-- `qmd --index <name> get "#docid"` — Full document by ID (from search results).-- `qmd --index <name> multi-get "org/people/*.md" --json -l 40` — Batch retrieve by glob pattern.+- **By path** — `mcp__qmd__get` with `path` arg. CLI: `qmd --index <name> get "path/to/file.md"`.+- **By docid** — `mcp__qmd__get` with `#abc123` syntax. CLI: `qmd --index <name> get "#docid"`.+- **Batch by glob** — `mcp__qmd__multi_get` with `pattern` arg. CLI: `qmd --index <name> multi-get "org/people/*.md" --json -l 40`.-### Index Management-- `qmd --index <name> update` — Re-index after file changes (fast, ~1-2s incremental). The SessionStart hook runs this automatically.+### Index Management (CLI only — MCP exposes read surfaces)+- `qmd --index <name> update` — Re-index after file changes (fast, ~1-2s incremental). The SessionStart hook and the PostToolUse debounced refresh both run this automatically; manual invocation is rarely needed.- `qmd --index <name> embed` — Regenerate vector embeddings (slower, run after bulk changes).## Bootstrap (Fresh Clone)@@ -53,17 +65,16 @@ node --experimental-strip-types scripts/qmd-bootstrap.tsIt reads `qmd_index` and `qmd_context` from `vault-manifest.json`, registers the collection, attaches the vault context, walks the vault, and generates embeddings. Idempotent — safe to re-run.## When to Search-- User mentions a past decision, incident, person, project → `qmd --index <name> query`-- User asks "what did we decide about X" → `qmd --index <name> query`-- User mentions a person by name → `qmd --index <name> search "<name>"`-- Before creating a new note → `qmd --index <name> vsearch "<topic>"` to check for existing content-- After creating a note → `qmd --index <name> vsearch "<note title>"` to find notes that should link to it-- Loading context for review prep → `qmd --index <name> multi-get "perf/evidence/*.md"`-- Loading 1-on-1 context → `qmd --index <name> search "<person name> 1-1"`-## After Bulk Changes-Run `qmd --index <name> update && qmd --index <name> embed` to keep the index fresh. The SessionStart hook does `qmd --index <name> update` automatically, but `qmd --index <name> embed` should be run explicitly after sessions that create many notes.+Each case lists the preferred MCP call; fall back to the CLI equivalent if MCP isn't registered.-## MCP Server+- User mentions a past decision, incident, person, project → `mcp__qmd__query` (hybrid).+- User asks "what did we decide about X" → `mcp__qmd__query` (hybrid with `intent` describing the decision context).+- User mentions a person by name → `mcp__qmd__query` with `searches=[{type:"lex", query:"<name>"}]`.+- Before creating a new note → `mcp__qmd__query` with `searches=[{type:"vec", query:"<topic>"}]` to check for existing content.+- After creating a note → `mcp__qmd__query` with `searches=[{type:"vec", query:"<note title>"}]` to find notes that should link to it.+- Loading context for review prep → `mcp__qmd__multi_get` with `pattern="perf/evidence/*.md"`.+- Loading 1-on-1 context → `mcp__qmd__query` with `searches=[{type:"lex", query:"<person name> 1-1"}]`.-`.mcp.json` wires QMD as an MCP server via `.claude/scripts/qmd-mcp.mjs` — a Node wrapper that bypasses the Windows npm shim and scopes the server to the same `qmd_index`. The `qmd` tools (`query`, `search`, `vsearch`, `get`, `multi-get`) appear in the Claude Code tool menu when QMD is installed. No per-query `--index` argument needed through the MCP — it's already scoped by the wrapper.+## After Bulk Changes+Run `qmd --index <name> update && qmd --index <name> embed` in the shell. The SessionStart hook and the PostToolUse debounced refresh run `update` automatically, but `embed` should be run explicitly after sessions that create many notes.diff --git a/.github/scripts/generate-changelog.ts b/.github/scripts/generate-changelog.tsindex 8276478..2b7a59d 100644--- a/.github/scripts/generate-changelog.ts+++ b/.github/scripts/generate-changelog.ts@@ -12,8 +12,10 @@*/import { spawnSync } from "node:child_process";-import { fileURLToPath } from "node:url";import { readFileSync, writeFileSync } from "node:fs";++import { isMainModule } from "../../.claude/scripts/lib/main-guard.ts";+import { escapeRegex } from "../../.claude/scripts/lib/regex.ts";import { isCovered } from "./manifest-check.ts";const PREFIX_MAP: Readonly<Record<string, string>> = {@@ -123,10 +125,6 @@ export function generateSection(version: string, commits: readonly string[]): streturn lines.join("\n");}-function escapeRegex(s: string): string {- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");-}-function prependToChangelog(section: string, version: string): void {const content = readFileSync("CHANGELOG.md", { encoding: "utf-8" });const versionPattern = new RegExp(`^## ${escapeRegex(version)} — .*$`, "m");@@ -430,7 +428,4 @@ function main(): void {if (!section.endsWith("\n")) process.stdout.write("\n");}-// Only run main when invoked as a script (not when imported by tests).-if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {- main();-}+if (isMainModule(import.meta.url)) main();diff --git a/.github/scripts/manifest-check.ts b/.github/scripts/manifest-check.tsindex 451459b..665d877 100644--- a/.github/scripts/manifest-check.ts+++ b/.github/scripts/manifest-check.ts@@ -10,7 +10,8 @@import { readFileSync, readdirSync, type Dirent } from "node:fs";import { join } from "node:path";-import { fileURLToPath } from "node:url";++import { isMainModule } from "../../.claude/scripts/lib/main-guard.ts";type Manifest = { readonly infrastructure?: readonly string[] };@@ -83,6 +84,7 @@ const WATCHED: ReadonlyArray<{// the corresponding entries in vault-manifest.json's `infrastructure` array.const WATCHED_ROOT_FILES: readonly string[] = ["AGENTS.md",+ "ARCHITECTURE.md","CLAUDE.md","CHANGELOG.md","CONTRIBUTING.md",@@ -166,6 +168,4 @@ function main(): void {);}-if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {- main();-}+if (isMainModule(import.meta.url)) main();diff --git a/.obsidian/app.json b/.obsidian/app.jsonnew file mode 100644index 0000000..957efe5--- /dev/null+++ b/.obsidian/app.json@@ -0,0 +1,11 @@+{+ "userIgnoreFilters": [+ "ARCHITECTURE.md",+ "README.md",+ "README.ja.md",+ "README.ko.md",+ "README.zh-CN.md",+ "CHANGELOG.md",+ "CONTRIBUTING.md"+ ]+}diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdnew file mode 100644index 0000000..8745d26--- /dev/null+++ b/ARCHITECTURE.md@@ -0,0 +1,362 @@+# Architecture++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`.++---++## System Overview++obsidian-mind is a plain Obsidian vault with three systems layered on top:++1. **The vault itself** — Markdown files, frontmatter, wikilinks. Portable, git-tracked, Obsidian-browsable.+2. **A hook pipeline** — small TypeScript scripts invoked by the agent harness at lifecycle events (session start, every message, after writes, before compaction, at session end).+3. **A semantic search layer (QMD)** — a separate CLI + SQLite index + MCP server, all scoped to a named index read from `vault-manifest.json`.++The three layers communicate through one coordination point: **`vault-manifest.json`**. It declares the template version, the QMD index name, and the boundary between infrastructure files (shipped by the template) and user content (created by the human).++```mermaid+flowchart TB+ User["Human operator"]+ subgraph Agent["AI coding agent (Claude Code / Codex / Gemini)"]+ Harness["Agent harness"]+ Hooks["Hook pipeline<br/>(.claude/scripts/)"]+ MCP["MCP tools"]+ end+ subgraph Vault["Obsidian vault"]+ Manifest["vault-manifest.json<br/>(source of truth)"]+ Notes["Markdown notes<br/>(work/, perf/, brain/, org/)"]+ Config[".claude/ .codex/ .gemini/<br/>(hook configs)"]+ end+ QMD["QMD<br/>(named SQLite index + embeddings)"]+ Obsidian["Obsidian app<br/>(graph, Bases, CLI)"]++ User <--> Agent+ User <--> Obsidian+ Harness --> Hooks+ Harness --> MCP+ Hooks --> Manifest+ Hooks --> Notes+ Hooks --> QMD+ MCP --> QMD+ QMD --> Notes+ Obsidian --> Notes+ Config --> Hooks+```++The vault is the persistent state. Everything else is machinery around it.++---++## Division of Responsibility++Two actors do the work, and the boundary between them is the most important design choice in the system.++**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 — the hook test suite has 400+ unit tests locking the contracts.++**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 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.++---++## Design Principles++Four ideas shape every decision in this template. When a change breaks one of them, it needs a very good reason.++### 1. Graph-first, not folder-first++Folders group by purpose. Links group by meaning. A note lives in one folder (its home) but links to many notes (its context). Competency notes stay definitional and receive evidence through backlinks — review prep becomes reading the backlinks panel on each competency. This is why every new note must link to at least one existing note, and why the agent is instructed to treat orphan notes as bugs.++### 2. Vault-first memory++All durable knowledge lives in the vault, inside `brain/` topic notes. The agent-specific memory indexes (`~/.claude/.../MEMORY.md`) are pointers to vault locations, never the storage themselves. This keeps memory git-tracked, machine-portable, and visible in the Obsidian graph.++### 3. Progressive disclosure++`SessionStart` injects ~2K tokens of lightweight context (North Star excerpt, git summary, tasks, file listing). Full note contents are pulled on demand via QMD semantic search. A full file read is a last resort, not a default. This keeps session cost flat regardless of vault size.++### 4. Agent-agnostic core++The hook scripts, subagent prompts, command definitions, and vault conventions are pure Markdown and TypeScript with no SDK dependencies. Each agent (Claude Code, Codex CLI, Gemini CLI) brings its own config file pointing at the same scripts. Only the `~/.claude/` auto-memory loader is Claude Code-specific.++---++## The Manifest as Source of Truth++`vault-manifest.json` is the one file that every layer reads. It answers five questions:++| Question | Field |+|----------|-------|+| What version of the template is this? | `version`, `released`, `version_fingerprints` |+| What does QMD call its store? | `qmd_index`, `qmd_context` |+| Which files are template infrastructure? | `infrastructure[]` |+| Which files are user content? | `user_content_roots[]`, `scaffold{}` |+| What frontmatter is required for each note type? | `frontmatter_required{}` |++The `qmd_index` field is the most load-bearing. Three independent callers read it:++```mermaid+flowchart LR+ Manifest["vault-manifest.json<br/>qmd_index: obsidian-mind"]+ SessionStart["SessionStart hook<br/>(session-start.ts)"]+ MCP[".mcp.json wrapper<br/>(qmd-mcp.mjs)"]+ Refresh["Mid-session refresh<br/>(PostToolUse / Stop / PreCompact<br/>→ qmd-refresh-run.ts worker)"]+ Store[("QMD SQLite store<br/>(named: obsidian-mind)")]++ Manifest --> SessionStart+ Manifest --> MCP+ Manifest --> Refresh+ SessionStart -->|re-index at startup| Store+ Refresh -->|debounced refresh| Store+ MCP -->|search tools| Store+```++Because all three callers derive the index name from the same field, the vault can coexist with other QMD-indexed projects on the same machine without collision. Change `qmd_index` in the manifest and the next bootstrap creates a fresh, isolated store.++The `infrastructure[]` vs `user_content_roots[]` split is what makes `/om-vault-upgrade` work. When importing from an older template, the migrator overwrites infrastructure files wholesale and preserves user content untouched.++---++## Lifecycle Hooks++Five hooks run at different moments in a session. Each is a small Node script invoked via `--experimental-strip-types` (TypeScript executes directly, no build step).++```mermaid+sequenceDiagram+ participant User+ participant Agent+ participant Hooks+ participant Vault+ participant QMD++ User->>Agent: start session+ Agent->>Hooks: SessionStart+ Hooks->>Vault: read North Star, git log, tasks, file listing+ Hooks->>QMD: re-index (async)+ Hooks-->>Agent: inject ~2K tokens of context++ loop each user message+ User->>Agent: prompt+ Agent->>Hooks: UserPromptSubmit+ Hooks->>Hooks: classify (decision, incident, win, 1:1, ...)+ Hooks-->>Agent: routing hints+ end++ loop each Write/Edit to .md+ Agent->>Hooks: PostToolUse+ Hooks->>Hooks: validate frontmatter + wikilinks+ Hooks->>QMD: debounced refresh (detached)+ Hooks-->>Agent: warnings if invalid+ end++ Note over Agent,Hooks: if context fills+ Agent->>Hooks: PreCompact+ Hooks->>Vault: back up transcript to thinking/session-logs/++ User->>Agent: end session+ Agent->>Hooks: Stop+ Hooks-->>Agent: wrap-up checklist reminder+```++A few specific design choices are worth calling out:++- **`SessionStart` injects, it does not load.** It builds a ~2K-token briefing (filename listing, North Star excerpt, git summary, open tasks) and hands it to the agent. Full note contents never flow through this hook.+- **`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.+- **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` (end of session) — 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` is deliberately lightweight.** Beyond triggering the shared refresh, it only prints a short checklist. For a thorough review, the user invokes `/om-wrap-up` explicitly. Putting heavy logic in a Stop hook would slow every session exit and surprise the user.++---++## QMD Integration++QMD provides semantic search. It is the mechanism behind most of the agent's retrieval intelligence. Three entry points all read from the same named index:++| Caller | Entry point | When |+|--------|-------------|------|+| Agent tool menu | `.mcp.json` → `qmd-mcp.mjs` | Every `mcp__qmd__*` tool call from the agent |+| Session startup | `session-start.ts` | Re-index on every new session |+| Mid-session refresh | `qmd-refresh.ts` / `stop-checklist.ts` / `pre-compact.ts` → shared debounce → `qmd-refresh-run.ts` | After `.md` writes, at session end, and before compaction |++Every `qmd update` invocation re-reads the per-index YAML (`~/.config/qmd/<index>.yml`), so changes to the collection config — including the ignore list synced from `.obsidian/app.json` — propagate to every surface without a session restart.++```mermaid+flowchart TB+ subgraph Reader["Agent tools"]+ MCP_get["mcp__qmd__get"]+ MCP_query["mcp__qmd__query"]+ MCP_multi["mcp__qmd__multi_get"]+ MCP_status["mcp__qmd__status"]+ end+ subgraph Writer["Index maintenance"]+ Boot["qmd-bootstrap.ts<br/>(one-time)"]+ Session["session-start.ts<br/>(per session)"]+ Refresh["qmd-refresh-run.ts<br/>(per write/stop/pre-compact,<br/>debounced, detached)"]+ end+ Wrapper["qmd-mcp.mjs<br/>(reads qmd_index from manifest)"]+ CLI["qmd CLI<br/>(--index <name> from manifest)"]+ Store[("Named SQLite store<br/>+ embeddings")]++ MCP_get --> Wrapper+ MCP_query --> Wrapper+ MCP_multi --> Wrapper+ MCP_status --> Wrapper+ Wrapper --> Store+ Boot --> CLI+ Session --> CLI+ Refresh --> CLI+ 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.++### MCP as the agent-facing contract++When the MCP server is registered, the agent's normal path to QMD is through typed tools — `mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, and `mcp__qmd__status` — that appear in its tool menu alongside Read and Edit. These come from the [Model Context Protocol](https://modelcontextprotocol.io) server declared in `.mcp.json`, launched by a thin wrapper (`.claude/scripts/qmd-mcp.mjs`) that reads `qmd_index` from the manifest and invokes `qmd mcp` underneath. The CLI remains available — and is documented as the fallback — but during a session with MCP live, the agent goes through typed tools, not shell.++The wrapper exists so that each vault can run its own isolated index without users hand-editing `.mcp.json`. The index name flows from the manifest into the wrapper, the wrapper into QMD, QMD into its per-vault SQLite store.++The contract matters because the alternative — teaching every subagent and slash command to shell out to `qmd search` on every call — would couple each prompt to QMD's CLI surface, duplicate parse/retry logic across files, and force every prompt to re-explain the tool. MCP collapses all of that into one typed interface for the in-session path. When QMD changes its CLI, the wrapper adapts; the rest of the template is insulated. When another MCP-aware service needs to join the vault (a bug tracker, a docs search, a calendar), it registers in `.mcp.json` and gains the same privileged position.++### One ignore list, two engines++Obsidian and QMD both need to know which files to hide from search. Rather than maintain two lists that can drift, the template treats `.obsidian/app.json` → `userIgnoreFilters` as the single source of truth. `qmd-bootstrap.ts` reads that array and writes it into the QMD per-index YAML (`~/.config/qmd/<index>.yml`) as the collection's `ignore` field. Every subsequent `qmd update` (initial index, mid-session refresh, session-start reindex) honors the list.++```mermaid+flowchart LR+ App[".obsidian/app.json<br/>userIgnoreFilters"]+ Boot["qmd-bootstrap.ts"]+ YAML["~/.config/qmd/<index>.yml<br/>collections.<name>.ignore"]+ Obs["Obsidian<br/>(search, graph, switcher)"]+ QmdUpdate["qmd update<br/>(every invocation)"]++ App --> Obs+ App --> Boot+ Boot --> YAML+ YAML --> QmdUpdate+```++This is why the list lives in Obsidian's config and not `vault-manifest.json`: users who adjust what's hidden in Obsidian's UI get the same change propagated to QMD on the next bootstrap. Files that are infrastructure (template dev docs like this one, `CHANGELOG.md`, `CONTRIBUTING.md`) are good candidates; user-authored content should not be here.++---++## Multi-Agent Portability++The same scripts serve three agents. Each agent has its own config file mapping its own event names to the shared scripts. The event vocabularies differ — Claude Code calls it `Stop`, Gemini calls it `SessionEnd`, Codex has no compaction event — but the scripts are identical.++```mermaid+flowchart TB+ subgraph Configs["Per-agent config (event name mapping)"]+ Claude[".claude/settings.json<br/>Claude Code"]+ Codex[".codex/hooks.json<br/>Codex CLI"]+ Gemini[".gemini/settings.json<br/>Gemini CLI"]+ end+ subgraph Shared[".claude/scripts/ (shared core)"]+ S1["session-start.ts"]+ S2["classify-message.ts"]+ S3["validate-write.ts"]+ S4["qmd-refresh.ts"]+ S5["pre-compact.ts"]+ S6["stop-checklist.ts"]+ end+ subgraph Manuals["Operating manuals"]+ CM["CLAUDE.md"]+ AM["AGENTS.md"]+ GM["GEMINI.md"]+ end++ Claude --> Shared+ Codex --> Shared+ Gemini --> Shared+ Claude -.reads.-> CM+ Codex -.reads.-> AM+ Gemini -.reads.-> GM+```++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.++---++## Vault-First Memory++There are two memory systems, and the distinction is load-bearing:++```mermaid+flowchart LR+ SessionStart["SessionStart hook<br/>(.claude/scripts/session-start.ts)"]+ subgraph Ephemeral["~/.claude/ (not git-tracked)"]+ MemIndex["MEMORY.md<br/>(auto-loaded index)"]+ end+ subgraph Durable["Vault (git-tracked)"]+ NorthStar["brain/North Star.md"]+ BrainIdx["brain/Memories.md<br/>(topic index)"]+ Gotchas["brain/Gotchas.md"]+ Patterns["brain/Patterns.md"]+ Decisions["brain/Key Decisions.md"]+ end++ SessionStart ==>|reads every session| NorthStar+ MemIndex -->|points at| BrainIdx+ MemIndex -->|points at| Gotchas+ MemIndex -->|points at| Patterns+ MemIndex -->|points at| Decisions+ BrainIdx --> Gotchas+ BrainIdx --> Patterns+ BrainIdx --> Decisions+```++Two load paths into a session, both landing in the vault:++- **Pointer indirection** — `~/.claude/.../MEMORY.md` is Claude Code's private auto-memory directory. The template uses it only to hold a thin index that points at vault locations. Topics fire on demand when the conversation touches them.+- **Direct injection** — `brain/North Star.md` is loaded by the `SessionStart` hook on every session as its own context block. It's the goals document; it needs to be present every time, not only when triggered.++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.++---++## Skills and Commands++The template ships two categories of skills:++- **Obsidian-native skills** (`kepano/obsidian-skills`) in `.claude/skills/` — teach the agent Obsidian-flavored Markdown, the Obsidian CLI, Bases, and JSON Canvas. Loaded automatically when relevant.+- **A custom QMD skill** in `.claude/skills/qmd/` — teaches the agent the preference order for vault retrieval (MCP tools when registered → `qmd` CLI as fallback → Grep/Glob as last resort) and the signals that should trigger a proactive search (past decisions, incidents, people, architecture, duplicates before creating a note).++Slash commands in `.claude/commands/` are operational workflows (e.g. `/om-standup`, `/om-wrap-up`, `/om-review-brief`). Each is a Markdown file with prompt instructions. Subagents in `.claude/agents/` are invoked by those commands to keep heavy operations (Slack archaeology, PR deep scans, vault migration) out of the main context window.++The rule for adding a new command: if it produces durable knowledge, it should write to the vault. If it would only make sense within one session, it is probably better as a prompt pattern than a command.++---++## Extension Seams++The design makes these changes easy:++| Change | Touch this |+|--------|------------|+| Add a new note type | `vault-manifest.json` → `frontmatter_required`, and a template in `templates/` |+| Isolate this vault from others on the same machine | `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 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 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 |++The design is hostile to these changes (on purpose):++- Storing memories outside the vault. The whole point of `brain/` is portability and graph visibility.+- Bypassing the manifest. If a new component needs to know the index name or the infrastructure boundary, it should read the manifest rather than hardcode.+- Hardcoding agent event names inside scripts. Event name translation is a config-layer concern.++---++## Upgrade Path++Template versions are tracked in `vault-manifest.json` with fingerprints that let `/om-vault-upgrade` detect an older vault's version by presence or absence of specific files. The migrator uses the infrastructure/user-content split to decide what to overwrite versus preserve. `CHANGELOG.md` documents what changed in each version.++The long-term stability guarantee is narrow: the manifest keys (`qmd_index`, `infrastructure`, `user_content_roots`, `frontmatter_required`), the hook script names under `.claude/scripts/`, and the folder layout for user content. Everything else — including command names, subagent internals, and classification logic — is allowed to evolve between versions.diff --git a/CLAUDE.md b/CLAUDE.mdindex acd4cca..76db81e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -11,7 +11,12 @@ This vault has [obsidian-skills](https://github.com/kepano/obsidian-skills) inst- **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 -- `qmd --index <name> query "..."` for hybrid search, `qmd --index <name> search "..."` for keyword, `qmd --index <name> vsearch "..."` for semantic. **Always pass `--index <name>`** where `<name>` is the `qmd_index` field from `vault-manifest.json` -- this keeps the SQLite store isolated from any other vault that shares the machine. Also registered as an MCP server via `.mcp.json` using `.claude/scripts/qmd-mcp.mjs`, which reads the same manifest field so the CLI, MCP, and SessionStart hook all scope to the same store. On a fresh clone, run `node --experimental-strip-types scripts/qmd-bootstrap.ts` once to build the index. Falls back to grep/glob if QMD not installed.+- **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` 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.### Custom Slash Commands@@ -274,7 +279,7 @@ When asked to "remember" something: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 — `qmd query "<topic keywords>"` searches the whole vault, so after the query filter or prioritize the results whose `file` path is under `brain/`. Do not assume the topic name alone scopes the search.+- 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).diff --git a/README.ja.md b/README.ja.mdindex 85bc6f4..9d4554e 100644--- a/README.ja.md+++ b/README.ja.md@@ -120,8 +120,10 @@ qmd --index obsidian-mind update # 一括編集後qmd --index obsidian-mind embed # 多数の新規ノート後```+**MCPによるネイティブなエージェントツール。** `.mcp.json`に[Model Context Protocol](https://modelcontextprotocol.io)サーバーとして登録されています — QMDがインストールされていれば、`mcp__qmd__query`、`mcp__qmd__get`、`mcp__qmd__multi_get`がReadやEditと並んでエージェントのツールメニューに表示されます。サブエージェント、スラッシュコマンド、メイン会話はすべて同じ型付きコントラクトを呼び出します。後から別のMCP対応ツール(データベース、チケット管理、カレンダー)を追加しても、同じ方法でプラグインできます。+> [!NOTE]-> QMDがインストールされていなくても、すべて動作します — エージェントはObsidian CLIとgrepにフォールバックします。+> QMDがインストールされていなくても、すべて動作します — エージェントはObsidian CLIとgrepにフォールバックし、MCPサーバーのエントリは無害な警告とともにスキップされます。---@@ -139,6 +141,8 @@ qmd --index obsidian-mind embed # 多数の新規ノート後## ⚙️ 仕組み+**手続き的コードが環境を所有し、エージェントがコンテンツを所有します。** `.claude/scripts/`のフックが分類、検証、インデックス作成、ライフサイクル注入を処理します — 決定論的で、テスト可能で、どのエージェントでも同じように動作します。ノートを書き、配置し、リンクし、ブリーフを作成する — それらは判断であり、エージェントに委ねられます。両者は小さなハンドオフで出会い(フックがコンテキストを注入し、エージェントがボールトを読む)、どちらも相手の仕事をする必要はありません。+**フォルダは目的別にグループ化。リンクは意味別にグループ化。** ノートは1つのフォルダ(その居場所)に存在しますが、多くのノート(そのコンテキスト)にリンクします。エージェントがこのグラフを維持し、作業ノートを人物、意思決定、コンピテンシーに自動的にリンクします。レビューシーズンが来たとき、各コンピテンシーノートのバックリンクがそのままエビデンスの軌跡になっています。リンクのないノートはバグです。**ボールトファーストのメモリ**がセッション間・マシン間でコンテキストを保持します。永続的な知識はすべて`brain/`のトピックノート(git管理、Obsidianで閲覧可能、リンク付き)に保存されます。Claude Codeの`MEMORY.md`(`~/.claude/`)はボールト内の場所を指す自動読み込みインデックスであり、ストレージそのものではありません。これにより、記憶はマシン変更後も生き残り、グラフの一部として機能します。diff --git a/README.ko.md b/README.ko.mdindex 6d60c2c..46dd495 100644--- a/README.ko.md+++ b/README.ko.md@@ -120,8 +120,10 @@ qmd --index obsidian-mind update # 일괄 편집 후qmd --index obsidian-mind embed # 많은 신규 노트 후```+**MCP를 통한 네이티브 에이전트 도구.** `.mcp.json`에 [Model Context Protocol](https://modelcontextprotocol.io) 서버로 등록되어 있습니다 — QMD가 설치되어 있으면 `mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`가 Read와 Edit 옆에 에이전트의 도구 메뉴에 나타납니다. 서브에이전트, 슬래시 명령, 메인 대화 모두 동일한 타입 지정 계약을 호출합니다. 나중에 다른 MCP 호환 도구(데이터베이스, 티켓팅 시스템, 캘린더)를 추가하면 같은 방식으로 플러그인됩니다.+> [!NOTE]-> QMD가 설치되어 있지 않아도 모든 기능이 작동합니다 — 에이전트가 Obsidian CLI와 grep으로 대체합니다.+> QMD가 설치되어 있지 않아도 모든 기능이 작동합니다 — 에이전트가 Obsidian CLI와 grep으로 대체하고, MCP 서버 항목은 무해한 경고와 함께 건너뜁니다.---@@ -139,6 +141,8 @@ qmd --index obsidian-mind embed # 많은 신규 노트 후## ⚙️ 작동 원리+**절차적 코드는 환경을 소유하고, 에이전트는 콘텐츠를 소유합니다.** `.claude/scripts/`의 훅이 분류, 검증, 인덱싱, 라이프사이클 주입을 처리합니다 — 결정론적이고, 테스트 가능하며, 모든 에이전트에서 동일하게 실행됩니다. 노트를 작성하고, 분류하고, 링크하고, 브리프를 작성하는 것 — 이는 판단이며 에이전트의 몫으로 남겨집니다. 양쪽은 작은 핸드오프에서 만납니다(훅이 컨텍스트를 주입하고 에이전트가 볼트를 읽음) — 서로의 일을 할 필요가 없습니다.+**폴더는 용도별로 그룹화하고, 링크는 의미별로 그룹화합니다.** 노트는 하나의 폴더(본거지)에 있지만 여러 노트(컨텍스트)에 링크됩니다. 에이전트는 이 그래프를 유지 관리합니다 — 작업 노트를 사람, 의사결정, 역량에 자동으로 연결합니다. 리뷰 시즌이 오면 각 역량 노트의 백링크가 이미 증거 자료가 됩니다. 링크가 없는 노트는 버그입니다.**볼트 우선 메모리**는 세션과 기기 간에 컨텍스트를 유지합니다. 모든 지속 지식은 `brain/` 토픽 노트에 있습니다(git 추적, Obsidian 브라우저 가능, 링크됨). Claude Code의 `MEMORY.md`(`~/.claude/`)는 볼트 위치를 가리키는 자동 로드 인덱스일 뿐 — 저장소 자체가 아닙니다. 즉, 메모리가 기기 변경에도 유지되며 그래프의 일부가 됩니다.diff --git a/README.md b/README.mdindex 9b2a655..9bf0429 100644--- a/README.md+++ b/README.md@@ -109,7 +109,7 @@ QMD is where most of the agent's retrieval intelligence comes from. Optional in- **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.- **Subagents get sharper context.** `context-loader`, `review-prep`, `brag-spotter`, and friends consult QMD first, then fall back to grep.-- **First-class MCP tools.** Registered via `.mcp.json` at the project root — when QMD is installed, its search tools appear directly in the Claude Code tool menu.+- **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.```bashnpm install -g @tobilu/qmd@@ -148,6 +148,8 @@ qmd --index obsidian-mind embed # after many new notes## ⚙️ How It Works+**Procedural code owns the environment. The agent owns content.** The hooks in `.claude/scripts/` handle classification, validation, indexing, and lifecycle injection — deterministic, testable, runs the same for every agent. Writing notes, filing them, linking them, drafting briefs — those are judgments, and they stay with the agent. The two halves meet at small handoffs (hooks inject context, agent reads the vault) so neither has to do the other's job.+**Folders group by purpose. Links group by meaning.** A note lives in one folder (its home) but links to many notes (its context). Your agent maintains this graph — linking work notes to people, decisions, and competencies automatically. When review season arrives, the backlinks on each competency note are already the evidence trail. A note without links is a bug.**Vault-first memory** keeps context across sessions and machines. All durable knowledge lives in `brain/` topic notes (git-tracked, Obsidian-browsable, linked). Claude Code's `MEMORY.md` (`~/.claude/`) is an auto-loaded index that points to vault locations — never the storage itself. This means memories survive machine changes and are part of the graph.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 1ccda55..831b35f 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -120,8 +120,10 @@ qmd --index obsidian-mind update # 批量编辑后qmd --index obsidian-mind embed # 大量新笔记后```+**通过 MCP 原生集成为 Agent 工具。** 在 `.mcp.json` 中注册为 [Model Context Protocol](https://modelcontextprotocol.io) 服务器——当 QMD 已安装时,`mcp__qmd__query`、`mcp__qmd__get`、`mcp__qmd__multi_get` 会与 Read、Edit 一起出现在 Agent 的工具菜单中。子代理、斜杠命令和主对话都通过同一个带类型的契约进行调用。之后再接入其他 MCP 兼容工具(数据库、工单系统、日历),接入方式完全一致。+> [!NOTE]-> 如果没有安装 QMD,一切仍然正常运作——Agent 会回退到 Obsidian CLI 和 grep。+> 如果没有安装 QMD,一切仍然正常运作——Agent 会回退到 Obsidian CLI 和 grep,MCP 服务器条目会以无害的警告被跳过。---@@ -139,6 +141,8 @@ qmd --index obsidian-mind embed # 大量新笔记后## ⚙️ 工作原理+**过程化代码负责环境,Agent 负责内容。** `.claude/scripts/` 中的钩子处理分类、验证、索引和生命周期注入——可复现、可测试,对每个 Agent 都以相同方式运行。撰写笔记、归类、链接、起草简报——这些属于判断范畴,交由 Agent 处理。两侧通过小而清晰的交接相遇(钩子注入上下文,Agent 读取仓库),因此双方都不需要越界做对方的工作。+**文件夹按用途组织,链接按含义组织。** 一个笔记存放在一个文件夹中(它的归属),但链接到许多笔记(它的上下文)。Agent 维护这个图谱——自动将工作笔记链接到人员、决策和能力项。当绩效评估季到来时,每个能力项笔记上的反向链接就是现成的证据链。一个没有链接的笔记就是一个 bug。**仓库优先的记忆** 使上下文能跨会话和设备持续存在。所有持久知识存储在 `brain/` 主题笔记中(git 跟踪、Obsidian 可浏览、相互链接)。Claude Code 的 `MEMORY.md`(`~/.claude/`)是一个自动加载的索引,指向仓库中的位置——本身不存储内容。这意味着记忆可以在更换设备后保留,并且是知识图谱的一部分。diff --git a/scripts/qmd-bootstrap.ts b/scripts/qmd-bootstrap.tsindex 3e7cbdb..0a5cdaa 100644--- a/scripts/qmd-bootstrap.ts+++ b/scripts/qmd-bootstrap.ts@@ -8,8 +8,10 @@* in vault-manifest.json (`qmd_index`).* 2. Attach the vault's context string (`qmd_context`) so QMD's snippets* and rerank step know what this collection is.- * 3. Walk the vault and build the sparse index.- * 4. Generate vector embeddings.+ * 3. Sync `.obsidian/app.json` userIgnoreFilters into the QMD YAML config+ * so both engines hide the same files from search.+ * 4. Walk the vault and build the sparse index.+ * 5. Generate vector embeddings.** Safe to re-run. Every step reports current state rather than failing on* "already exists" — the context string is re-attached so updates to@@ -29,7 +31,15 @@import { spawnSync } from "node:child_process";import { readFileSync } from "node:fs";+import { warn } from "../.claude/scripts/lib/hook-io.ts";+import { isMainModule } from "../.claude/scripts/lib/main-guard.ts";import { buildQmdCommand, resolveQmdEntry } from "../.claude/scripts/lib/qmd.ts";+import {+ qmdConfigPath,+ readObsidianIgnore,+ translateToGlob,+ writeQmdIgnore,+} from "../.claude/scripts/lib/qmd-ignore.ts";import { isValidQmdIndex } from "../.claude/scripts/lib/session-start.ts";type ManifestSubset = {@@ -217,6 +227,45 @@ function main(): void {"Attaching vault context from manifest",);+ // Propagate Obsidian's userIgnoreFilters into QMD's YAML so both engines+ // honor the same hidden-file list. Runs after `collection add` because+ // that call overwrites the collection entry without preserving `ignore`.+ // readObsidianIgnore returns null when app.json is unreadable/unparseable —+ // we skip propagation in that case so a user typo doesn't strip the+ // existing QMD ignore block. A warn() has already been emitted.+ const obsidianIgnore = readObsidianIgnore();+ if (obsidianIgnore !== null) {+ const qmdIgnore: string[] = [];+ for (const p of obsidianIgnore) {+ const glob = translateToGlob(p);+ if (glob === null) {+ warn(+ `Skipping regex pattern ${JSON.stringify(p)} — QMD ignore field accepts globs only.`,+ );+ continue;+ }+ qmdIgnore.push(glob);+ }+ // Print the step header only after the write succeeds, so logs never+ // show "→ Syncing..." as a completed step when writeQmdIgnore actually+ // skipped (missing config or unknown collection — both already warn()).+ const wrote = writeQmdIgnore(+ qmdConfigPath(index),+ collectionName,+ qmdIgnore,+ );+ if (wrote) {+ process.stdout.write(+ "→ Syncing ignore patterns from .obsidian/app.json\n",+ );+ if (qmdIgnore.length > 0) {+ process.stdout.write(+ ` ${qmdIgnore.length} ignore pattern(s) synced from .obsidian/app.json\n`,+ );+ }+ }+ }+run(entry, ["--index", index, "update"], "Indexing vault files");run(entry, ["--index", index, "embed"], "Generating embeddings");@@ -225,4 +274,4 @@ function main(): void {);}-main();+if (isMainModule(import.meta.url)) main();diff --git a/vault-manifest.json b/vault-manifest.jsonindex 81b868e..f8878a6 100644--- a/vault-manifest.json+++ b/vault-manifest.json@@ -13,6 +13,7 @@"README.*.md","CHANGELOG.md","CONTRIBUTING.md",+ "ARCHITECTURE.md","LICENSE",".gitignore",".mcp.json",