Skip to content

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

feat: deliver session context as an instruction file through a Claude Code mod (#271)

Brenno Ferrari1d6bf4a4dcbe
diff --git a/.claude/scripts/tests/generate-changelog.test.ts b/.claude/scripts/tests/generate-changelog.test.ts
index 2b7dbc8..e4893b3 100644
--- a/.claude/scripts/tests/generate-changelog.test.ts
+++ b/.claude/scripts/tests/generate-changelog.test.ts
@@ -7,6 +7,9 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
import {
classifyCommit,
generateSection,
@@ -14,7 +17,9 @@ import {
toFingerprintKey,
pickMarkers,
findLatestOpenFingerprint,
+ bumpPluginJsonVersion,
bumpShardYamlVersion,
+ PLUGIN_JSON,
insertChangelogSection,
} from "../../../.github/scripts/generate-changelog.ts";
@@ -244,6 +249,28 @@ describe("pickMarkers", () => {
});
});
+describe("bumpPluginJsonVersion", () => {
+ const FIXTURE = JSON.stringify({ name: "obsidian-mind", version: "8.6.0", description: "d", types: "./types/index.d.ts" }, null, 2) + "\n";
+
+ test("sets the mod's version to the normalized release version, keeping key order", () => {
+ const out = bumpPluginJsonVersion(FIXTURE, "v9.0");
+ assert.equal(JSON.parse(out).version, "9.0.0");
+ assert.deepEqual(Object.keys(JSON.parse(out)), ["name", "version", "description", "types"]);
+ assert.ok(out.endsWith("}\n"));
+ });
+
+ test("refuses a plugin.json without a version", () => {
+ assert.throws(() => bumpPluginJsonVersion('{"name":"obsidian-mind"}', "v9.0"), /no string `version`/);
+ });
+
+ test("the shipped mod carries the template's version", () => {
+ const repo = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+ const plugin = JSON.parse(readFileSync(join(repo, PLUGIN_JSON), "utf-8")) as { version: string };
+ const manifest = JSON.parse(readFileSync(join(repo, "vault-manifest.json"), "utf-8")) as { version: string };
+ assert.equal(plugin.version, manifest.version, "a release bumps both; between releases they must agree");
+ });
+});
+
describe("bumpShardYamlVersion", () => {
const FIXTURE = [
"apiVersion: v1",
diff --git a/.claude/skills/obsidian-mind/.claude-plugin/plugin.json b/.claude/skills/obsidian-mind/.claude-plugin/plugin.json
new file mode 100644
index 0000000..baeb3d7
--- /dev/null
+++ b/.claude/skills/obsidian-mind/.claude-plugin/plugin.json
@@ -0,0 +1,10 @@
+{
+ "name": "obsidian-mind",
+ "version": "8.6.0",
+ "description": "Delivers obsidian-mind's session context as an instruction file, so it survives compaction whole and reaches subagents. The vault's settings hooks stand down for each event it handles and run as before wherever it does not load.",
+ "author": {
+ "name": "Brenno Ferrari",
+ "url": "https://github.com/breferrari/obsidian-mind"
+ },
+ "types": "./types/index.d.ts"
+}
diff --git a/.claude/skills/obsidian-mind/hooks/context.ts b/.claude/skills/obsidian-mind/hooks/context.ts
new file mode 100644
index 0000000..02843ca
--- /dev/null
+++ b/.claude/skills/obsidian-mind/hooks/context.ts
@@ -0,0 +1,36 @@
+import type { PromptContextResult } from "claude-code";
+
+/** The name the context renders under when no instruction file can carry it. */
+export const CONTEXT_BLOCK = "obsidian-mind";
+
+/**
+ * The first message's context with the session context added: as a project
+ * instruction file, which Claude Code frames like CLAUDE.md, re-reads after
+ * compaction and `/clear`, and gives general-purpose subagents.
+ *
+ * When a hook above rewrote the `claudeMd` text, the files behind it are
+ * unknown and no file can be added (`instructionFiles` is undefined). The
+ * context then rides as a block of its own, so the session still gets it:
+ * the settings hook has already stood down for this event.
+ *
+ * Either way an earlier copy is replaced, never duplicated.
+ */
+export function withSessionContext(below: PromptContextResult, path: string, text: string): PromptContextResult {
+ if (below.instructionFiles) {
+ const others = below.instructionFiles.filter((file) => !samePath(file.path, path));
+ return { ...below, instructionFiles: [...others, { path, kind: "project", content: text }] };
+ }
+ const others = below.blocks.filter((block) => block.name !== CONTEXT_BLOCK);
+ return { ...below, blocks: [...others, { name: CONTEXT_BLOCK, text }] };
+}
+
+/**
+ * One file, however it is spelled: the root comes back from Claude Code in
+ * the OS's form (`C:\vault` on Windows) while the mod appends `/…`, and the
+ * engine may hand a path back normalised: separators and the drive letter's
+ * case are not part of a file's identity.
+ */
+export function samePath(a: string, b: string): boolean {
+ const norm = (p: string) => p.replaceAll("\\", "/").replace(/^([a-z]):/i, (d) => d.toLowerCase());
+ return norm(a) === norm(b);
+}
diff --git a/.claude/skills/obsidian-mind/hooks/hooks.json b/.claude/skills/obsidian-mind/hooks/hooks.json
new file mode 100644
index 0000000..5fcba7c
--- /dev/null
+++ b/.claude/skills/obsidian-mind/hooks/hooks.json
@@ -0,0 +1 @@
+{ "modules": ["./register.ts"] }
diff --git a/.claude/skills/obsidian-mind/hooks/register.test.ts b/.claude/skills/obsidian-mind/hooks/register.test.ts
new file mode 100644
index 0000000..c4f5fea
--- /dev/null
+++ b/.claude/skills/obsidian-mind/hooks/register.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, test } from "claude-code/testing";
+import { CONTEXT_BLOCK, withSessionContext } from "./context.ts";
+import { engine, ROOT, type On, type Reply } from "./world.ts";
+
+// Run with `claude plugin test .claude/skills/obsidian-mind`. Each test's own
+// `on` hooks sit beneath the mod and stand in for the engine and the vault.
+
+const CONTEXT = "## Session Context\n\n### Date\n2026-10-03 (Saturday)\n\n_context injected: 0.1kB / 20.0kB budget_\n";
+
+/**
+ * The world beneath the mod, plus every value the mod stores as this
+ * session's context. The kit's `$` has no state noun to read it back, so the
+ * writes are what a test can see; the last one is what prompt.context reads.
+ */
+function vault(on: On, script: Reply | (() => Reply), options: { hangFirstWrite?: boolean } = {}) {
+ const context: unknown[] = [];
+ on("state.set", (_$, e, next) => {
+ const write = e as { plugin?: string; key?: string; value?: unknown };
+ if (write.plugin === "obsidian-mind" && write.key === "context") context.push(write.value);
+ return next(e);
+ });
+ const world = engine(on, typeof script === "function" ? script : () => script, options);
+ return { ...world, passedDown: world.passedDown.SessionStart, context };
+}
+const lastContext = (seen: { context: unknown[] }) => seen.context.at(-1) ?? null;
+
+describe("session context (#265)", () => {
+ test("runs the vault script in deliver mode, writes the context file, and stands the settings hook down", async ($, on) => {
+ const seen = vault(on, { exitCode: 0, stdout: CONTEXT });
+ await $.classic.SessionStart({ source: "startup" });
+
+ expect(seen.runs.length).toBe(1);
+ expect(seen.runs[0]?.argv.at(-1)).toBe(`${ROOT}/.claude/scripts/session-start.ts`);
+ expect(seen.runs[0]?.init?.cwd).toBe(ROOT);
+ expect(seen.runs[0]?.init?.env?.["CLAUDE_PROJECT_DIR"]).toBe(ROOT);
+ expect(JSON.parse(seen.runs[0]?.init?.stdin ?? "{}")).toEqual(expect.objectContaining({ om_mod: "deliver", source: "startup" }));
+
+ // The engine normalises the path per OS (`C:\vault\…` on Windows): check the file, not the spelling.
+ expect(seen.writes.length).toBe(1);
+ expect(seen.writes[0]?.path).toMatch(/vault[\\/]\.claude[\\/]session-context\.md$/);
+ expect(seen.writes[0]?.text).toBe(CONTEXT);
+ expect(seen.passedDown.length).toBe(1);
+ expect(seen.passedDown[0]?.["om_mod"]).toBe("standdown");
+
+ // What prompt.context will add, and the re-render that makes it add it.
+ expect(lastContext(seen)).toBe(CONTEXT);
+ expect(seen.invalidated).toEqual(["prompt.context", "prompt.context"], "redrawn when cleared, and again with the new context");
+ });
+
+ test("a run that fails after one that worked clears the old context, so it cannot ride beside fresh hook output", async ($, on) => {
+ let fail = false;
+ const seen = vault(on, () => (fail ? { exitCode: 1, stdout: "" } : { exitCode: 0, stdout: CONTEXT }));
+
+ await $.classic.SessionStart({ source: "startup" });
+ expect(lastContext(seen)).toBe(CONTEXT);
+ fail = true;
+ await $.classic.SessionStart({ source: "clear" });
+
+ expect(seen.runs.length).toBe(2);
+ expect(seen.passedDown[1]?.["om_mod"]).toBe(undefined);
+ expect(lastContext(seen)).toBe(null);
+ expect(seen.invalidated).toEqual(["prompt.context", "prompt.context", "prompt.context"]);
+ });
+
+ test("a compaction whose run fails keeps the last good context: the hook's fallback there is only a pointer", async ($, on) => {
+ let fail = false;
+ const seen = vault(on, () => (fail ? { exitCode: 1, stdout: "" } : { exitCode: 0, stdout: CONTEXT }));
+
+ await $.classic.SessionStart({ source: "startup" });
+ fail = true;
+ await $.classic.SessionStart({ source: "compact" });
+
+ expect(seen.runs.length).toBe(2);
+ expect(seen.passedDown[1]?.["om_mod"]).toBe(undefined);
+ expect(lastContext(seen)).toBe(CONTEXT);
+ });
+
+ test("a context-file write that never settles does not hold up delivery", async ($, on) => {
+ const world = vault(on, { exitCode: 0, stdout: CONTEXT }, { hangFirstWrite: true });
+ await $.classic.SessionStart({ source: "startup" });
+
+ expect(world.writes.length).toBe(1);
+ expect(world.passedDown[0]?.["om_mod"]).toBe("standdown");
+ expect(lastContext(world)).toBe(CONTEXT);
+ });
+
+ test("when the script fails, the settings hook gets the original event and runs as without the mod", async ($, on) => {
+ const seen = vault(on, { exitCode: 1, stdout: "", stderr: "boom" });
+ await $.classic.SessionStart({ source: "startup" });
+
+ // The mod ran and its script failed: not skipped for some other reason.
+ expect(seen.runs.length).toBe(1);
+ expect(lastContext(seen)).toBe(null);
+ expect(seen.passedDown.length).toBe(1);
+ expect(seen.passedDown[0]?.["om_mod"]).toBe(undefined);
+ expect(seen.writes.length).toBe(0);
+ });
+
+ test("a context process.run cut short counts as a failure: the hook is not stood down for part of it", async ($, on) => {
+ const seen = vault(on, { exitCode: 0, stdout: CONTEXT, truncated: true });
+ await $.classic.SessionStart({ source: "startup" });
+
+ expect(seen.runs.length).toBe(1);
+ expect(seen.passedDown[0]?.["om_mod"]).toBe(undefined);
+ expect(seen.writes.length).toBe(0);
+ });
+
+ test("an empty context counts as a failure too: nothing is stood down for nothing", async ($, on) => {
+ const seen = vault(on, { exitCode: 0, stdout: " \n" });
+ await $.classic.SessionStart({ source: "clear" });
+
+ expect(seen.runs.length).toBe(1);
+ expect(seen.passedDown[0]?.["om_mod"]).toBe(undefined);
+ });
+});
+
+describe("withSessionContext", () => {
+ const PATH = `${ROOT}/.claude/session-context.md`;
+ const claudeMd = { path: `${ROOT}/CLAUDE.md`, kind: "project" as const, content: "# Vault" };
+
+ test("adds the context as a project instruction file, after the files already there", () => {
+ const out = withSessionContext({ blocks: [{ name: "claudeMd", text: "" }], instructionFiles: [claudeMd] }, PATH, CONTEXT);
+ expect(out.instructionFiles).toEqual([claudeMd, { path: PATH, kind: "project", content: CONTEXT }]);
+ expect(out.blocks).toEqual([{ name: "claudeMd", text: "" }]);
+ });
+
+ test("replaces an earlier copy instead of adding a second", () => {
+ const once = withSessionContext({ blocks: [], instructionFiles: [claudeMd] }, PATH, "old");
+ const twice = withSessionContext(once, PATH, CONTEXT);
+ expect(twice.instructionFiles?.filter((file) => file.path === PATH)).toEqual([{ path: PATH, kind: "project", content: CONTEXT }]);
+ });
+
+ test("when the files behind claudeMd are unknown, the context rides as its own block", () => {
+ const out = withSessionContext({ blocks: [{ name: "claudeMd", text: "rewritten" }] }, PATH, CONTEXT);
+ expect(out.instructionFiles).toBe(undefined);
+ expect(out.blocks).toEqual([
+ { name: "claudeMd", text: "rewritten" },
+ { name: CONTEXT_BLOCK, text: CONTEXT },
+ ]);
+ });
+
+ test("a copy spelled with the other separator or drive case is still the same file", () => {
+ const once = withSessionContext({ blocks: [], instructionFiles: [] }, "C:\\vault/.claude/session-context.md", "old");
+ const respelled = { ...once, instructionFiles: once.instructionFiles?.map((f) => ({ ...f, path: "c:\\vault\\.claude\\session-context.md" })) };
+ const twice = withSessionContext(respelled, "C:\\vault/.claude/session-context.md", CONTEXT);
+ expect(twice.instructionFiles?.length).toBe(1);
+ expect(twice.instructionFiles?.[0]?.content).toBe(CONTEXT);
+ });
+
+ test("that block is replaced, not duplicated, on a re-render", () => {
+ const once = withSessionContext({ blocks: [] }, PATH, "old");
+ const twice = withSessionContext(once, PATH, CONTEXT);
+ expect(twice.blocks).toEqual([{ name: CONTEXT_BLOCK, text: CONTEXT }]);
+ });
+});
diff --git a/.claude/skills/obsidian-mind/hooks/register.ts b/.claude/skills/obsidian-mind/hooks/register.ts
new file mode 100644
index 0000000..062cb7a
--- /dev/null
+++ b/.claude/skills/obsidian-mind/hooks/register.ts
@@ -0,0 +1,85 @@
+import { atom, read, update, type EngineInterface, type Register } from "claude-code";
+import { withSessionContext } from "./context.ts";
+
+/**
+ * obsidian-mind's Claude Code mod (#262).
+ *
+ * The vault's settings hooks stay the engine: Codex and Gemini run them, and
+ * so does Claude Code wherever this mod does not load (an older CLI, an
+ * untrusted folder, a session launched in a vault subfolder, a policy that
+ * allows only managed mods). This mod changes how their output reaches the
+ * session, never what it says: it runs the vault's own scripts and delivers
+ * the result through a better channel.
+ *
+ * Session context (#265): `session-start.ts` runs here with
+ * `om_mod: "deliver"`, and its output becomes an instruction file instead of
+ * hook output. Unlike hook output it is not cut at 10,000 characters, it is
+ * re-read whole after compaction and `/clear` instead of shrinking to a
+ * pointer, and general-purpose subagents receive it.
+ *
+ * The switch is the event itself: the settings hook is passed
+ * `om_mod: "standdown"` and exits, but only on an event this hook actually
+ * handled. The work is done before `next`, so if it fails the hook throws,
+ * Claude Code skips it, and the settings hook gets the original event and
+ * runs as it would without the mod.
+ */
+
+/** Where the delivered context is also written, so /memory opens what the model received. Gitignored. */
+const CONTEXT_FILE = ".claude/session-context.md";
+
+/**
+ * The context this session's instruction file carries. In `$.state`, not a
+ * module variable: the host keeps it for the session, across a hot reload of
+ * this module. Each classic.SessionStart clears it before its run.
+ */
+const sessionContext = atom({ plugin: "obsidian-mind", key: "context" } as const, null);
+
+/** Run one of the vault's hook scripts with `input` on stdin; its stdout, or a throw. */
+async function runScript($: EngineInterface, root: string, script: string, input: object): Promise<string> {
+ const run = await $.process.run(["node", "--disable-warning=ExperimentalWarning", "--experimental-strip-types", `${root}/.claude/scripts/${script}`], {
+ cwd: root,
+ env: { CLAUDE_PROJECT_DIR: root },
+ stdin: JSON.stringify(input),
+ timeoutMs: 30_000,
+ });
+ if (run.exitCode !== 0 || run.stdout.trim() === "") {
+ throw new Error(`${script} exited ${run.exitCode}: ${run.stderr.slice(0, 300)}`);
+ }
+ // A cut output would stand the hook down for part of what it delivers.
+ if (run.isStdoutTruncated) throw new Error(`${script} printed more than process.run keeps`);
+ return run.stdout;
+}
+
+export const register: Register = (on) => {
+ on("classic.SessionStart", async ($, e, next) => {
+ // If this run fails, the settings hook runs instead. At a start that
+ // begins a conversation it prints the full layer, so the old context is
+ // cleared first (and the render redrawn) or it would ride beside the
+ // fresh one. At a compaction it prints only a pointer, trusting the
+ // static half to be in the conversation already; under the mod it never
+ // was, so there the last good context is kept rather than lost.
+ if (e.source !== "compact") {
+ await update($, sessionContext, () => null);
+ $.ui.invalidate("prompt.context");
+ }
+ const root = await $.session.root();
+ const text = await runScript($, root, "session-start.ts", { ...e, om_mod: "deliver" });
+ await update($, sessionContext, () => text);
+ // Not awaited: delivery does not depend on the file, so a slow, hung or
+ // failed write never holds up the session. The file only backs what
+ // /memory shows. Runs are minutes apart (startup, then a compaction), so
+ // two writes landing out of order is not a case worth machinery: a
+ // deadline would need a timer that outlives this hook, and a chain
+ // without one would let a hung write stall every later write.
+ $.fs.write(`${root}/${CONTEXT_FILE}`, text).catch(() => {});
+ $.ui.invalidate("prompt.context");
+ return next({ ...e, om_mod: "standdown" } as typeof e);
+ });
+
+ on("prompt.context", async ($, e, next) => {
+ const below = await next(e);
+ const text = await read($, sessionContext);
+ if (text === null) return below;
+ return withSessionContext(below, `${await $.session.root()}/${CONTEXT_FILE}`, text);
+ });
+};
diff --git a/.claude/skills/obsidian-mind/hooks/world.ts b/.claude/skills/obsidian-mind/hooks/world.ts
new file mode 100644
index 0000000..5cda21b
--- /dev/null
+++ b/.claude/skills/obsidian-mind/hooks/world.ts
@@ -0,0 +1,52 @@
+import type { test } from "claude-code/testing";
+
+// The engine and the vault beneath the mod, for the plugin tests. Each test's
+// `on` hooks sit below the mod; these stand in for the host's calls and for
+// the settings hooks the mod passes events down to. Shared by every suite, so
+// a change to the host's reply shapes is made in one place.
+
+/** The `on` a plugin test receives. */
+export type On = Parameters<Extract<Parameters<typeof test>[1], (...args: never[]) => unknown>>[1];
+
+/** What a vault script prints, as `process.run` reports it. */
+export type Reply = { exitCode: number; stdout: string; stderr?: string; truncated?: boolean };
+
+export const ROOT = "/vault";
+
+export type World = {
+ /** Each script the mod ran: its argv and init (cwd, env, stdin). */
+ runs: Array<{ argv: readonly string[]; init?: { cwd?: string; env?: Record<string, string>; stdin?: string } }>;
+ /** Each settings-hook event the mod passed down, by event name. */
+ passedDown: Record<"SessionStart", Array<Record<string, unknown>>>;
+ writes: Array<{ path: string; text: string }>;
+ invalidated: string[];
+};
+
+/**
+ * Stub the host beneath the mod. `reply` answers each `process.run`; a call
+ * on `$` is answered `{ value }`. `hangFirstWrite` makes the first `fs.write`
+ * never settle, to prove delivery does not wait on it.
+ */
+export function engine(on: On, reply: () => Reply, options: { hangFirstWrite?: boolean } = {}): World {
+ const world: World = { runs: [], passedDown: { SessionStart: [] }, writes: [], invalidated: [] };
+ on("session.root", () => ({ value: ROOT }));
+ on("process.run", (_$, e) => {
+ world.runs.push(e as World["runs"][number]);
+ const { exitCode, stdout, stderr = "", truncated = false } = reply();
+ return { value: { exitCode, stdout, stderr, isStdoutTruncated: truncated, isStderrTruncated: false } };
+ });
+ on("fs.write", (_$, e) => {
+ world.writes.push(e);
+ if (options.hangFirstWrite && world.writes.length === 1) return new Promise<never>(() => {});
+ return { value: undefined };
+ });
+ on("ui.invalidate", (_$, e) => {
+ world.invalidated.push(e.event);
+ return { value: undefined };
+ });
+ on("classic.SessionStart", (_$, e) => {
+ world.passedDown.SessionStart.push(e as unknown as Record<string, unknown>);
+ return {};
+ });
+ return world;
+}
diff --git a/.claude/skills/obsidian-mind/types/index.d.ts b/.claude/skills/obsidian-mind/types/index.d.ts
new file mode 100644
index 0000000..30ffbc7
--- /dev/null
+++ b/.claude/skills/obsidian-mind/types/index.d.ts
@@ -0,0 +1,11 @@
+// The mod's per-session state: what the host keeps for it for the session,
+// across a hot reload of the module.
+
+declare module "claude-code" {
+ interface PluginState {
+ "obsidian-mind": {
+ /** The session context this session's instruction file carries; null when none was delivered. */
+ context: string | null;
+ };
+ }
+}
diff --git a/.github/scripts/generate-changelog.ts b/.github/scripts/generate-changelog.ts
index ad4bf1d..7367ee1 100644
--- a/.github/scripts/generate-changelog.ts
+++ b/.github/scripts/generate-changelog.ts
@@ -451,6 +451,38 @@ function updateShardYaml(version: string): void {
writeFileSync(path, bumpShardYamlVersion(content, version), { encoding: "utf-8" });
}
+/** Where the template's Claude Code mod declares its version. */
+export const PLUGIN_JSON = ".claude/skills/obsidian-mind/.claude-plugin/plugin.json";
+
+/**
+ * Set the mod's `version` in its plugin.json to the release version. The mod
+ * ships inside the template, so it carries the template's version; Claude
+ * Code's strict validation requires the field, and a release owns it like it
+ * owns vault-manifest.json and shard.yaml. Key order and formatting are kept.
+ */
+export function bumpPluginJsonVersion(content: string, version: string): string {
+ const plugin = JSON.parse(content) as Record<string, unknown>;
+ if (typeof plugin["version"] !== "string") {
+ throw new Error("plugin.json has no string `version` — refusing to write.");
+ }
+ plugin["version"] = normalizeVersion(version);
+ return JSON.stringify(plugin, null, 2) + "\n";
+}
+
+function updatePluginJson(version: string): void {
+ let content: string;
+ try {
+ content = readFileSync(PLUGIN_JSON, { encoding: "utf-8" });
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ process.stderr.write(`${PLUGIN_JSON} not present — skipping the mod's version bump.\n`);
+ return;
+ }
+ throw err;
+ }
+ writeFileSync(PLUGIN_JSON, bumpPluginJsonVersion(content, version), { encoding: "utf-8" });
+}
+
function main(): void {
const version = process.argv[2];
if (!version) {
@@ -480,6 +512,7 @@ function main(): void {
prependToChangelog(section, version);
updateManifest(version, prevTag);
updateShardYaml(version);
+ updatePluginJson(version);
// Print section for GitHub Release body
process.stdout.write(section);
diff --git a/.github/workflows/mod.yml b/.github/workflows/mod.yml
new file mode 100644
index 0000000..4ad8252
--- /dev/null
+++ b/.github/workflows/mod.yml
@@ -0,0 +1,81 @@
+name: Mod
+
+# The Claude Code mod in .claude/skills/obsidian-mind/ is checked by Claude
+# Code itself: `plugin validate --strict` reads its manifest and module the way
+# the engine will and refuses what the engine would, and `plugin test` runs its
+# *.test.ts files against the real engine.
+#
+# Pushes and pull requests use a pinned CLI, so main never turns red without a
+# change in the repo. A weekly run uses the latest CLI: the mod API is young
+# and moves between releases, and a break should show there first.
+
+on:
+ push:
+ branches: [main]
+ # The mod runs the vault's hook scripts, so any change under
+ # .claude/scripts/ (lib/ included) can change what it delivers.
+ paths: &mod-paths
+ - '.claude/skills/obsidian-mind/**'
+ - '.claude/scripts/**'
+ # The README check below reads every README's hooks and calls lines.
+ - 'README*.md'
+ - '.github/workflows/mod.yml'
+ pull_request:
+ paths: *mod-paths
+ schedule:
+ - cron: '17 6 * * 1'
+ workflow_dispatch:
+
+env:
+ # The version the mod is known to work on; the weekly run overrides it.
+ CLAUDE_CODE_VERSION: ${{ github.event_name == 'schedule' && 'latest' || '2.1.288' }}
+
+jobs:
+ mod:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - name: Install Claude Code (CI-only, not shipped)
+ shell: bash
+ run: npm install -g "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" && claude --version
+ - name: Validate the mod
+ shell: bash
+ run: claude plugin validate --strict .claude/skills/obsidian-mind
+ - name: Every README shows the hooks and calls validate reports
+ shell: bash
+ run: |
+ # The READMEs quote these two lines so a user can check the mod before
+ # trusting the folder; a mod that gains a hook or a call must say so.
+ out=$(claude plugin validate .claude/skills/obsidian-mind 2>&1 | sed 's/\x1b\[[0-9;]*m//g')
+ for kind in hooks calls; do
+ line=$(printf '%s\n' "$out" | grep "register.ts $kind:" | sed 's/^[[:space:]]*//' | tr -d '\r')
+ [ -n "$line" ] || { echo "::error::validate printed no $kind line"; exit 1; }
+ for readme in README.md README.ja.md README.ko.md README.zh-CN.md; do
+ # The whole line, not a substring: a README listing an extra call
+ # would otherwise still contain the true line and pass.
+ # A here-string, not a pipe: grep -q exits at its first match, and
+ # under pipefail the tr it leaves writing fails a README that matches.
+ grep -qxF -- "$line" <<<"$(sed 's/^[[:space:]]*//' "$readme" | tr -d '\r')" || { echo "::error::$readme does not show: $line"; exit 1; }
+ done
+ done
+ - name: Test the mod
+ shell: bash
+ run: claude plugin test .claude/skills/obsidian-mind
+ - name: The checks left nothing behind
+ shell: bash
+ run: |
+ # --ignored too: the engine's typings and tsconfig are gitignored, and
+ # a check that writes them should still be seen.
+ residue=$(git status --porcelain --ignored --untracked-files=all)
+ if [ -n "$residue" ]; then
+ echo "::error::checking the mod left files behind in the working tree"
+ echo "$residue"
+ exit 1
+ fi
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 90d7f52..301258f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -142,6 +142,9 @@ jobs:
if [ -f .shardmind/shard.yaml ]; then
git add .shardmind/shard.yaml
fi
+ if [ -f .claude/skills/obsidian-mind/.claude-plugin/plugin.json ]; then
+ git add .claude/skills/obsidian-mind/.claude-plugin/plugin.json
+ fi
# A resumed run finds the changelog and manifests already at $VERSION,
# so nothing stages and `git commit` exits 1 — which under `bash -e`
# killed the job here rather than at whatever actually failed. Ask the
@@ -207,6 +210,17 @@ jobs:
fi
fi
+ # The mod's plugin.json carries the template's version too (optional, like shard.yaml).
+ plugin_path=".claude/skills/obsidian-mind/.claude-plugin/plugin.json"
+ if git cat-file -e "$VERSION:$plugin_path" 2>/dev/null; then
+ plugin=$(git show "$VERSION:$plugin_path" | sed -n 's/.*"version":[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)
+ echo "plugin.json=$plugin"
+ if [ "$plugin" != "$want" ]; then
+ echo "::error::Tagged plugin.json version=$plugin, expected $want"
+ exit 1
+ fi
+ fi
+
- name: Build vault zip
run: |
ZIP_NAME="obsidian-mind-${VERSION}.zip"
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 87ac548..a068748 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -7,12 +7,26 @@ on:
- '.claude/scripts/**'
- '.scripts/**'
- '.shardmind/**'
+ # Suites here also guard files outside .claude/scripts/: the mod's
+ # timeouts against settings.json, plugin.json's version against the
+ # manifest, the hook commands' walk-up, and the delivery gate's judge.
+ - '.claude/skills/obsidian-mind/**'
+ - '.claude/settings.json'
+ - '.github/scripts/**'
+ - 'vault-manifest.json'
- '.github/workflows/test.yml'
pull_request:
paths:
- '.claude/scripts/**'
- '.scripts/**'
- '.shardmind/**'
+ # Suites here also guard files outside .claude/scripts/: the mod's
+ # timeouts against settings.json, plugin.json's version against the
+ # manifest, the hook commands' walk-up, and the delivery gate's judge.
+ - '.claude/skills/obsidian-mind/**'
+ - '.claude/settings.json'
+ - '.github/scripts/**'
+ - 'vault-manifest.json'
- '.github/workflows/test.yml'
jobs:
diff --git a/.gitignore b/.gitignore
index bb93a58..c109b08 100644
--- a/.gitignore
+++ b/.gitignore
@@ -33,6 +33,13 @@ thinking/session-logs/
node_modules/
.claude/scripts/node_modules/
+# The Claude Code mod: the session context it delivers (rewritten every
+# session, read through /memory), and the typings and tsconfig Claude Code
+# writes into a mod folder when it is loaded for development.
+.claude/session-context.md
+.claude/skills/obsidian-mind/.claude-plugin/types/
+.claude/skills/obsidian-mind/tsconfig.json
+
# Hook runtime state (local, self-pruning / debounce sentinel)
.claude/scripts/.hint-state.json
.claude/scripts/.checklist-state.json
diff --git a/AGENTS.md b/AGENTS.md
index 74b4115..646b549 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,7 +51,7 @@ Do not register the raw `qmd` server in a consuming repo — it searches every n
## What's Claude Code-specific
-Only the `~/.claude/` auto-memory loader is truly Claude Code-specific. Everything else — hooks, commands, subagent prompts, vault memory — is portable.
+Two things are Claude Code-specific: the `~/.claude/` auto-memory loader, and the `obsidian-mind` mod in `.claude/skills/obsidian-mind/`, which on Claude Code 2.1.287+ delivers the session context as an instruction file and presents the Stop report. Neither is needed elsewhere: the mod only changes how the settings hooks' output reaches a Claude Code session, and every other agent runs those same hooks directly. Everything else (hooks, commands, subagent prompts, vault memory) is portable.
## Setup
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index a457820..a7ef02f 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -211,6 +211,15 @@ A few specific design choices are worth calling out:
- **A changed `Stop` report reaches the agent too (#256).** A `systemMessage` is shown to the user and never added to the model's context, so the drift the agent is best placed to fix never reached it. And every `Stop` output that does reach the model is printed in full for the user: a `decision: "block"` reason under a "Stop hook error" label (v8.5.0 shipped that), `Stop` `additionalContext` under "Stop hook feedback". `UserPromptSubmit` `additionalContext` is the one channel that reaches the model and is never shown. So when the findings change, `Stop` shows the user a one-line-per-section summary and saves the full report for the session (`lib/stop-handoff.ts`: written atomically, claimed by rename so it is delivered once, the newest report wins, a week-old one is pruned). The next prompt's `classify-message` takes it and hands it to the agent beside any routing hints, with a preface telling it to deal with the user's message first. If the report cannot be saved, `Stop` sends it as feedback instead (Claude Code; Codex's handling of Stop feedback is unverified): visible, but never lost. `SessionEnd` and a `Stop` without a `session_id` have no next prompt to ride, so the user gets the full report.
- **Why not `SessionEnd`.** It looks like the natural home for an end-of-session checklist, but Claude Code discards a SessionEnd hook's `systemMessage`, and Codex documents SessionEnd as advisory and does not surface its `systemMessage`. Wired there, the checklist would reach nobody on two of the three agents. Gemini does display it during shutdown, so Gemini keeps its SessionEnd wiring. The acting path is `/om-wrap-up`, which runs the hygiene pass while tools are still live.
+### The Claude Code mod
+
+Claude Code 2.1.287 added mods: plugins whose code runs inside Claude Code and can wrap the settings-hook events as `classic.<Event>` (PreToolUse rides `tool.call` instead). The template ships one, `obsidian-mind`, at `.claude/skills/obsidian-mind/`; Claude Code loads it in place once the vault folder is trusted, from the session's working folder only.
+
+- **The hooks stay the engine.** Codex and Gemini have no mods, and on Claude Code the mod does not load everywhere (an older CLI, an untrusted folder, a session started in a subfolder, managed-only policy). So the mod adds no behaviour of its own: it runs the same scripts and only changes the channel their output reaches the session through.
+- **The switch rides on the event.** What the mod passes to `next()` is what the settings hooks read on stdin (`lib/om-mod.ts`). For an event it handles, the mod does its own work first and then passes `om_mod: "standdown"`, and the script exits. The flag exists only on events the mod's hook actually ran on: a mod that throws, crashed or never loaded sends the original event, and the hook runs as without it. An environment variable would outlive a dead mod and leave the hooks silent; answering the event without `next` would silence the user's own hooks too.
+- **SessionStart becomes an instruction file.** The mod runs `session-start.ts` with `om_mod: "deliver"` (the full layer, held to `eager_layer_instruction_budget_bytes`) and adds the output in `prompt.context` as a project instruction file. Claude Code re-reads instruction files after compaction and `/clear`, gives them to general-purpose subagents, and does not cut them at the hook limit. The text is kept in the mod's per-session state (`$.state`, which survives a hot reload of the module) and cleared (and redrawn) before every run that starts a conversation, so a run that fails there cannot leave an older context riding beside the full layer the settings hook then prints. A compaction keeps it: the hook's fallback there is only a pointer to a static half that, under the mod, was never in the conversation, so the last good context is the better thing to keep. It is also written to `.claude/session-context.md` (gitignored), which is where `/memory` points: unawaited, so delivery never waits on the file. The file is only what `/memory` shows: two runs seconds apart could in principle leave the older text on disk, and that case is accepted rather than guarded, since runs are minutes apart in practice.
+- **The work happens before `next`.** If the script fails, the mod's hook throws before passing the flag down, Claude Code skips it, and the settings hook delivers as usual. A failure after `next` resolved would keep the stood-down result, so nothing runs after it.
+
---
## QMD Integration
diff --git a/CLAUDE.md b/CLAUDE.md
index d23a5a9..c2ce0fc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -52,7 +52,7 @@ Defined in `.claude/commands/`. Claude Code auto-surfaces every command with its
| `.claude/commands/` | Slash commands (auto-surfaced in-session; catalog in `brain/Skills.md`) | One `.md` per command |
| `.claude/agents/` | Subagents | See subagents table below |
| `.claude/scripts/` | Hook scripts + the MCP server | `session-start.ts`, `classify-message.ts`, `validate-write.ts`, `pre-compact.ts`, `stop-checklist.ts`, `charcount.ts`, `om-mcp.mjs` (see **Reaching the vault from another repo** below) |
-| `.claude/skills/` | Obsidian + QMD skills | Loaded automatically via Skill tool |
+| `.claude/skills/` | Obsidian + QMD skills, and the `obsidian-mind` Claude Code mod | Skills load via the Skill tool; the mod loads as a plugin on Claude Code 2.1.287+ |
## Obsidian CLI
@@ -446,6 +446,8 @@ Five lifecycle hooks in `.claude/settings.json`:
| PreCompact | Before context compaction | Backs up session transcript to `thinking/session-logs/` |
| Stop | After every response | Checklist + concrete vault-hygiene drift findings (same scan as SessionStart), shown once per session and again only when the findings change; hands drift to `om-tidy`. A Stop `systemMessage` reaches only the user, and every Stop output that reaches the agent is also printed in full for the user. So a changed report shows the user a one-line-per-section summary and saves the full report for the next prompt, where the UserPromptSubmit hook hands it to the agent unseen; the agent deals with the user's message first, then acts, asks, or leaves it. If the report cannot be saved, it goes out as Stop feedback instead. SessionEnd and a Stop without a session id show the full report. Also triggers the debounced QMD refresh. For thorough review, use `/om-wrap-up` instead. |
+**On Claude Code 2.1.287+, the `obsidian-mind` mod** (`.claude/skills/obsidian-mind/`) delivers the SessionStart context as an instruction file instead: it runs `session-start.ts` itself and passes the settings hook `om_mod: "standdown"` for that event. The context then survives compaction whole and reaches general-purpose subagents (Explore and Plan skip instruction files by design); `/memory` shows it as `.claude/session-context.md`. Wherever the mod does not load (Codex, Gemini, older Claude Code, an untrusted folder, a session started in a vault subfolder), the hooks above run unchanged.
+
## Write-Correctness Laws
Each law exists because its absence caused real correction work in vaults running this template. Violating them re-creates documented failures.
diff --git a/GEMINI.md b/GEMINI.md
index 74b4115..646b549 100644
--- a/GEMINI.md
+++ b/GEMINI.md
@@ -51,7 +51,7 @@ Do not register the raw `qmd` server in a consuming repo — it searches every n
## What's Claude Code-specific
-Only the `~/.claude/` auto-memory loader is truly Claude Code-specific. Everything else — hooks, commands, subagent prompts, vault memory — is portable.
+Two things are Claude Code-specific: the `~/.claude/` auto-memory loader, and the `obsidian-mind` mod in `.claude/skills/obsidian-mind/`, which on Claude Code 2.1.287+ delivers the session context as an instruction file and presents the Stop report. Neither is needed elsewhere: the mod only changes how the settings hooks' output reaches a Claude Code session, and every other agent runs those same hooks directly. Everything else (hooks, commands, subagent prompts, vault memory) is portable.
## Setup
diff --git a/README.ja.md b/README.ja.md
index 4beda5c..c994134 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -203,6 +203,25 @@ QMDは**3つの小さなモデルをローカルで**実行します。設定す
> [!TIP]
> ただ話すだけ。フックがルーティングを処理します。
+### 🧩 Claude Code の mod
+
+Claude Code 2.1.287 以降では、ボールトは mod も同梱しています。`.claude/skills/obsidian-mind/` にある、Claude Code の内部で動くプラグインです。ボールト自身のフックスクリプトを実行し、その出力がセッションに届く経路だけを変えます。
+
+- **セッションコンテキストは、`CLAUDE.md` と同じく instruction ファイルとして届きます。** コンパクションや `/clear` の後もそのまま全体が読み直され(フック出力ではポインタに縮みます)、汎用サブエージェントにも届き(フック出力は届きません)、Claude Code のフック出力の 10,000 文字制限で切られません。予算は `vault-manifest.json` の `eager_layer_instruction_budget_bytes` です。オープンタスクのように縮まないセクションは、それを超えることがあります。`/memory` には `.claude/session-context.md` として表示されます。
+
+mod は処理するイベントごとに、対応するフックに待機を伝えます。mod が読み込まれない場所では、フックはこれまでどおり動きます。Codex と Gemini、古い Claude Code、ボールトのサブフォルダで始めたセッション(ボールトのルートで起動するか、そこへ `/cd` して `/clear`)、信頼していないフォルダです。mod は、ボールトに対する Claude Code の信頼確認を承認した後にだけ読み込まれます。
+
+mod はサンドボックス化されておらず、あなたの権限で動くコードです。フォルダを信頼する前に内容を確認してください。`claude plugin validate .claude/skills/obsidian-mind` が、フックするイベントと行う呼び出しをすべて一覧にします(ボールト自身のスクリプトを実行し、コンテキストファイルを書くだけです)。無効にするには、`.claude/settings.local.json` に `"enabledPlugins": { "obsidian-mind@skills-dir": false }` を追加します。
+
+<!-- mod-validate:start -->
+この版の mod で、その出力のうち確認すべき 2 行は次のとおりです:
+
+```text
+ ❯ ./register.ts hooks: classic.SessionStart, prompt.context
+ ❯ ./register.ts calls: $.fs.write, $.process.run (via runScript), $.session.root, $.state.get, $.state.set, $.ui.invalidate
+```
+<!-- mod-validate:end -->
+
### ⚡ トークン効率
obsidian-mindはボールト全体をコンテキストに読み込み**ません**。階層型ローディングでトークンコストを抑えます:
@@ -421,7 +440,7 @@ templates/ YAMLフロントマター付きObsidianテンプレー
commands/ 18個のスラッシュコマンド
agents/ 9個のサブエージェント
scripts/ フックスクリプト + charcount.tsユーティリティ
- skills/ Obsidian + QMDスキル
+ skills/ Obsidian + QMDスキル、obsidian-mind mod
settings.json 5つのフック設定
.scripts/ ボールトレベルのツール — QMDブートストラップ(新規クローン時に一度実行)
diff --git a/README.ko.md b/README.ko.md
index 0c427a3..eb2dd9f 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -203,6 +203,25 @@ QMD는 **세 개의 작은 모델을 로컬에서** 실행하므로, 설정할 A
> [!TIP]
> 그냥 이야기하세요. 훅이 라우팅을 처리합니다.
+### 🧩 Claude Code mod
+
+Claude Code 2.1.287 이상에서는 볼트가 mod도 함께 제공합니다. `.claude/skills/obsidian-mind/`에 있는, Claude Code 안에서 실행되는 플러그인입니다. 볼트 자체의 훅 스크립트를 실행하고, 그 출력이 세션에 전달되는 경로만 바꿉니다.
+
+- **세션 컨텍스트가 `CLAUDE.md`처럼 instruction 파일로 전달됩니다.** 컴팩션과 `/clear` 후에도 전체가 다시 읽히고(훅 출력은 포인터로 줄어듭니다), 범용 서브에이전트에도 전달되며(훅 출력은 전달되지 않습니다), Claude Code 훅 출력의 10,000자 제한에 잘리지 않습니다. 예산은 `vault-manifest.json`의 `eager_layer_instruction_budget_bytes`이며, 열린 작업처럼 줄어들지 않는 섹션은 이를 넘을 수 있습니다. `/memory`에는 `.claude/session-context.md`로 표시됩니다.
+
+mod는 처리하는 이벤트마다 해당 훅에 대기하라고 알립니다. mod가 로드되지 않는 곳에서는 훅이 이전과 똑같이 동작합니다. Codex와 Gemini, 이전 버전의 Claude Code, 볼트 하위 폴더에서 시작한 세션(볼트 루트에서 실행하거나, 그곳으로 `/cd`한 뒤 `/clear`), 신뢰하지 않은 폴더입니다. mod는 볼트에 대한 Claude Code의 신뢰 확인을 수락한 뒤에만 로드됩니다.
+
+mod는 샌드박스 없이 사용자의 권한으로 실행되는 코드이므로, 폴더를 신뢰하기 전에 내용을 확인하세요. `claude plugin validate .claude/skills/obsidian-mind`가 훅하는 모든 이벤트와 수행하는 모든 호출을 나열합니다(볼트 자체의 스크립트를 실행하고 컨텍스트 파일을 쓰는 것이 전부입니다). 끄려면 `.claude/settings.local.json`에 `"enabledPlugins": { "obsidian-mind@skills-dir": false }`를 추가하세요.
+
+<!-- mod-validate:start -->
+이 버전의 mod에서 출력 중 확인할 두 줄은 다음과 같습니다:
+
+```text
+ ❯ ./register.ts hooks: classic.SessionStart, prompt.context
+ ❯ ./register.ts calls: $.fs.write, $.process.run (via runScript), $.session.root, $.state.get, $.state.set, $.ui.invalidate
+```
+<!-- mod-validate:end -->
+
### ⚡ 토큰 효율성
obsidian-mind는 전체 볼트를 컨텍스트에 로드하지 **않습니다**. 계층형 로딩으로 토큰 비용을 최소화합니다:
@@ -421,7 +440,7 @@ templates/ YAML 프론트매터가 포함된 Obsidian 템플릿
commands/ 18개 슬래시 명령어
agents/ 9개 서브에이전트
scripts/ 훅 스크립트 + charcount.ts 유틸리티
- skills/ Obsidian + QMD 스킬
+ skills/ Obsidian + QMD 스킬, obsidian-mind mod
settings.json 5개 훅 설정
.scripts/ 볼트 수준 도구 — QMD 부트스트랩 (새 클론에서 한 번 실행)
diff --git a/README.md b/README.md
index a74c1c2..50bc01f 100644
--- a/README.md
+++ b/README.md
@@ -210,6 +210,25 @@ Five lifecycle hooks handle routing automatically:
> [!TIP]
> You just talk. The hooks handle the routing.
+### 🧩 The Claude Code mod
+
+On Claude Code 2.1.287 or later, the vault also ships a mod: `.claude/skills/obsidian-mind/`, a plugin whose code runs inside Claude Code. It runs the vault's own hook scripts and changes only how their output reaches the session:
+
+- **Session context arrives as an instruction file**, the way `CLAUDE.md` does. It is re-read whole after compaction and `/clear` (as hook output it shrinks to a pointer), it reaches general-purpose subagents (hook output never does), and it is not cut at Claude Code's 10,000-character hook limit. Its budget is `eager_layer_instruction_budget_bytes` in `vault-manifest.json`; sections that never shrink, such as open tasks, can still take it past that. `/memory` lists it as `.claude/session-context.md`.
+
+For each event it handles, the mod tells the matching hook to stand down. Wherever the mod does not load, the hooks run exactly as before: Codex and Gemini, older Claude Code, a session started in a vault subfolder (launch from the vault root, or `/cd` there and `/clear`), or a folder you have not trusted. It loads only after you accept Claude Code's trust prompt for the vault.
+
+A mod is unsandboxed code that runs with your permissions, so check what it does before trusting the folder: `claude plugin validate .claude/skills/obsidian-mind` lists every event it hooks and every call it makes (it runs the vault's own scripts and writes the context file, nothing else). To turn it off, add `"enabledPlugins": { "obsidian-mind@skills-dir": false }` to `.claude/settings.local.json`.
+
+<!-- mod-validate:start -->
+The two lines that matter in its output, for this version of the mod:
+
+```text
+ ❯ ./register.ts hooks: classic.SessionStart, prompt.context
+ ❯ ./register.ts calls: $.fs.write, $.process.run (via runScript), $.session.root, $.state.get, $.state.set, $.ui.invalidate
+```
+<!-- mod-validate:end -->
+
### ⚡ Token Efficiency
obsidian-mind does **not** dump your entire vault into context. It uses tiered loading to keep token costs low:
@@ -518,7 +537,7 @@ templates/ Obsidian templates with YAML frontmatter
commands/ 18 slash commands
agents/ 9 subagents
scripts/ Hook scripts + charcount.ts utility
- skills/ Obsidian + QMD skills
+ skills/ Obsidian + QMD skills, and the obsidian-mind mod
settings.json 5 hooks configuration
.scripts/ Vault-level tooling — QMD bootstrap (run once on a fresh clone)
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 521c68a..7bea487 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -203,6 +203,25 @@ QMD **在本地运行三个小模型**,因此不需要配置 API 密钥,没
> [!TIP]
> 你只需要正常对话。钩子会处理路由。
+### 🧩 Claude Code mod
+
+在 Claude Code 2.1.287 及以上版本中,仓库还附带一个 mod:`.claude/skills/obsidian-mind/`,一个在 Claude Code 内部运行的插件。它运行仓库自身的钩子脚本,只改变其输出到达会话的方式:
+
+- **会话上下文像 `CLAUDE.md` 一样以 instruction 文件的形式送达。** 压缩和 `/clear` 之后会被完整地重新读取(作为钩子输出时会缩减为一个指针),能送达通用子代理(钩子输出送达不了),也不会被 Claude Code 钩子输出的 10,000 字符上限截断。其预算是 `vault-manifest.json` 中的 `eager_layer_instruction_budget_bytes`;像未完成任务这样不会缩减的部分仍可能超出它。`/memory` 中显示为 `.claude/session-context.md`。
+
+对于它处理的每个事件,mod 会通知对应的钩子让出。在 mod 未加载的地方,钩子与以前完全一样地运行:Codex 和 Gemini、旧版 Claude Code、在仓库子文件夹中启动的会话(请在仓库根目录启动,或 `/cd` 到根目录后执行 `/clear`)、以及未信任的文件夹。只有在你接受了 Claude Code 对该仓库的信任提示之后,mod 才会加载。
+
+mod 是没有沙箱、以你的权限运行的代码,因此在信任该文件夹之前请先检查它的行为:`claude plugin validate .claude/skills/obsidian-mind` 会列出它挂钩的每个事件和发出的每个调用(它只运行仓库自身的脚本并写入上下文文件)。要关闭它,在 `.claude/settings.local.json` 中加入 `"enabledPlugins": { "obsidian-mind@skills-dir": false }`。
+
+<!-- mod-validate:start -->
+对于这一版本的 mod,其输出中值得确认的两行如下:
+
+```text
+ ❯ ./register.ts hooks: classic.SessionStart, prompt.context
+ ❯ ./register.ts calls: $.fs.write, $.process.run (via runScript), $.session.root, $.state.get, $.state.set, $.ui.invalidate
+```
+<!-- mod-validate:end -->
+
### ⚡ Token 效率
obsidian-mind **不会**将整个 vault 加载到上下文中。它使用分层加载来控制 token 成本:
@@ -421,7 +440,7 @@ templates/ 带有 YAML frontmatter 的 Obsidian 模板
commands/ 18 个斜杠命令
agents/ 9 个子代理
scripts/ 钩子脚本 + charcount.ts 工具
- skills/ Obsidian + QMD 技能
+ skills/ Obsidian + QMD 技能,obsidian-mind mod
settings.json 5 个钩子配置
.scripts/ 仓库级工具 — QMD 引导脚本(新克隆时运行一次)