Skip to content

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

feat: make /om-vault-upgrade ShardMind-aware, keeping local improvements through an upgrade (#315)

Brenno Ferrari327ae425b7e8
diff --git a/.claude/commands/om-vault-upgrade.md b/.claude/commands/om-vault-upgrade.md
index 30c2b31..c846a59 100644
--- a/.claude/commands/om-vault-upgrade.md
+++ b/.claude/commands/om-vault-upgrade.md
@@ -1,21 +1,75 @@
# Vault Upgrade
-Import and migrate content from an existing Obsidian vault into this obsidian-mind instance. Works with older obsidian-mind versions and arbitrary Obsidian vaults.
+Two jobs, picked by whether a source vault is given:
-**When to use**: After downloading or cloning the latest obsidian-mind template, to pull in your existing vault content. Also works for migrating any Obsidian vault into the obsidian-mind structure.
+- **No source: upgrade THIS vault** to the latest template release, through [ShardMind](https://github.com/breferrari/shardmind), keeping every local improvement. See *Upgrade this vault* below.
+- **A source vault: import its content** into this obsidian-mind instance. Works with older obsidian-mind versions and arbitrary Obsidian vaults. See *Workflow* below.
## Usage
```
-/om-vault-upgrade <path-to-source-vault>
+/om-vault-upgrade # upgrade this vault (ShardMind)
+/om-vault-upgrade --dry-run # show the upgrade plan only
+/om-vault-upgrade <path-to-source-vault> # import another vault's content
/om-vault-upgrade <path-to-source-vault> --dry-run
-/om-vault-upgrade --source <path-to-source-vault>
-/om-vault-upgrade --source <path-to-source-vault> --dry-run
+/om-vault-upgrade --source <path-to-source-vault> [--dry-run]
```
**Arguments**:
- `<path-to-source-vault>` — absolute or relative path to the vault to migrate FROM (positional or via `--source`)
-- `--dry-run` — generate the migration plan without executing it (saves to `thinking/`)
+- `--dry-run` — produce the plan without changing anything
+
+## Upgrade this vault (ShardMind)
+
+ShardMind owns the engine lifecycle: `shardmind update` moves a managed vault to a new release, and `shardmind adopt` brings a vault that was cloned without it under management. This command owns the judgment ShardMind's bulk modes cannot make: whether a file that differs from the template is one **you improved** (keep it, and maybe upstream it) or one **you never updated** (take the new version). A blunt use-all-theirs downgrades every local enhancement. A blunt keep-all-mine is worse: it records stale files as yours, so the vault reports itself up to date while those files stay old and no later update touches them.
+
+**Requires ShardMind 0.2.0 or later** (`shardmind --version`; upgrade with `npm i -g shardmind@latest`). Without ShardMind, use *Workflow* below with this vault's previous copy as the source.
+
+### U1. Plan
+
+```bash
+node --experimental-strip-types .claude/scripts/upgrade-plan.ts
+```
+
+It never changes the vault. It detects which case this is:
+
+- **Managed** (`.shardmind/state.json` exists): it reads `shardmind --json` and `shardmind update --dry-run --json`.
+- **Cloned without ShardMind** (a `vault-manifest.json` but no state, including an incomplete adoption): the release the vault came from is the manifest's `version`. It reads `shardmind adopt … --from-version <v> --dry-run --yes --json` and hashes each differing file against that release.
+- **Neither:** not an obsidian-mind vault; use *Workflow* below.
+
+It then prints every file needing judgment, sorted into:
+
+| Section | Meaning | What happens |
+|---|---|---|
+| **Behind** | The template changed it; you never did | Take the new version. Nothing of yours is lost |
+| **Ahead** | Changed only in this vault | Keep yours. List it to the user as an **upstream candidate** if it is an improvement |
+| **Merged** | Changed on both sides, merged cleanly | Show the user the result to review |
+| **Conflicts** | Changed on both sides, or a new template file where you already have one | The user decides per file |
+| **New in the template** | Added | Taken as is |
+
+Show the report to the user. With `--dry-run`, stop here.
+
+### U2. Apply
+
+ShardMind executes only through its terminal UI (`--json` works with `--dry-run` only), so run it non-interactively: `CI=true … --yes < /dev/null`.
+
+**Managed vault:**
+- **No conflicts:** `CI=true shardmind update --yes < /dev/null`. `--yes` auto-keeps your version wherever both sides changed, so it is safe only once the plan shows no conflicts.
+- **Conflicts:** ask the user to run `! shardmind update` themselves and decide each conflicting file in the prompt, or in their editor.
+
+**Cloned without ShardMind:**
+1. Write the new release's bytes for the **behind** files only. Each is checked against adopt's plan before it is written, so nothing you changed is touched:
+ ```bash
+ node --experimental-strip-types .claude/scripts/upgrade-plan.ts --apply-behind
+ ```
+2. **No conflicts:** `CI=true shardmind adopt github:breferrari/obsidian-mind --from-version <v> --mode keep-all-mine --yes < /dev/null`. Every file that still differs is now really yours.
+3. **Conflicts:** have the user run `! shardmind adopt github:breferrari/obsidian-mind --from-version <v> --mode decide-per-file` instead.
+
+### U3. Verify
+
+1. `shardmind --json` reports the new version, with `update.kind` `up-to-date`. Its `files.modified` must be exactly the **ahead** files, plus any conflicts the user kept. A behind file listed there was frozen, so fix it before finishing.
+2. The hooks run: `echo '{}' | node --experimental-strip-types .claude/scripts/session-start.ts` exits 0 and prints the session context.
+3. Report the **ahead** files to the user as upstream candidates. A local improvement every vault could use belongs upstream, where the next release carries it.
## Subagents
diff --git a/.claude/scripts/lib/upgrade-plan.ts b/.claude/scripts/lib/upgrade-plan.ts
new file mode 100644
index 0000000..4a9573b
--- /dev/null
+++ b/.claude/scripts/lib/upgrade-plan.ts
@@ -0,0 +1,179 @@
+/**
+ * The ahead/behind judgment `/om-vault-upgrade` makes on top of ShardMind
+ * (#101).
+ *
+ * ShardMind owns the engine lifecycle: `update` moves a managed vault to a
+ * new release, `adopt` brings a vault that was cloned without it under
+ * management. Its bulk modes cannot tell a file the user improved from a
+ * file the user simply never updated: both are "your version differs". A
+ * blunt use-all-theirs downgrades every local enhancement; a blunt
+ * keep-all-mine freezes every stale file at its old release, because adopt
+ * then records it as user-modified and later updates leave it alone.
+ *
+ * These classifiers read ShardMind 0.2.0's `--dry-run --json` plans
+ * (`schemaVersion` 1) and sort every file into what to take, what to keep,
+ * and what needs a person. Pure: the caller runs ShardMind and, for adopt,
+ * supplies the hash of each file at the release the vault was cloned from.
+ */
+
+/** ShardMind's `--json` envelope. */
+export type ShardmindEnvelope<T> =
+ | { readonly schemaVersion: number; readonly command: string; readonly ok: true; readonly result: T }
+ | {
+ readonly schemaVersion: number;
+ readonly command: string;
+ readonly ok: false;
+ readonly error: { readonly code: string | null; readonly message: string; readonly hint?: string | null };
+ };
+
+export type StatusResult = {
+ readonly installed: boolean;
+ readonly version?: string;
+ readonly update?: { readonly kind: string; readonly current?: string; readonly latest?: string };
+ readonly files?: { readonly modified?: readonly (string | { readonly path: string })[] };
+};
+
+export type UpdatePlanFile = {
+ readonly path: string;
+ readonly action: string;
+ readonly reason?: string;
+ readonly preexisting?: boolean;
+ readonly binary?: boolean;
+ readonly renamedFrom?: string;
+};
+export type UpdatePlan = {
+ readonly dryRun: boolean;
+ readonly upToDate?: true;
+ readonly version?: string;
+ readonly files: readonly UpdatePlanFile[];
+};
+
+export type AdoptPlanFile = {
+ readonly path: string;
+ readonly classification: "matches" | "differs" | "shard-only";
+ readonly shardHash: string;
+ readonly userHash?: string;
+ readonly volatile: boolean;
+ readonly binary?: boolean;
+ readonly movedFrom?: string;
+};
+export type AdoptPlan = { readonly dryRun: boolean; readonly files: readonly AdoptPlanFile[] };
+
+export type UpgradeReport = {
+ /** The template moved on and the user never touched the file: take the new version. */
+ readonly behind: readonly string[];
+ /** Changed only locally: keep it. An upstream candidate if it is an improvement. */
+ readonly ahead: readonly string[];
+ /** Changed on both sides and merged cleanly: review the result. */
+ readonly merged: readonly string[];
+ /** Changed on both sides and not mergeable: a person decides. */
+ readonly conflicts: readonly string[];
+ /** New in the template. */
+ readonly added: readonly string[];
+ /** Nothing to judge: identical, volatile, or the user's own by design. */
+ readonly unchanged: number;
+};
+
+const empty = (): { -readonly [K in keyof UpgradeReport]: K extends "unchanged" ? number : string[] } => ({
+ behind: [],
+ ahead: [],
+ merged: [],
+ conflicts: [],
+ added: [],
+ unchanged: 0,
+});
+
+function modifiedPaths(status: StatusResult | null): Set<string> {
+ const list = status?.files?.modified ?? [];
+ return new Set(list.map((m) => (typeof m === "string" ? m : m.path)));
+}
+
+/**
+ * A managed vault's update plan. ShardMind already knows each file's base
+ * (the release recorded in its state), so the action says it all:
+ * `overwrite`, `restore_missing` and `delete` touch only files the user left
+ * alone; a `noop` on a file the status report lists as modified is a local
+ * change the template never made, which is the "ahead" case the bulk modes
+ * cannot see.
+ */
+export function classifyUpdate(plan: UpdatePlan, status: StatusResult | null): UpgradeReport {
+ const r = empty();
+ const modified = modifiedPaths(status);
+ for (const f of plan.files) {
+ switch (f.action) {
+ case "overwrite":
+ case "restore_missing":
+ case "delete":
+ r.behind.push(f.path);
+ break;
+ case "add":
+ r.added.push(f.path);
+ break;
+ case "auto_merge":
+ r.merged.push(f.path);
+ break;
+ case "conflict":
+ r.conflicts.push(f.path);
+ break;
+ case "noop":
+ if (modified.has(f.path)) r.ahead.push(f.path);
+ else r.unchanged++;
+ break;
+ default:
+ // skip_volatile, keep_as_user: the user's by design.
+ r.unchanged++;
+ }
+ }
+ return r;
+}
+
+/**
+ * An unmanaged clone's adopt plan. Adopt compares the user's file with the
+ * LATEST release only, so a differing file is either one the user changed or
+ * one the template changed since the clone; the hash of the file at the
+ * release the vault was cloned from (`baseHash`, null when the path did not
+ * exist there) tells them apart:
+ * - user's bytes equal the base → the user never touched it → behind;
+ * - user changed it, template did not (base equals the latest) → ahead;
+ * - both changed it, or the path is new in the template but the user
+ * already has a file there → a person decides.
+ */
+export function classifyAdopt(plan: AdoptPlan, baseHash: (path: string) => string | null): UpgradeReport {
+ const r = empty();
+ for (const f of plan.files) {
+ if (f.classification === "matches") {
+ r.unchanged++;
+ continue;
+ }
+ if (f.classification === "shard-only") {
+ r.added.push(f.path);
+ continue;
+ }
+ if (f.volatile) {
+ r.unchanged++;
+ continue;
+ }
+ const base = baseHash(f.movedFrom ?? f.path);
+ if (base !== null && f.userHash === base) r.behind.push(f.path);
+ else if (base !== null && f.shardHash === base) r.ahead.push(f.path);
+ else r.conflicts.push(f.path);
+ }
+ return r;
+}
+
+/** The report as markdown, for the user. Every list in full: a cut list would hide a decision. */
+export function formatUpgradeReport(r: UpgradeReport, from: string, to: string): string {
+ const section = (title: string, what: string, paths: readonly string[]): string =>
+ paths.length === 0 ? "" : `\n### ${title} (${paths.length})\n${what}\n${paths.map((p) => `- \`${p}\``).join("\n")}\n`;
+ return [
+ `## Upgrade plan: ${from} → ${to}`,
+ `${r.unchanged} file(s) need no judgment.`,
+ section("Behind", "The template changed these and you never did. Taking the new version loses nothing.", r.behind),
+ section("Ahead — keep, and consider upstreaming", "Changed only in this vault. Kept as yours.", r.ahead),
+ section("Merged — review", "Changed on both sides; merged without conflict.", r.merged),
+ section("Conflicts — your decision", "Changed on both sides (or a new template file where you already have one).", r.conflicts),
+ section("New in the template", "Added as they are.", r.added),
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
diff --git a/.claude/scripts/tests/upgrade-plan.test.ts b/.claude/scripts/tests/upgrade-plan.test.ts
new file mode 100644
index 0000000..76e0568
--- /dev/null
+++ b/.claude/scripts/tests/upgrade-plan.test.ts
@@ -0,0 +1,120 @@
+/**
+ * The ahead/behind judgment behind `/om-vault-upgrade` (#101), on plans
+ * shaped exactly like ShardMind 0.2.0's `--dry-run --json` output.
+ *
+ * ShardMind's bulk modes cannot tell a file the user improved from one the
+ * user never updated. Measured on a real 9.0.0 → 9.0.1 clone with one local
+ * edit: `adopt --mode keep-all-mine` reported the vault "9.0.1, up to date"
+ * while four files stayed at 9.0.0, recorded as user-modified so that no
+ * later update would touch them. These pin the classification that avoids it.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyAdopt,
+ classifyUpdate,
+ formatUpgradeReport,
+ type AdoptPlan,
+ type UpdatePlan,
+} from "../lib/upgrade-plan.ts";
+
+describe("classifyUpdate — a managed vault", () => {
+ const plan: UpdatePlan = {
+ dryRun: true,
+ files: [
+ { path: "CHANGELOG.md", action: "overwrite" },
+ { path: "vault-manifest.json", action: "overwrite" },
+ { path: ".claude/scripts/charcount.ts", action: "noop", reason: "no upstream change" },
+ { path: ".claude/scripts/lib/charcount.ts", action: "noop", reason: "identical" },
+ { path: "templates/Work Note.md", action: "auto_merge" },
+ { path: ".claude/settings.json", action: "conflict" },
+ { path: ".claude/scripts/new-hook.ts", action: "add" },
+ { path: "brain/Gotchas.md", action: "restore_missing" },
+ { path: "old/removed.md", action: "delete" },
+ { path: "Home.md", action: "skip_volatile" },
+ { path: "mine.md", action: "keep_as_user" },
+ ],
+ };
+ const status = { installed: true, files: { modified: [{ path: ".claude/scripts/charcount.ts" }] } };
+
+ test("each action lands where it belongs", () => {
+ const r = classifyUpdate(plan, status);
+ assert.deepEqual(r.behind, ["CHANGELOG.md", "vault-manifest.json", "brain/Gotchas.md", "old/removed.md"]);
+ assert.deepEqual(r.ahead, [".claude/scripts/charcount.ts"]);
+ assert.deepEqual(r.merged, ["templates/Work Note.md"]);
+ assert.deepEqual(r.conflicts, [".claude/settings.json"]);
+ assert.deepEqual(r.added, [".claude/scripts/new-hook.ts"]);
+ assert.equal(r.unchanged, 3);
+ });
+
+ test("a noop on a file the user did not modify is not 'ahead'", () => {
+ const r = classifyUpdate(plan, { installed: true, files: { modified: [] } });
+ assert.deepEqual(r.ahead, []);
+ });
+
+ test("modified may be listed as plain paths too", () => {
+ const r = classifyUpdate(plan, { installed: true, files: { modified: [".claude/scripts/charcount.ts"] } });
+ assert.deepEqual(r.ahead, [".claude/scripts/charcount.ts"]);
+ });
+});
+
+describe("classifyAdopt — a vault cloned without ShardMind", () => {
+ const base: Record<string, string> = {
+ "CHANGELOG.md": "h-old-changelog",
+ ".claude/scripts/charcount.ts": "h-charcount",
+ ".claude/settings.json": "h-old-settings",
+ };
+ const plan: AdoptPlan = {
+ dryRun: true,
+ files: [
+ { path: "Home.md", classification: "matches", shardHash: "h-home", volatile: false },
+ // Template changed it, the user never did → behind.
+ { path: "CHANGELOG.md", classification: "differs", shardHash: "h-new-changelog", userHash: "h-old-changelog", volatile: false },
+ // The user changed it, the template did not → ahead.
+ { path: ".claude/scripts/charcount.ts", classification: "differs", shardHash: "h-charcount", userHash: "h-mine", volatile: false },
+ // Both changed it → a person decides.
+ { path: ".claude/settings.json", classification: "differs", shardHash: "h-new-settings", userHash: "h-my-settings", volatile: false },
+ // The template adds a path the user already has → a person decides.
+ { path: "brain/New.md", classification: "differs", shardHash: "h-new", userHash: "h-users", volatile: false },
+ { path: "bases/New.base", classification: "shard-only", shardHash: "h-b", volatile: false },
+ { path: "brain/North Star.md", classification: "differs", shardHash: "h-x", userHash: "h-y", volatile: true },
+ ],
+ };
+ const r = classifyAdopt(plan, (p) => base[p] ?? null);
+
+ test("behind: the user's bytes are the release they cloned", () => {
+ assert.deepEqual(r.behind, ["CHANGELOG.md"]);
+ });
+ test("ahead: changed only locally", () => {
+ assert.deepEqual(r.ahead, [".claude/scripts/charcount.ts"]);
+ });
+ test("conflicts: changed on both sides, or a new template path the user already has", () => {
+ assert.deepEqual(r.conflicts, [".claude/settings.json", "brain/New.md"]);
+ });
+ test("new template files are added; matches and volatile files need no judgment", () => {
+ assert.deepEqual(r.added, ["bases/New.base"]);
+ assert.equal(r.unchanged, 2);
+ });
+ test("a renamed file is judged by its base at the old path", () => {
+ const moved = classifyAdopt(
+ { dryRun: true, files: [{ path: "new/Place.md", movedFrom: "old/Place.md", classification: "differs", shardHash: "h2", userHash: "h1", volatile: false }] },
+ (p) => (p === "old/Place.md" ? "h1" : null),
+ );
+ assert.deepEqual(moved.behind, ["new/Place.md"]);
+ });
+});
+
+describe("formatUpgradeReport", () => {
+ test("names every file in full, by section, and skips empty sections", () => {
+ const out = formatUpgradeReport(
+ { behind: ["a.md"], ahead: ["b.ts"], merged: [], conflicts: [], added: [], unchanged: 7 },
+ "v9.0.0",
+ "v9.0.1",
+ );
+ assert.match(out, /^## Upgrade plan: v9\.0\.0 → v9\.0\.1\n7 file\(s\) need no judgment\./);
+ assert.match(out, /### Behind \(1\)[\s\S]*- `a\.md`/);
+ assert.match(out, /### Ahead — keep, and consider upstreaming \(1\)[\s\S]*- `b\.ts`/);
+ assert.doesNotMatch(out, /Merged|Conflicts|New in the template/);
+ });
+});
diff --git a/.claude/scripts/upgrade-plan.ts b/.claude/scripts/upgrade-plan.ts
new file mode 100644
index 0000000..6ad461b
--- /dev/null
+++ b/.claude/scripts/upgrade-plan.ts
@@ -0,0 +1,189 @@
+#!/usr/bin/env node
+/**
+ * upgrade-plan — the ShardMind-aware preflight for `/om-vault-upgrade` (#101).
+ *
+ * node --experimental-strip-types .claude/scripts/upgrade-plan.ts [--json] [--apply-behind] [--source <ref>]
+ *
+ * Reads the vault, never changes it (except with --apply-behind, below):
+ * - managed (`.shardmind/state.json`): `shardmind --json` and
+ * `shardmind update --dry-run --json`, classified by `classifyUpdate`;
+ * - cloned without ShardMind (a `vault-manifest.json`, no state): the
+ * release it was cloned from is the manifest's `version`; runs
+ * `shardmind adopt <source> --from-version <v> --dry-run --yes --json`,
+ * fetches that release to hash each file's base, and classifies with
+ * `classifyAdopt`.
+ * Prints the report (or, with --json, `{ mode, from, to, report }`).
+ *
+ * --apply-behind (unmanaged clone only): writes the latest release's bytes
+ * for every BEHIND file — one the user never changed — after checking each
+ * against adopt's `shardHash`, so a following
+ * `shardmind adopt … --mode keep-all-mine` keeps exactly the files that are
+ * really the user's. Without it, keep-all-mine would record the stale files
+ * as user-modified, and no later update would ever touch them.
+ *
+ * Requires ShardMind 0.2.0 or later (`--json`).
+ */
+
+import { spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { isMainModule } from "./lib/main-guard.ts";
+import { resolveProjectDir } from "./lib/project-dir.ts";
+import {
+ classifyAdopt,
+ classifyUpdate,
+ formatUpgradeReport,
+ type AdoptPlan,
+ type ShardmindEnvelope,
+ type StatusResult,
+ type UpdatePlan,
+ type UpgradeReport,
+} from "./lib/upgrade-plan.ts";
+
+const DEFAULT_SOURCE = "github:breferrari/obsidian-mind";
+
+function fail(message: string): never {
+ process.stderr.write(`upgrade-plan: ${message}\n`);
+ process.exit(1);
+}
+
+/**
+ * ShardMind's real entry point, run with this Node, so no shell or `.cmd`
+ * shim is involved (the same reason qmd is launched this way, #54). Falls
+ * back to `shardmind` on PATH through the shell.
+ */
+function shardmindCommand(args: readonly string[]): { cmd: string; args: string[]; shell: boolean } {
+ const root = spawnSync("npm root -g", { shell: true, encoding: "utf8", timeout: 10_000 }).stdout?.trim() ?? "";
+ const entry = root ? join(root, "shardmind", "dist", "cli.js") : "";
+ if (entry && existsSync(entry)) return { cmd: process.execPath, args: [entry, ...args], shell: false };
+ // No argument here comes from outside this script except the source ref,
+ // which main() checks against a strict pattern.
+ return { cmd: ["shardmind", ...args].join(" "), args: [], shell: true };
+}
+
+/** Run ShardMind and parse its `--json` envelope. */
+function shardmind<T>(vault: string, args: readonly string[]): ShardmindEnvelope<T> {
+ const c = shardmindCommand([...args, "--no-update-check"]);
+ const r = spawnSync(c.cmd, c.args, {
+ cwd: vault,
+ shell: c.shell,
+ encoding: "utf8",
+ timeout: 300_000,
+ input: "",
+ env: { ...process.env, CI: "true" },
+ });
+ try {
+ return JSON.parse(r.stdout) as ShardmindEnvelope<T>;
+ } catch {
+ fail(`shardmind ${args[0] ?? ""} gave no JSON (exit ${r.status}): ${(r.stderr || r.stdout).slice(0, 400)}`);
+ }
+}
+
+function versionAtLeast(v: string, min: readonly number[]): boolean {
+ const parts = v.trim().replace(/^v/, "").split(/[.-]/).map((n) => Number.parseInt(n, 10));
+ for (let i = 0; i < min.length; i++) {
+ const a = parts[i] ?? 0;
+ if (a !== min[i]) return a > (min[i] as number);
+ }
+ return true;
+}
+
+const sha256 = (b: Buffer): string => createHash("sha256").update(b).digest("hex");
+
+/** A shallow clone of `source` at tag `v<version>`, in a temp folder. */
+function cloneRelease(source: string, version: string): string {
+ const repo = source.replace(/^github:/, "").replace(/[#@].*$/, "");
+ const dir = mkdtempSync(join(tmpdir(), "om-upgrade-base-"));
+ const r = spawnSync("git", ["clone", "-q", "--depth", "1", "--branch", `v${version}`, `https://github.com/${repo}`, dir], {
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ if (r.status !== 0) fail(`could not fetch ${repo} v${version}: ${r.stderr.slice(0, 300)}`);
+ return dir;
+}
+
+/** The newest stable `vX.Y.Z` tag of `source`. */
+function latestRelease(source: string): string {
+ const repo = source.replace(/^github:/, "").replace(/[#@].*$/, "");
+ const r = spawnSync("git", ["ls-remote", "--tags", `https://github.com/${repo}`], { encoding: "utf8", timeout: 60_000 });
+ const tags = [...r.stdout.matchAll(/refs\/tags\/v(\d+)\.(\d+)\.(\d+)$/gm)].map((m) => [Number(m[1]), Number(m[2]), Number(m[3])] as const);
+ if (tags.length === 0) fail(`no release tags found for ${repo}`);
+ tags.sort((a, b) => b[0] - a[0] || b[1] - a[1] || b[2] - a[2]);
+ return (tags[0] as readonly number[]).join(".");
+}
+
+function main(): void {
+ const args = process.argv.slice(2);
+ const asJson = args.includes("--json");
+ const applyBehind = args.includes("--apply-behind");
+ const sourceIdx = args.indexOf("--source");
+ const source = sourceIdx >= 0 ? (args[sourceIdx + 1] ?? "") : DEFAULT_SOURCE;
+ if (!/^(github:)?[\w.-]+\/[\w.-]+$/.test(source)) fail(`not a shard reference: ${source}`);
+
+ const vault = resolveProjectDir(process.cwd());
+ const v = shardmindCommand(["--version"]);
+ const ver = spawnSync(v.cmd, v.args, { shell: v.shell, encoding: "utf8", timeout: 60_000 });
+ if (ver.status !== 0) fail("ShardMind is not installed. Install it (npm i -g shardmind) or use the manual migration in /om-vault-upgrade.");
+ if (!versionAtLeast(ver.stdout, [0, 2, 0])) fail(`ShardMind ${ver.stdout.trim()} is too old; 0.2.0 or later is needed for --json. Run: npm i -g shardmind@latest`);
+
+ let mode: "managed" | "unmanaged";
+ let from = "?";
+ let to = "?";
+ let report: UpgradeReport;
+
+ if (existsSync(join(vault, ".shardmind", "state.json"))) {
+ mode = "managed";
+ const status = shardmind<StatusResult>(vault, ["--json"]);
+ if (!status.ok) fail(`status: ${status.error.message}${status.error.hint ? ` — ${status.error.hint}` : ""}`);
+ from = status.result.version ?? "?";
+ to = status.result.update?.latest ?? from;
+ const plan = shardmind<UpdatePlan>(vault, ["update", "--dry-run", "--json"]);
+ if (!plan.ok) fail(`update plan: ${plan.error.message}${plan.error.hint ? ` — ${plan.error.hint}` : ""}`);
+ report = classifyUpdate(plan.result, status.result);
+ } else {
+ mode = "unmanaged";
+ let manifest: { version?: unknown } = {};
+ try {
+ manifest = JSON.parse(readFileSync(join(vault, "vault-manifest.json"), "utf8")) as { version?: unknown };
+ } catch {
+ fail("no .shardmind/state.json and no vault-manifest.json: not an obsidian-mind vault. Use the manual migration in /om-vault-upgrade.");
+ }
+ if (typeof manifest.version !== "string") fail("vault-manifest.json has no version, so the release this vault came from is unknown.");
+ from = manifest.version;
+ to = latestRelease(source);
+ const plan = shardmind<AdoptPlan>(vault, ["adopt", source, "--from-version", from, "--dry-run", "--yes", "--json"]);
+ if (!plan.ok) fail(`adopt plan: ${plan.error.message}${plan.error.hint ? ` — ${plan.error.hint}` : ""}`);
+ const base = cloneRelease(source, from);
+ try {
+ report = classifyAdopt(plan.result, (p) => {
+ const f = join(base, p);
+ return existsSync(f) ? sha256(readFileSync(f)) : null;
+ });
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+
+ if (applyBehind && report.behind.length > 0) {
+ const latest = cloneRelease(source, to);
+ try {
+ const want = new Map(plan.result.files.map((f) => [f.path, f.shardHash]));
+ for (const p of report.behind) {
+ const bytes = readFileSync(join(latest, p));
+ if (sha256(bytes) !== want.get(p)) fail(`${p} at v${to} does not match adopt's plan; nothing more was written`);
+ writeFileSync(join(vault, p), bytes);
+ }
+ } finally {
+ rmSync(latest, { recursive: true, force: true });
+ }
+ process.stderr.write(`upgrade-plan: wrote v${to} of ${report.behind.length} behind file(s)\n`);
+ }
+ }
+
+ process.stdout.write(
+ asJson ? `${JSON.stringify({ mode, from, to, report }, null, 2)}\n` : `${formatUpgradeReport(report, `v${from}`, `v${to}`)}\n`,
+ );
+}
+
+if (isMainModule(import.meta.url)) main();
diff --git a/README.md b/README.md
index 237b7ff..9fbc5ad 100644
--- a/README.md
+++ b/README.md
@@ -423,7 +423,7 @@ Defined in `.claude/commands/`. Run them in Claude Code, Codex CLI, or Gemini CL
| `/om-tidy` | Self-maintenance — acts on every hygiene flag: archive, group, split. Never deletes, never commits |
| `/om-correct` | Sweep a corrected fact — applies it at the single source, links restatements, preserves dated records |
| `/om-vault-audit` | Audit indexes, links, orphans, stale context |
-| `/om-vault-upgrade` | Import content from an existing vault — version detection, classification, migration |
+| `/om-vault-upgrade` | Upgrade this vault through ShardMind (keeps your local improvements), or import content from an existing vault — version detection, classification, migration |
| `/om-prep-1on1` | Prep for an upcoming 1:1 — load person context, open items, suggested agenda |
| `/om-meeting` | Prep for any meeting by topic — subject-forward briefing with open items and considerations |
| `/om-intake` | Process meeting notes inbox — classify and route to the right vault notes |
diff --git a/brain/Skills.md b/brain/Skills.md
index bd06b2b..95a30f4 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -53,7 +53,7 @@ Custom slash commands, subagents, and reusable workflows. Defined in `.claude/co
|---------|---------|
| `/om-correct` | Sweep a corrected fact through the vault — semantic + literal search, applies at the single source, replaces restatements with links, preserves notes recording what was believed at the time. The acting half of Write-Correctness Law 2 |
| `/om-vault-audit` | Deep structural audit — indexes, frontmatter, links, Bases, folder placement, stale context |
-| `/om-vault-upgrade` | Import content from an existing vault — detects version, classifies notes, transforms frontmatter, rebuilds indexes |
+| `/om-vault-upgrade` | Upgrade this vault through ShardMind, keeping local improvements and listing them as upstream candidates; or import content from an existing vault — detects version, classifies notes, transforms frontmatter, rebuilds indexes |
| `/om-project-archive` | Move completed project from `work/active/` to `work/archive/YYYY/`, update all indexes — moves whole `active/<Topic>/` clusters intact |
| `/om-tidy` | Self-maintenance pass — acts on every hygiene flag: archives completed work, groups clusters, splits oversized notes, reports open loops. Never deletes, never commits |
@@ -79,7 +79,7 @@ Custom slash commands, subagents, and reusable workflows. Defined in `.claude/co
**Maintenance:**
- `/om-vault-audit` should be run at the end of substantial sessions — catches stale indexes and mixed context
-- `/om-vault-upgrade` imports content from an existing vault (older obsidian-mind or any Obsidian vault). Detects version, classifies notes, transforms frontmatter, fixes wikilinks, rebuilds indexes. Use `--dry-run` to preview.
+- `/om-vault-upgrade` with no source upgrades this vault through ShardMind 0.2.0+: `upgrade-plan.ts` sorts every differing file into behind (take), ahead (keep; upstream candidate), merged or conflict before anything is applied. With a source, it imports content from an existing vault (older obsidian-mind or any Obsidian vault). Detects version, classifies notes, transforms frontmatter, fixes wikilinks, rebuilds indexes. Use `--dry-run` to preview.
- `/om-project-archive` handles the active/ → archive/ move with index updates
## Subagents