A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
refactor: migrate ShardMind hooks to split bootstrap/personalize lifecycle (#75) (#96)
Brenno Ferrari78484b1dcce6
diff --git a/.claude/scripts/tests/bootstrap-hook.test.ts b/.claude/scripts/tests/bootstrap-hook.test.tsnew file mode 100644index 0000000..ce87349--- /dev/null+++ b/.claude/scripts/tests/bootstrap-hook.test.ts@@ -0,0 +1,100 @@+/**+ * Unit tests for the v6 bootstrap hook (.shardmind/hooks/bootstrap.ts).+ *+ * Bootstrap owns the unmanaged-artifact responsibilities — git init and the+ * QMD index — split out of the legacy post-install hook. Drives the exported+ * `ensureGitRepo` and the default-export orchestration against synthetic+ * vaults under a per-test temp directory. The subprocess paths (`git init`,+ * `node qmd-bootstrap.ts`) get integration coverage through ShardMind's+ * contract suite when it runs against this shard; here we exercise the+ * skip/gate branches that avoid spawning.+ *+ * Each test gets its own `os.tmpdir() + crypto.randomUUID()` directory to+ * avoid the parallel-load flake pattern documented in the take-next skill.+ */++import { test, describe, beforeEach, afterEach } from "node:test";+import assert from "node:assert/strict";+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { randomUUID } from "node:crypto";++import bootstrap, { ensureGitRepo } from "../../../.shardmind/hooks/bootstrap.ts";++async function makeTempDir(prefix: string): Promise<string> {+ return mkdtemp(join(tmpdir(), `${prefix}-${randomUUID()}-`));+}++const isENOENT = (err: unknown): boolean =>+ (err as NodeJS.ErrnoException).code === "ENOENT";++describe("ensureGitRepo", () => {+ let vault: string;++ beforeEach(async () => {+ vault = await makeTempDir("bootstrap-hook");+ });++ afterEach(async () => {+ await rm(vault, { recursive: true, force: true });+ });++ test("skips when .git/ already exists", async () => {+ await mkdir(join(vault, ".git"), { recursive: true });+ // HEAD is one of the few files git always writes during init; if+ // the hook's skip-branch fires correctly, our pre-existing empty+ // .git/ stays empty.+ await ensureGitRepo(vault);+ await assert.rejects(+ readFile(join(vault, ".git", "HEAD"), "utf-8"),+ isENOENT,+ "ensureGitRepo must not run `git init` when .git/ already exists",+ );+ });+});++describe("bootstrap (default export) — orchestration gates", () => {+ // Pre-creates `.git/` to short-circuit `ensureGitRepo` (avoiding a real+ // `git init` subprocess) and pins `qmd_enabled: false` so `bootstrapQmd`+ // is gated off — leaving bootstrap a no-op that must not write anything.+ let vault: string;++ beforeEach(async () => {+ vault = await makeTempDir("bootstrap-hook");+ await mkdir(join(vault, ".git"), { recursive: true });+ });++ afterEach(async () => {+ await rm(vault, { recursive: true, force: true });+ });++ function makeCtx(overrides: Partial<{ qmdEnabled: boolean }>): {+ slot: "bootstrap";+ vaultRoot: string;+ values: Record<string, unknown>;+ modules: Record<string, "included" | "excluded">;+ shard: { name: string; version: string };+ previousVersion?: string;+ } {+ return {+ slot: "bootstrap",+ vaultRoot: vault,+ values: {+ user_name: "Jane Engineer",+ org_name: "Independent",+ vault_purpose: "engineering",+ qmd_enabled: overrides.qmdEnabled ?? false,+ },+ modules: {},+ shard: { name: "obsidian-mind", version: "6.2.0" },+ };+ }++ test("no-op when .git/ exists and qmd is disabled — writes nothing", async () => {+ await bootstrap(makeCtx({ qmdEnabled: false }));+ // git init skipped (HEAD absent) and qmd gated off (.qmd absent).+ await assert.rejects(readFile(join(vault, ".git", "HEAD"), "utf-8"), isENOENT);+ await assert.rejects(readFile(join(vault, ".qmd", "config.json"), "utf-8"), isENOENT);+ });+});diff --git a/.claude/scripts/tests/post-install-hook.test.ts b/.claude/scripts/tests/personalize-hook.test.tssimilarity index 62%rename from .claude/scripts/tests/post-install-hook.test.tsrename to .claude/scripts/tests/personalize-hook.test.tsindex 5be5401..771152f 100644--- a/.claude/scripts/tests/post-install-hook.test.ts+++ b/.claude/scripts/tests/personalize-hook.test.ts@@ -1,18 +1,23 @@/**- * Unit tests for the v6 post-install hook (.shardmind/hooks/post-install.ts).+ * Unit tests for the v6 personalize hook (.shardmind/hooks/personalize.ts).*- * Drives the named exports against synthetic vaults under a per-test temp- * directory. Covers Invariant 2's binding contract: with values at defaults- * the hook must leave `brain/North Star.md` byte-identical; with a non-empty- * `user_name` the hook personalizes the heading once and is idempotent on- * subsequent runs. The default-export path (which spawns `git`/`node`) isn't- * exercised here — those subprocesses get integration coverage through- * ShardMind's contract suite when it runs against this shard.+ * Personalize owns the managed-file responsibility — the North Star heading —+ * split out of the legacy post-install hook. Drives the exported+ * `personalizeNorthStar` and the default-export against synthetic vaults under+ * a per-test temp directory.+ *+ * NOTE on Invariant 2: the legacy post-install suite asserted that the hook+ * left North Star byte-identical when `valuesAreDefaults === true`. That+ * contract no longer lives here — the engine refuses to call `personalize` at+ * all on an all-defaults install (Invariant 2 is engine-enforced), and+ * `PersonalizeContext` carries no `valuesAreDefaults` flag for the hook to+ * check. The "engine skips personalize on defaults" assertion now belongs to+ * ShardMind's engine test suite. What remains testable here: given the hook+ * IS called, an empty `user_name` is still a no-op (the hook's secondary+ * guard), and a non-empty name personalizes once and is idempotent.** Each test gets its own `os.tmpdir() + crypto.randomUUID()` directory to* avoid the parallel-load flake pattern documented in the take-next skill.- * `beforeEach` / `afterEach` own the lifecycle so test bodies stay focused- * on assertions.*/import { test, describe, beforeEach, afterEach } from "node:test";@@ -22,10 +27,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { randomUUID } from "node:crypto";-import postInstall, {- ensureGitRepo,+import personalize, {personalizeNorthStar,-} from "../../../.shardmind/hooks/post-install.ts";+} from "../../../.shardmind/hooks/personalize.ts";const NORTH_STAR_BASE = `---date:@@ -58,7 +62,7 @@ describe("personalizeNorthStar", () => {let vault: string;beforeEach(async () => {- vault = await makeTempDir("post-install-hook");+ vault = await makeTempDir("personalize-hook");await mkdir(join(vault, "brain"), { recursive: true });await writeFile(join(vault, "brain", "North Star.md"), NORTH_STAR_BASE, "utf-8");});@@ -116,7 +120,7 @@ describe("personalizeNorthStar — ENOENT tolerance", () => {// `brain` deselection (impossible today since `removable: false`,// but the guard costs nothing) or an upstream rename leaves the// path absent.- vault = await makeTempDir("post-install-hook");+ vault = await makeTempDir("personalize-hook");await mkdir(join(vault, "brain"), { recursive: true });});@@ -135,43 +139,15 @@ describe("personalizeNorthStar — ENOENT tolerance", () => {});});-describe("ensureGitRepo", () => {- let vault: string;-- beforeEach(async () => {- vault = await makeTempDir("post-install-hook");- });-- afterEach(async () => {- await rm(vault, { recursive: true, force: true });- });-- test("skips when .git/ already exists", async () => {- await mkdir(join(vault, ".git"), { recursive: true });- // HEAD is one of the few files git always writes during init; if- // the hook's skip-branch fires correctly, our pre-existing empty- // .git/ stays empty.- await ensureGitRepo(vault);- await assert.rejects(- readFile(join(vault, ".git", "HEAD"), "utf-8"),- isENOENT,- "ensureGitRepo must not run `git init` when .git/ already exists",- );- });-});--describe("postInstall (default export) — Invariant 2 binding", () => {- // Drives the orchestration gate `if (!ctx.valuesAreDefaults)` in the- // default export, which the named-export tests can't reach. Pre-creates- // `.git/` to short-circuit `ensureGitRepo` (avoiding a real `git init`- // subprocess on each test) and pins `qmd_enabled: false` so- // `bootstrapQmd` is gated off — leaving the personalization branch as- // the only orchestration path the test exercises.+describe("personalize (default export) — empty-name guard", () => {+ // The engine only reaches this hook when values are non-default, so there+ // is no `valuesAreDefaults` branch to drive. The remaining hook-side gate+ // is the empty-`user_name` guard: a non-default install with a blank name+ // must leave North Star untouched rather than write `# North Star — `.let vault: string;beforeEach(async () => {- vault = await makeTempDir("post-install-hook");- await mkdir(join(vault, ".git"), { recursive: true });+ vault = await makeTempDir("personalize-hook");await mkdir(join(vault, "brain"), { recursive: true });await writeFile(join(vault, "brain", "North Star.md"), NORTH_STAR_BASE, "utf-8");});@@ -180,53 +156,39 @@ describe("postInstall (default export) — Invariant 2 binding", () => {await rm(vault, { recursive: true, force: true });});- function makeCtx(overrides: Partial<{- valuesAreDefaults: boolean;- userName: string;- qmdEnabled: boolean;- }>): {+ function makeCtx(overrides: Partial<{ userName: string }>): {+ slot: "personalize";vaultRoot: string;values: Record<string, unknown>;modules: Record<string, "included" | "excluded">;shard: { name: string; version: string };- valuesAreDefaults: boolean;- newFiles: string[];- removedFiles: string[];} {return {+ slot: "personalize",vaultRoot: vault,values: {user_name: overrides.userName ?? "",org_name: "Independent",vault_purpose: "engineering",- qmd_enabled: overrides.qmdEnabled ?? false,+ qmd_enabled: false,},modules: {},- shard: { name: "obsidian-mind", version: "6.0.0-beta.1" },- valuesAreDefaults: overrides.valuesAreDefaults ?? true,- newFiles: [],- removedFiles: [],+ shard: { name: "obsidian-mind", version: "6.2.0" },};}- test("Invariant 2: leaves North Star byte-identical when valuesAreDefaults", async () => {- await postInstall(makeCtx({ valuesAreDefaults: true }));- const after = await readFile(join(vault, "brain", "North Star.md"), "utf-8");- assert.equal(after, NORTH_STAR_BASE);- });-- test("personalizes North Star when valuesAreDefaults is false and user_name is set", async () => {- await postInstall(makeCtx({ valuesAreDefaults: false, userName: "Jane Engineer" }));+ test("personalizes North Star when user_name is set", async () => {+ await personalize(makeCtx({ userName: "Jane Engineer" }));const after = await readFile(join(vault, "brain", "North Star.md"), "utf-8");assert.match(after, /^# North Star — Jane Engineer$/m);});- test("leaves North Star alone when valuesAreDefaults is false but user_name is empty", async () => {+ test("leaves North Star alone when user_name is empty", async () => {// Empty user_name means the user took the wizard but didn't enter a- // name (some other value drove !valuesAreDefaults). Personalizing+ // name (some other value drove the non-default install). Personalizing// with the empty string would produce the eyesore `# North Star — `;// the hook's secondary guard (userName.trim().length > 0) catches it.- await postInstall(makeCtx({ valuesAreDefaults: false, userName: "" }));+ await personalize(makeCtx({ userName: "" }));const after = await readFile(join(vault, "brain", "North Star.md"), "utf-8");assert.equal(after, NORTH_STAR_BASE);});diff --git a/.claude/scripts/tests/shard-contract.test.ts b/.claude/scripts/tests/shard-contract.test.tsnew file mode 100644index 0000000..583f5b2--- /dev/null+++ b/.claude/scripts/tests/shard-contract.test.ts@@ -0,0 +1,139 @@+/**+ * Shard manifest contract tests.+ *+ * Pins the ShardMind hook-lifecycle migration (#75) and the engine-coupling+ * invariant it introduced: a shard that declares the split `bootstrap` /+ * `personalize` slots MUST also declare `requires.shardmind` at the floor that+ * understands them (>=0.1.3). Without that floor an older engine silently+ * skips the unknown slots — no git init, no QMD index, no personalization —+ * instead of refusing the install. This test fails loudly if a future edit+ * drops the floor, re-introduces the deprecated single `post-install` slot+ * (which would dual-fire against the native slots on a >=0.1.3 engine), or+ * removes one of the three lifecycle hooks.+ *+ * Zero-dep by design: there's no YAML parser in the hook runtime, and+ * `.shardmind/shard.yaml` is a file we own, so a line-oriented scan is robust+ * enough and keeps the test dependency-free (matching the JSON-reading+ * `hook-config.test.ts`). Path resolution is CWD-independent (via+ * `import.meta.url`) so the test passes both under `npm test` (cwd+ * `.claude/scripts`) and under release.yml's repo-root invocation.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");+const shardYaml = readFileSync(resolve(repoRoot, ".shardmind/shard.yaml"), {+ encoding: "utf-8",+});++/** Lowest shardmind engine that understands the split hook lifecycle. */+const MIN_SHARDMIND: readonly [number, number, number] = [0, 1, 3];++function gte(+ a: readonly [number, number, number],+ b: readonly [number, number, number],+): boolean {+ for (let i = 0; i < 3; i++) {+ if (a[i]! !== b[i]!) return a[i]! > b[i]!;+ }+ return true; // equal+}++/**+ * Return the indented sub-block beneath a `key:` line that opens a mapping —+ * the run of lines more indented than the key itself, up to the next sibling+ * key or a dedent. Lets a test scope its assertions to one mapping (e.g.+ * `hooks.bootstrap`) instead of scanning the whole file, so a stray `script:`+ * or `fingerprint:` elsewhere can't produce a false pass. Returns "" if the+ * key isn't found as a block-opener.+ */+function blockUnder(yaml: string, key: string): string {+ const lines = yaml.split(/\r?\n/);+ const opener = new RegExp(`^(\\s*)${key}:\\s*$`);+ let start = -1;+ let indent = 0;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (line === undefined) continue;+ const m = opener.exec(line);+ if (m) {+ start = i;+ indent = (m[1] ?? "").length;+ break;+ }+ }+ if (start === -1) return "";++ const out: string[] = [];+ for (let i = start + 1; i < lines.length; i++) {+ const line = lines[i];+ if (line === undefined) break;+ if (line.trim() === "") {+ out.push(line); // blank lines stay inside the block+ continue;+ }+ const lineIndent = (line.match(/^\s*/)?.[0] ?? "").length;+ if (lineIndent <= indent) break; // sibling key or dedent → block ended+ out.push(line);+ }+ return out.join("\n");+}++describe("shard.yaml — hook lifecycle contract (#75)", () => {+ test("declares the three native lifecycle slots", () => {+ assert.match(shardYaml, /^hooks:/m, "missing hooks block");+ assert.match(shardYaml, /^\s+bootstrap:/m, "missing bootstrap slot");+ assert.match(shardYaml, /^\s+personalize:\s*\S/m, "missing personalize slot");+ assert.match(shardYaml, /^\s+post-update:\s*\S/m, "missing post-update slot");+ });++ test("bootstrap declares a script and a fingerprint", () => {+ // Scope to the hooks.bootstrap block so the assertions can't be+ // satisfied by a `script:`/`fingerprint:` key elsewhere in the file.+ const bootstrap = blockUnder(shardYaml, "bootstrap");+ assert.ok(bootstrap, "missing hooks.bootstrap block");+ assert.match(+ bootstrap,+ /^\s+script:\s*\.shardmind\/hooks\/bootstrap\.ts\s*$/m,+ "bootstrap.script must point at .shardmind/hooks/bootstrap.ts",+ );+ assert.match(+ bootstrap,+ /^\s+fingerprint:\s*"[^"]+"\s*$/m,+ "bootstrap.fingerprint must be set (re-bootstrap-on-update marker)",+ );+ });++ test("does NOT declare the deprecated post-install slot", () => {+ // A >=0.1.3 engine maps post-install -> bootstrap+personalize for+ // back-compat; declaring it alongside the native slots would dual-fire.+ assert.doesNotMatch(+ shardYaml,+ /^\s*post-install:/m,+ "post-install must not coexist with the native slots (dual-fire risk)",+ );+ });++ test(`requires.shardmind floor is >= ${MIN_SHARDMIND.join(".")}`, () => {+ const m = /^\s*shardmind:\s*">=(\d+)\.(\d+)\.(\d+)"/m.exec(shardYaml);+ assert.ok(+ m,+ 'requires.shardmind must declare a ">=X.Y.Z" range so old engines refuse the install',+ );+ const floor: [number, number, number] = [+ Number(m![1]),+ Number(m![2]),+ Number(m![3]),+ ];+ assert.ok(+ gte(floor, MIN_SHARDMIND),+ `requires.shardmind floor ${floor.join(".")} is below the ${MIN_SHARDMIND.join(+ ".",+ )} the split hook lifecycle needs`,+ );+ });+});diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 1c0ab13..38086a6 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -6,11 +6,13 @@ on:paths:- '.claude/scripts/**'- 'scripts/**'+ - '.shardmind/**'- '.github/workflows/test.yml'pull_request:paths:- '.claude/scripts/**'- 'scripts/**'+ - '.shardmind/**'- '.github/workflows/test.yml'jobs:diff --git a/.shardmind/hooks/post-install.ts b/.shardmind/hooks/bootstrap.tssimilarity index 51%rename from .shardmind/hooks/post-install.tsrename to .shardmind/hooks/bootstrap.tsindex 4fdc225..98bd9da 100644--- a/.shardmind/hooks/post-install.ts+++ b/.shardmind/hooks/bootstrap.ts@@ -1,32 +1,31 @@/**- * obsidian-mind post-install hook.+ * obsidian-mind bootstrap hook.*- * Runs once after `shardmind install` writes the vault and its state. Non-fatal:- * throwing surfaces as a warning in the install summary, never rolls back the- * install. See ShardMind docs/ARCHITECTURE.md §9.3.+ * Runs on first install + adopt, and on update whenever `hooks.bootstrap.fingerprint`+ * in shard.yaml changes (see ShardMind docs/AUTHORING.md §Hook lifecycle). Writes+ * *unmanaged* paths only (`.git/`, `.qmd/`) — the engine warns+ * (`HOOK_BOOTSTRAP_MANAGED_WRITE`) if a bootstrap hook touches a managed file, so+ * this hook never edits vault content. Non-fatal: throwing surfaces as a warning in+ * the install summary, never rolls back the install.** Responsibilities (all idempotent, all skippable):* 1. Initialize a git repo at the vault root if one doesn't already exist.- * Creates an *unmanaged* `.git/` directory — Invariant 2 doesn't apply- * (only managed-file edits are gated on `valuesAreDefaults`).- * 2. Personalize the managed `brain/North Star.md` with the user's name —- * gated on `!ctx.valuesAreDefaults` per Invariant 2 (with all values at- * defaults, the install must remain byte-equivalent to `git clone`).- * The engine re-hashes managed files after the hook exits, so state.json- * reflects the post-edit content (#75).- * 3. Bootstrap the QMD semantic index when `qmd_enabled === true`. Creates- * `.qmd/` (unmanaged), so this branch ignores `valuesAreDefaults` and- * runs unconditionally inside the `qmd_enabled` gate. Skips silently if- * the `qmd` binary isn't on PATH — the user gets a note in stdout- * telling them how to install it later. We never hard-fail on optional- * tooling.+ * Creates an *unmanaged* `.git/` directory.+ * 2. Bootstrap the QMD semantic index when `qmd_enabled === true`. Creates+ * `.qmd/` (unmanaged). Skips silently if the `qmd` binary isn't on PATH —+ * the user gets a note in stdout telling them how to install it later. We+ * never hard-fail on optional tooling.*- * `personalizeNorthStar` and `ensureGitRepo` are exported by name so the- * test suite can drive them with synthetic vault layouts.+ * Unlike the legacy `post-install` hook, bootstrap carries no North Star+ * personalization — that moved to `personalize.ts`, which the engine gates on+ * non-default values (Invariant 2 is now engine-enforced, not hook-checked).+ *+ * `ensureGitRepo` is exported by name so the test suite can drive it with+ * synthetic vault layouts.*/import { spawn } from 'node:child_process';-import { access, readFile, writeFile } from 'node:fs/promises';+import { access } from 'node:fs/promises';import { join } from 'node:path';// Vault-relative path to the QMD bootstrap script. Centralized so a future@@ -37,37 +36,25 @@ import { join } from 'node:path';// one.const QMD_BOOTSTRAP_RELATIVE = 'scripts/qmd-bootstrap.ts';-// Local mirror of ShardMind's HookContext shape. Inlined (rather than imported-// from `shardmind/runtime`) so obsidian-mind has no shardmind dependency —-// the engine's hook runner spawns this file via tsx and the types are erased-// at runtime. Kept in sync with `source/runtime/types.ts::HookContext` in-// the shardmind repo. See ShardMind docs/SHARD-LAYOUT.md §Hooks, state, and-// re-hash semantics.-interface HookCtx {+// Local mirror of ShardMind's BootstrapContext shape. Inlined (rather than+// imported from `shardmind/runtime`) so obsidian-mind has no shardmind+// dependency — the engine's hook runner spawns this file via tsx and the types+// are erased at runtime. Kept in sync with `source/runtime/types.ts::BootstrapContext`+// in the shardmind repo. Bootstrap always runs, so it receives no+// `valuesAreDefaults` flag and no `newFiles`/`removedFiles` (those are+// update-only). See ShardMind docs/AUTHORING.md §Per-slot context shapes.+interface BootstrapContext {+ slot: 'bootstrap';vaultRoot: string;values: Record<string, unknown>;modules: Record<string, 'included' | 'excluded'>;shard: { name: string; version: string };previousVersion?: string;- valuesAreDefaults: boolean;- newFiles: string[];- removedFiles: string[];}-export default async function postInstall(ctx: HookCtx): Promise<void> {+export default async function bootstrap(ctx: BootstrapContext): Promise<void> {await ensureGitRepo(ctx.vaultRoot);- // Invariant 2: managed-file edits are gated on `!valuesAreDefaults`. With- // every value at its schema default, the install MUST stay byte-equivalent- // to `git clone` — so we leave North Star alone. When the user supplied a- // non-default name (or any other value), personalize the heading.- if (!ctx.valuesAreDefaults) {- const userName = typeof ctx.values['user_name'] === 'string' ? ctx.values['user_name'] : '';- if (userName.trim().length > 0) {- await personalizeNorthStar(ctx.vaultRoot, userName);- }- }-if (ctx.values['qmd_enabled'] === true) {await bootstrapQmd(ctx.vaultRoot);}@@ -100,39 +87,6 @@ export async function ensureGitRepo(vaultRoot: string): Promise<void> {}}-/**- * Replace `# North Star` with `# North Star — <userName>` once. Idempotent:- * a heading already personalized (with this name or any other) is left- * alone — the regex anchors to the literal verbatim form. ENOENT-tolerant:- * if `brain/` was deselected (the `brain` module is `removable: false`,- * so this shouldn't happen in practice, but the guard costs nothing) or- * the file moved upstream, the hook exits cleanly.- */-export async function personalizeNorthStar(vaultRoot: string, userName: string): Promise<void> {- const target = join(vaultRoot, 'brain', 'North Star.md');- let original: string;- try {- original = await readFile(target, 'utf-8');- } catch (err) {- if ((err as NodeJS.ErrnoException).code === 'ENOENT') {- console.log(`obsidian-mind: ${target} not present — skipping North Star personalization.`);- return;- }- throw err;- }-- // Anchor to the verbatim heading. If the file has already been personalized- // (heading reads `# North Star — <something>`), `^# North Star$/m` won't- // match and the file is left untouched — making the hook idempotent.- if (!/^# North Star$/m.test(original)) {- return;- }-- const personalized = original.replace(/^# North Star$/m, `# North Star — ${userName}`);- await writeFile(target, personalized, 'utf-8');- console.log(`obsidian-mind: personalized brain/North Star.md for ${userName}`);-}-async function bootstrapQmd(vaultRoot: string): Promise<void> {const bootstrap = join(vaultRoot, QMD_BOOTSTRAP_RELATIVE);try {diff --git a/.shardmind/hooks/personalize.ts b/.shardmind/hooks/personalize.tsnew file mode 100644index 0000000..9d65691--- /dev/null+++ b/.shardmind/hooks/personalize.ts@@ -0,0 +1,85 @@+/**+ * obsidian-mind personalize hook.+ *+ * Runs on first install + adopt ONLY, and only when the user supplied non-default+ * values — the engine refuses to call `personalize` on an all-defaults install+ * (Invariant 2: a defaults-only install must stay byte-equivalent to `git clone`).+ * That gate is now engine-enforced, so this hook carries no `valuesAreDefaults`+ * check of its own. See ShardMind docs/AUTHORING.md §Hook lifecycle.+ *+ * Writes *managed* files only — the engine warns if a personalize hook creates+ * an unmanaged path. The engine re-hashes managed files after the hook exits, so+ * state.json reflects the post-edit content. Non-fatal: throwing surfaces as a+ * warning in the install summary, never rolls back the install.+ *+ * Responsibility: personalize the managed `brain/North Star.md` heading with the+ * user's name. The empty-`user_name` guard stays in the hook — a user can drive+ * the install non-default via some other value (e.g. `org_name`) while leaving+ * their name blank, and `# North Star — ` would be an eyesore.+ *+ * `personalizeNorthStar` is exported by name so the test suite can drive it with+ * synthetic vault layouts.+ */++import { readFile, writeFile } from 'node:fs/promises';+import { join } from 'node:path';++// Local mirror of ShardMind's PersonalizeContext shape. Inlined (rather than+// imported from `shardmind/runtime`) so obsidian-mind has no shardmind+// dependency — the engine's hook runner spawns this file via tsx and the types+// are erased at runtime. Kept in sync with `source/runtime/types.ts::PersonalizeContext`+// in the shardmind repo. Personalize runs on first install/adopt only, so it+// receives no `previousVersion`, no `newFiles`/`removedFiles`, and — crucially —+// no `valuesAreDefaults`: if this hook runs, values are non-default by+// construction. See ShardMind docs/AUTHORING.md §Per-slot context shapes.+interface PersonalizeContext {+ slot: 'personalize';+ vaultRoot: string;+ values: Record<string, unknown>;+ modules: Record<string, 'included' | 'excluded'>;+ shard: { name: string; version: string };+}++export default async function personalize(ctx: PersonalizeContext): Promise<void> {+ // The engine only reaches this hook when values are non-default, so no+ // `valuesAreDefaults` check is needed. The empty-name guard remains: a+ // non-default `org_name` (or any other value) with a blank `user_name` must+ // still leave North Star untouched rather than write `# North Star — `.+ const userName = typeof ctx.values['user_name'] === 'string' ? ctx.values['user_name'] : '';+ if (userName.trim().length > 0) {+ await personalizeNorthStar(ctx.vaultRoot, userName);+ }+}++/**+ * Replace `# North Star` with `# North Star — <userName>` once. Idempotent:+ * a heading already personalized (with this name or any other) is left+ * alone — the regex anchors to the literal verbatim form. ENOENT-tolerant:+ * if `brain/` was deselected (the `brain` module is `removable: false`,+ * so this shouldn't happen in practice, but the guard costs nothing) or+ * the file moved upstream, the hook exits cleanly.+ */+export async function personalizeNorthStar(vaultRoot: string, userName: string): Promise<void> {+ const target = join(vaultRoot, 'brain', 'North Star.md');+ let original: string;+ try {+ original = await readFile(target, 'utf-8');+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ console.log(`obsidian-mind: ${target} not present — skipping North Star personalization.`);+ return;+ }+ throw err;+ }++ // Anchor to the verbatim heading. If the file has already been personalized+ // (heading reads `# North Star — <something>`), `^# North Star$/m` won't+ // match and the file is left untouched — making the hook idempotent.+ if (!/^# North Star$/m.test(original)) {+ return;+ }++ const personalized = original.replace(/^# North Star$/m, `# North Star — ${userName}`);+ await writeFile(target, personalized, 'utf-8');+ console.log(`obsidian-mind: personalized brain/North Star.md for ${userName}`);+}diff --git a/.shardmind/hooks/post-update.ts b/.shardmind/hooks/post-update.tsindex 48ce3e1..fb28d79 100644--- a/.shardmind/hooks/post-update.ts+++ b/.shardmind/hooks/post-update.ts@@ -7,7 +7,7 @@* For v6, update-time side effects are minimal:** * Vault structure stays stable across patch / minor bumps. No managed- * file needs personalization on update — the post-install hook handled+ * file needs personalization on update — the personalize hook handled* that once at install time, and the user's edits since then are owned* by the user (and protected by the merge engine).* * QMD's index is kept fresh by the PostToolUse `qmd-refresh.ts` hook@@ -21,24 +21,31 @@* migration ships a new managed file that the hook needs to seed, the* write must be guarded on `ctx.newFiles.includes(path)`.*- * If a future migration requires a re-bootstrap, branch on- * `ctx.previousVersion` here.+ * If a future migration requires a re-bootstrap (e.g. a QMD index schema+ * change), prefer bumping `hooks.bootstrap.fingerprint` in shard.yaml over+ * branching on `ctx.previousVersion` here — the engine re-runs `bootstrap`+ * on update whenever the fingerprint changes, keeping the re-bootstrap logic+ * in one place. See ShardMind docs/AUTHORING.md §Bootstrap fingerprint.*/-// Local mirror of ShardMind's HookContext shape. See post-install.ts for the-// rationale (no shardmind dep; types erased at runtime).-interface HookCtx {+// Local mirror of ShardMind's PostUpdateContext shape. See bootstrap.ts /+// personalize.ts for the rationale (no shardmind dep; types erased at runtime).+// Kept in sync with `source/runtime/types.ts::PostUpdateContext` in the+// shardmind repo. post-update receives `newFiles`/`removedFiles` (the merge+// delta) but no `valuesAreDefaults` — that flag is install-time only. See+// ShardMind docs/AUTHORING.md §Per-slot context shapes.+interface PostUpdateContext {+ slot: 'post-update';vaultRoot: string;values: Record<string, unknown>;modules: Record<string, 'included' | 'excluded'>;shard: { name: string; version: string };previousVersion?: string;- valuesAreDefaults: boolean;newFiles: string[];removedFiles: string[];}-export default async function postUpdate(ctx: HookCtx): Promise<void> {+export default async function postUpdate(ctx: PostUpdateContext): Promise<void> {const prev = ctx.previousVersion ?? 'unknown';console.log(`obsidian-mind: updated from ${prev} to ${ctx.shard.version}.`);diff --git a/.shardmind/shard-schema.yaml b/.shardmind/shard-schema.yamlindex 8e38e5c..21c7bb7 100644--- a/.shardmind/shard-schema.yaml+++ b/.shardmind/shard-schema.yaml@@ -8,9 +8,11 @@ schema_version: 1## Every value declares a `default` (Invariant 1: defaults must produce a# vault byte-equivalent to `git clone`). `required: true` here pairs with-# an empty default — the post-install hook personalizes North Star only-# when ctx.valuesAreDefaults === false (Invariant 2), so an unset name-# leaves managed files untouched.+# an empty default — the engine only runs the `personalize` hook when values+# are non-default (Invariant 2, engine-enforced), so an all-defaults install+# never touches North Star. The personalize hook keeps a secondary guard for+# an empty `user_name` (non-default via some other value), so an unset name+# still leaves managed files untouched.# ---------------------------------------------------------------------------values:diff --git a/.shardmind/shard.yaml b/.shardmind/shard.yamlindex 7e06bf9..3da2b25 100644--- a/.shardmind/shard.yaml+++ b/.shardmind/shard.yaml@@ -14,9 +14,20 @@ requires:# `--experimental-strip-types` + ESM; required by `.claude/scripts/*.ts`# which are executed natively by Node without a build step.node: ">=22.6.0"+ # Split hook lifecycle (bootstrap/personalize/post-update slots) + the+ # `requires.shardmind` check itself land in shardmind 0.1.3. Older engines+ # don't understand these slots; this floor makes them refuse with+ # SHARDMIND_VERSION_MISMATCH (on engines that enforce it) rather than+ # silently skipping the hooks.+ shardmind: ">=0.1.3"hooks:- post-install: .shardmind/hooks/post-install.ts+ bootstrap:+ script: .shardmind/hooks/bootstrap.ts+ # Bump when the QMD index schema changes — the engine re-runs bootstrap on+ # update whenever this fingerprint differs from the recorded one.+ fingerprint: "qmd-v1"+ personalize: .shardmind/hooks/personalize.tspost-update: .shardmind/hooks/post-update.ts# 60 s to accommodate first-run qmd bootstrap (index creation + initial embed pass).timeout_ms: 60000diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 31c5e16..3211d0c 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -367,13 +367,13 @@ Two ways to bring obsidian-mind into a new directory:**`git clone` — the original.** Clone the repo, open the folder in Obsidian, talk to the agent. Zero machinery beyond git. Every file ships verbatim; no install-time substitution. The hook scripts under `.claude/scripts/` only run when the agent triggers them. This path is the long-standing default and the one new contributors use to read the codebase.-**`shardmind install` — v6.** [ShardMind](https://github.com/breferrari/shardmind) is a package manager for Obsidian vault templates that produces the same vault as `git clone` plus a `.shardmind/` sidecar. A wizard collects four values (`user_name`, `org_name`, `vault_purpose`, `qmd_enabled`), gates eleven modules (4 always-on content, 4 removable content, 3 agent — `claude` / `codex` / `gemini`), and runs a post-install hook (`.shardmind/hooks/post-install.ts`) that initializes git, optionally bootstraps QMD when enabled, and personalizes `brain/North Star.md` with the user's name. The shard contract is locked by three invariants:+**`shardmind install` — v6.** [ShardMind](https://github.com/breferrari/shardmind) is a package manager for Obsidian vault templates that produces the same vault as `git clone` plus a `.shardmind/` sidecar. A wizard collects four values (`user_name`, `org_name`, `vault_purpose`, `qmd_enabled`), gates eleven modules (4 always-on content, 4 removable content, 3 agent — `claude` / `codex` / `gemini`), and runs the lifecycle hooks: `bootstrap` (`.shardmind/hooks/bootstrap.ts`) initializes git and optionally bootstraps QMD when enabled, and `personalize` (`.shardmind/hooks/personalize.ts`) writes the user's name into `brain/North Star.md`. The shard contract is locked by three invariants:1. **Invariant 1 — clone-equivalence under defaults.** `shardmind install --defaults` produces a vault byte-equivalent to `git clone` modulo Tier 1 exclusions (`.git`, `.github`, ephemeral `.obsidian/workspace*.json`), the engine metadata under `.shardmind/`, and a vault-root `shard-values.yaml`.-2. **Invariant 2 — hooks no-op on defaults.** The post-install hook respects `ctx.valuesAreDefaults` — managed-file edits (e.g., the North Star personalization) are gated on a non-default user value. With every value at its default, the install must remain byte-equivalent to clone.+2. **Invariant 2 — hooks no-op on defaults.** Managed-file edits (e.g., the North Star personalization) live in the `personalize` hook, which the engine refuses to call when every value is at its default — so the invariant is engine-enforced, not hook-checked. With every value at its default, the install remains byte-equivalent to clone.3. **Invariant 3 — post-update is additive-only.** The post-update hook restricts managed-file writes to `ctx.newFiles` (paths added by the new version), preventing clobbers of the merge engine's three-way resolution of user edits.-The contract surface lives at `.shardmind/shard.yaml` (manifest), `.shardmind/shard-schema.yaml` (values + module declarations), `.shardmind/hooks/{post-install,post-update}.ts` (lifecycle), and `.shardmindignore` at repo root (excludes `CONTRIBUTING.md`, README translations, marketing media from the install). Spec: [ShardMind `docs/SHARD-LAYOUT.md`](https://github.com/breferrari/shardmind/blob/main/docs/SHARD-LAYOUT.md).+The contract surface lives at `.shardmind/shard.yaml` (manifest), `.shardmind/shard-schema.yaml` (values + module declarations), `.shardmind/hooks/{bootstrap,personalize,post-update}.ts` (lifecycle), and `.shardmindignore` at repo root (excludes `CONTRIBUTING.md`, README translations, marketing media from the install). Spec: [ShardMind `docs/SHARD-LAYOUT.md`](https://github.com/breferrari/shardmind/blob/main/docs/SHARD-LAYOUT.md).**Additive principle.** `shardmind install` produces a strictly larger vault than `git clone` — never smaller, never different on shared paths under defaults. Deleting `.shardmind/` and `shard-values.yaml` from an installed vault leaves a working clone-equivalent vault. The same is true on the source side: deleting `.shardmind/` from this repo would produce a v5.1-shape working vault. ShardMind extends the clone experience; it doesn't replace it.diff --git a/README.ja.md b/README.ja.mdindex 042cd2d..857dea7 100644--- a/README.ja.md+++ b/README.ja.md@@ -106,7 +106,7 @@ mkdir my-vault && cd my-vaultshardmind install github:breferrari/obsidian-mind```-`shardmind install` はカレントディレクトリに書き込むため、先に新しいフォルダを作成して移動してください。ウィザードがあなたの名前、組織、ボールトの目的、含めるエージェント、QMDを有効化するかどうかを収集します。post-installフックがあなたの回答に基づいて`brain/North Star.md`をパーソナライズします。その後:+`shardmind install` はカレントディレクトリに書き込むため、先に新しいフォルダを作成して移動してください。ウィザードがあなたの名前、組織、ボールトの目的、含めるエージェント、QMDを有効化するかどうかを収集します。続いてShardMindがgitを初期化し、必要に応じてQMDをブートストラップし、あなたの回答に基づいて`brain/North Star.md`をパーソナライズします。その後:1. インストールされたフォルダを**Obsidianボールト**として開く2. 設定 → 一般で**Obsidian CLI**を有効化(Obsidian 1.12以上が必要)@@ -368,7 +368,7 @@ templates/ YAMLフロントマター付きObsidianテンプレー.shardmind/ ShardMindサイドカー — `shardmind install`でインストールした場合のみ使用shard.yaml マニフェスト(名前、バージョン、モジュール、フック)shard-schema.yaml ウィザードの値 + モジュールゲーティング- hooks/ post-install(QMDブートストラップ + パーソナライズ)、post-update+ hooks/ bootstrap(git初期化 + QMD)、personalize(North Star)、post-update```> [!NOTE]diff --git a/README.ko.md b/README.ko.mdindex 1e6096b..7b68017 100644--- a/README.ko.md+++ b/README.ko.md@@ -106,7 +106,7 @@ mkdir my-vault && cd my-vaultshardmind install github:breferrari/obsidian-mind```-`shardmind install`은 현재 디렉토리에 기록하므로, 먼저 새 폴더를 만들고 그 안으로 이동하세요. 마법사가 이름, 조직, 볼트 목적, 포함할 에이전트, QMD 활성화 여부를 수집합니다. post-install 훅이 답변에 따라 `brain/North Star.md`를 개인화합니다. 그런 다음:+`shardmind install`은 현재 디렉토리에 기록하므로, 먼저 새 폴더를 만들고 그 안으로 이동하세요. 마법사가 이름, 조직, 볼트 목적, 포함할 에이전트, QMD 활성화 여부를 수집합니다. 이어서 ShardMind가 git을 초기화하고, 필요 시 QMD를 부트스트랩하며, 답변에 따라 `brain/North Star.md`를 개인화합니다. 그런 다음:1. 설치된 폴더를 **Obsidian 볼트**로 엽니다2. 설정 → 일반에서 **Obsidian CLI**를 활성화합니다 (Obsidian 1.12+ 필요)@@ -368,7 +368,7 @@ templates/ YAML 프론트매터가 포함된 Obsidian 템플릿.shardmind/ ShardMind 사이드카 — `shardmind install`로 설치한 경우에만 사용shard.yaml 매니페스트 (이름, 버전, 모듈, 훅)shard-schema.yaml 마법사 값 + 모듈 게이팅- hooks/ post-install (QMD 부트스트랩 + 개인화), post-update+ hooks/ bootstrap (git 초기화 + QMD), personalize (North Star), post-update```> [!NOTE]diff --git a/README.md b/README.mdindex c86b311..6266a6e 100644--- a/README.md+++ b/README.md@@ -105,7 +105,7 @@ mkdir my-vault && cd my-vaultshardmind install github:breferrari/obsidian-mind```-`shardmind install` writes into the current directory, so create and enter a fresh folder first. The wizard collects your name, organization, vault purpose, agents to include, and whether to enable QMD; the post-install hook personalizes `brain/North Star.md` with your answers. Then:+`shardmind install` writes into the current directory, so create and enter a fresh folder first. The wizard collects your name, organization, vault purpose, agents to include, and whether to enable QMD; ShardMind then initializes git, optionally bootstraps QMD, and personalizes `brain/North Star.md` with your answers. Then:1. Open the installed folder as an **Obsidian vault**2. Enable the **Obsidian CLI** in Settings → General (requires Obsidian 1.12+)@@ -375,7 +375,7 @@ templates/ Obsidian templates with YAML frontmatter.shardmind/ ShardMind sidecar — only used if installed via `shardmind install`shard.yaml Manifest (name, version, modules, hooks)shard-schema.yaml Wizard values + module gating- hooks/ post-install (QMD bootstrap + personalization), post-update+ hooks/ bootstrap (git init + QMD), personalize (North Star), post-update```> [!NOTE]diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 047405a..a457eda 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -106,7 +106,7 @@ mkdir my-vault && cd my-vaultshardmind install github:breferrari/obsidian-mind```-`shardmind install` 会写入当前目录,因此请先创建并进入一个新文件夹。向导会收集你的姓名、组织、仓库用途、要包含的 Agent,以及是否启用 QMD。post-install 钩子会根据你的答案个性化 `brain/North Star.md`。然后:+`shardmind install` 会写入当前目录,因此请先创建并进入一个新文件夹。向导会收集你的姓名、组织、仓库用途、要包含的 Agent,以及是否启用 QMD。随后 ShardMind 会初始化 git、按需引导 QMD,并根据你的答案个性化 `brain/North Star.md`。然后:1. 将已安装的文件夹作为 **Obsidian 仓库** 打开2. 在 设置 → 通用 中启用 **Obsidian CLI**(需要 Obsidian 1.12+)@@ -368,7 +368,7 @@ templates/ 带有 YAML frontmatter 的 Obsidian 模板.shardmind/ ShardMind 旁挂目录——仅在通过 `shardmind install` 安装时使用shard.yaml 清单文件(名称、版本、模块、钩子)shard-schema.yaml 向导值 + 模块门控- hooks/ post-install(QMD 引导 + 个性化)、post-update+ hooks/ bootstrap(git 初始化 + QMD)、personalize(North Star)、post-update```> [!NOTE]