A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: derive qmd collection name from qmd_index (with legacy-name migration) (#121)
Brenno Ferrariaa7406e7b9e6
diff --git a/.claude/scripts/lib/qmd-bootstrap.ts b/.claude/scripts/lib/qmd-bootstrap.tsindex fb4525a..a39c466 100644--- a/.claude/scripts/lib/qmd-bootstrap.ts+++ b/.claude/scripts/lib/qmd-bootstrap.ts@@ -10,9 +10,27 @@*/import { escapeRegex } from "./regex.ts";+import { isValidQmdIndex } from "./session-start.ts";const DEFAULT_GLOB = "**/*.md";+/**+ * The legacy collection name a pre-#105 bootstrap may have registered: the+ * manifest `template` field. Returns the validated name, or null when there+ * is nothing to migrate — field absent/non-string, invalid as a qmd+ * identifier, or equal to the index (the shipped default, where the old+ * derivation was accidentally correct).+ */+export function legacyCollectionCandidate(+ templateField: unknown,+ index: string,+): string | null {+ if (typeof templateField !== "string") return null;+ if (templateField === index) return null;+ if (!isValidQmdIndex(templateField)) return null;+ return templateField;+}+export function buildCollectionAddArgs(index: string,collectionName: string,@@ -65,3 +83,17 @@ export function isContextRemoveBenign(o: {/no context found for/i.test(o.stdout));}++/**+ * True when a qmd invocation failed because the subcommand doesn't exist in+ * the installed version ("Unknown subcommand: rename"). qmd prints this to+ * stdout and EXITS 0, so callers must classify by output, never by status.+ * Used to distinguish "this qmd predates `collection rename`" (safe to fall+ * back to remove+re-add) from a genuine failure (leave data untouched).+ */+export function isUnknownSubcommandFailure(outcome: {+ readonly stdout: string;+ readonly stderr: string;+}): boolean {+ return /unknown subcommand/i.test(outcome.stdout + outcome.stderr);+}diff --git a/.claude/scripts/lib/qmd.ts b/.claude/scripts/lib/qmd.tsindex 9096348..70e3d75 100644--- a/.claude/scripts/lib/qmd.ts+++ b/.claude/scripts/lib/qmd.ts@@ -97,3 +97,32 @@ export function buildQmdCommand(shell: true,};}++/**+ * Parse a dotted version into a numeric triple. Accepts the bare "2.5.3"+ * shape and the `qmd --version` output shape ("qmd 2.5.3 (655769712a)") by+ * extracting the first x.y.z run. Returns null when no triple is present.+ */+export function parseVersionTriple(+ raw: string,+): readonly [number, number, number] | null {+ const m = raw.match(/(\d+)\.(\d+)\.(\d+)/);+ if (!m) return null;+ return [Number(m[1]), Number(m[2]), Number(m[3])];+}++/**+ * True when the installed qmd version (raw `--version` output) satisfies the+ * declared minimum. Fails OPEN on anything unparseable — an unknown version+ * must never brick a bootstrap or nag a session; the declared minimum only+ * acts when both sides are readable.+ */+export function qmdVersionAtLeast(actualRaw: string, minRaw: string): boolean {+ const actual = parseVersionTriple(actualRaw);+ const min = parseVersionTriple(minRaw);+ if (actual === null || min === null) return true;+ for (let i = 0; i < 3; i++) {+ if (actual[i]! !== min[i]!) return actual[i]! > min[i]!;+ }+ return true;+}diff --git a/.claude/scripts/tests/qmd-bootstrap.test.ts b/.claude/scripts/tests/qmd-bootstrap.test.tsindex b0dbb28..8f46364 100644--- a/.claude/scripts/tests/qmd-bootstrap.test.ts+++ b/.claude/scripts/tests/qmd-bootstrap.test.ts@@ -13,6 +13,8 @@ import {buildCollectionAddArgs,isContextRemoveBenign,makeCollectionAddBenignMatcher,+ isUnknownSubcommandFailure,+ legacyCollectionCandidate,} from "../lib/qmd-bootstrap.ts";describe("buildCollectionAddArgs", () => {@@ -275,3 +277,50 @@ describe("isContextRemoveBenign", () => {assert.equal(isContextRemoveBenign({ stdout: "", stderr: "" }), false);});});++describe("legacyCollectionCandidate", () => {+ test("returns the template name when it differs from the index", () => {+ assert.equal(+ legacyCollectionCandidate("obsidian-mind", "my-vault"),+ "obsidian-mind",+ );+ });+ test("null when template equals index (shipped default)", () => {+ assert.equal(+ legacyCollectionCandidate("obsidian-mind", "obsidian-mind"),+ null,+ );+ });+ test("null for absent or non-string template", () => {+ assert.equal(legacyCollectionCandidate(undefined, "my-vault"), null);+ assert.equal(legacyCollectionCandidate(42, "my-vault"), null);+ assert.equal(legacyCollectionCandidate(null, "my-vault"), null);+ });+ test("null for template values invalid as qmd identifiers", () => {+ assert.equal(legacyCollectionCandidate("../evil", "my-vault"), null);+ assert.equal(legacyCollectionCandidate("has space", "my-vault"), null);+ assert.equal(legacyCollectionCandidate("", "my-vault"), null);+ });+});++describe("isUnknownSubcommandFailure", () => {+ test("matches qmd's unknown-subcommand output on stdout", () => {+ assert.equal(+ isUnknownSubcommandFailure({+ stdout: "Unknown subcommand: rename\nRun 'qmd collection help' for usage",+ stderr: "",+ }),+ true,+ );+ });+ test("false for unrelated failures (locked store, real errors)", () => {+ assert.equal(+ isUnknownSubcommandFailure({+ stdout: "",+ stderr: "SqliteError: database is locked",+ }),+ false,+ );+ assert.equal(isUnknownSubcommandFailure({ stdout: "", stderr: "" }), false);+ });+});diff --git a/.claude/scripts/tests/qmd.test.ts b/.claude/scripts/tests/qmd.test.tsindex 1f10f69..d4922dd 100644--- a/.claude/scripts/tests/qmd.test.ts+++ b/.claude/scripts/tests/qmd.test.ts@@ -12,7 +12,12 @@ import assert from "node:assert/strict";import { existsSync } from "node:fs";import { isAbsolute } from "node:path";-import { buildQmdCommand, resolveQmdEntry } from "../lib/qmd.ts";+import {+ buildQmdCommand,+ parseVersionTriple,+ qmdVersionAtLeast,+ resolveQmdEntry,+} from "../lib/qmd.ts";describe("lib/qmd.resolveQmdEntry", () => {test("returns an absolute path to an existing qmd entrypoint when qmd is installed", () => {@@ -98,3 +103,34 @@ describe("lib/qmd.buildQmdCommand", () => {assert.notEqual(out.args, input);});});++describe("parseVersionTriple", () => {+ test("parses bare x.y.z", () => {+ assert.deepEqual(parseVersionTriple("2.5.3"), [2, 5, 3]);+ });+ test("parses the qmd --version output shape", () => {+ assert.deepEqual(parseVersionTriple("qmd 2.5.3 (655769712a)"), [2, 5, 3]);+ });+ test("null when no triple present", () => {+ assert.equal(parseVersionTriple("qmd dev-build"), null);+ assert.equal(parseVersionTriple(""), null);+ assert.equal(parseVersionTriple("2.5"), null);+ });+});++describe("qmdVersionAtLeast", () => {+ test("true when equal or above", () => {+ assert.equal(qmdVersionAtLeast("qmd 2.5.3 (abc)", "2.5.3"), true);+ assert.equal(qmdVersionAtLeast("qmd 2.5.3 (abc)", "2.0.0"), true);+ assert.equal(qmdVersionAtLeast("3.0.0", "2.9.9"), true);+ });+ test("false when below on any component", () => {+ assert.equal(qmdVersionAtLeast("qmd 1.9.9 (abc)", "2.0.0"), false);+ assert.equal(qmdVersionAtLeast("2.4.9", "2.5.0"), false);+ assert.equal(qmdVersionAtLeast("2.5.2", "2.5.3"), false);+ });+ test("fails open on unparseable input, either side", () => {+ assert.equal(qmdVersionAtLeast("qmd dev-build", "2.0.0"), true);+ assert.equal(qmdVersionAtLeast("2.5.3", "latest"), true);+ });+});diff --git a/scripts/qmd-bootstrap.ts b/scripts/qmd-bootstrap.tsindex f0bce3a..f5fa8b4 100644--- a/scripts/qmd-bootstrap.ts+++ b/scripts/qmd-bootstrap.ts@@ -36,9 +36,15 @@ import { isMainModule } from "../.claude/scripts/lib/main-guard.ts";import {buildCollectionAddArgs,isContextRemoveBenign,+ isUnknownSubcommandFailure,+ legacyCollectionCandidate,makeCollectionAddBenignMatcher,} from "../.claude/scripts/lib/qmd-bootstrap.ts";-import { buildQmdCommand, resolveQmdEntry } from "../.claude/scripts/lib/qmd.ts";+import {+ buildQmdCommand,+ qmdVersionAtLeast,+ resolveQmdEntry,+} from "../.claude/scripts/lib/qmd.ts";import {qmdConfigPath,readObsidianIgnore,@@ -50,6 +56,7 @@ import { isValidQmdIndex } from "../.claude/scripts/lib/session-start.ts";type ManifestSubset = {readonly qmd_index?: string;readonly qmd_context?: string;+ readonly qmd_min_version?: string;readonly template?: string;};@@ -97,7 +104,9 @@ function echo(outcome: SpawnOutcome): void {if (outcome.stderr) process.stderr.write(outcome.stderr);}-function ensureQmd(entry: string | null): void {+/** Verify qmd is installed; returns the raw `--version` output for the+ * min-version gate in main(). */+function ensureQmd(entry: string | null): string {const probe = spawnQmd(entry, ["--version"]);if (probe.status !== 0) {process.stderr.write(@@ -105,6 +114,21 @@ function ensureQmd(entry: string | null): void {);process.exit(1);}+ return probe.stdout;+}++/**+ * Quiet existence probe — no echo, because "not found" here is an expected+ * state during migration checks, not a diagnostic the user needs to see.+ */+function collectionExists(+ entry: string | null,+ index: string,+ name: string,+): boolean {+ return (+ spawnQmd(entry, ["--index", index, "collection", "show", name]).status === 0+ );}/**@@ -183,22 +207,32 @@ function main(): void {// Resolve once up front so every downstream spawn reuses the same entry.const entry = resolveQmdEntry();- ensureQmd(entry);+ const versionOut = ensureQmd(entry);- const collectionName = manifest.template ?? index;- // The collection name ends up as a YAML key, a `qmd://` URL segment, and a- // SQL identifier inside qmd's store. Same character class as `qmd_index`- // so a typo'd `template` field can't land an unparseable identifier.- // (`qmd_index` was validated above, so a failure here can only come from- // `template`.)- if (!isValidQmdIndex(collectionName)) {+ // Min-version gate (#100): a silently-old qmd is the failure the version+ // declaration exists to catch — fail loud here, where the user is already+ // taking explicit setup action. Fails OPEN on unparseable versions (an+ // unknown version must never brick the bootstrap); vaults without the+ // manifest field skip the gate entirely.+ const minVersion = manifest.qmd_min_version;+ if (+ typeof minVersion === "string" &&+ !qmdVersionAtLeast(versionOut, minVersion)+ ) {process.stderr.write(- `vault-manifest.json \`template\` field value ${JSON.stringify(collectionName)} ` +- "is not a valid qmd identifier.\n" +- "Allowed: alphanumerics, dot, dash, underscore; must start with an alphanumeric.\n",+ `Installed qmd (${versionOut.trim()}) is below this vault's declared minimum (${minVersion}).\n` ++ "Update it: npm i -g @tobilu/qmd\n",);process.exit(1);}++ // Collection name = qmd_index, the per-vault identity (#105). `template`+ // is the shared package identity — the same string for every install —+ // so deriving the collection name from it breaks idempotency on any+ // vault where the two differ (and mismatches the on-disk collection,+ // which qmd creates under the vault's own name). qmd_index was validated+ // above, so no second validation branch is needed.+ const collectionName = index;const contextPath = `qmd://${collectionName}/`;const contextText =manifest.qmd_context ??@@ -206,6 +240,71 @@ function main(): void {process.stdout.write(`→ Bootstrapping QMD index '${index}'\n`);+ // Migration (#105): bootstraps before the fix registered the collection+ // under the shared `template` name. Field states to handle:+ // 1. No legacy collection (fresh install, or the old bootstrap failed+ // before registering) → nothing to do.+ // 2. Legacy exists, correctly-named one doesn't → RENAME in place.+ // Rename keeps the indexed data, so migrated users pay no re-index.+ // 3. Both exist (user already re-registered by hand) → REMOVE the+ // legacy one; two collections over the same corpus double every+ // search result.+ // `collection rename` may not exist on older qmd installs — fall back to+ // remove, and the `collection add` below registers the correct name fresh.+ const legacyName = legacyCollectionCandidate(manifest.template, index);+ if (legacyName !== null && collectionExists(entry, index, legacyName)) {+ if (collectionExists(entry, index, collectionName)) {+ run(+ entry,+ ["--index", index, "collection", "remove", legacyName],+ `Removing legacy collection '${legacyName}' (superseded by '${collectionName}')`,+ );+ } else {+ process.stdout.write(+ `→ Renaming legacy collection '${legacyName}' → '${collectionName}' (#105 migration)\n`,+ );+ const renamed = spawnQmd(entry, [+ "--index",+ index,+ "collection",+ "rename",+ legacyName,+ collectionName,+ ]);+ echo(renamed);+ // qmd exits 0 even for unknown subcommands, so rename success is+ // verified by probing the target collection — never by exit status.+ if (!collectionExists(entry, index, collectionName)) {+ if (isUnknownSubcommandFailure(renamed)) {+ // Older qmd without `collection rename`: remove the legacy+ // entry; the registration below re-adds under the correct+ // name and the update/embed steps rebuild its index rows.+ run(+ entry,+ ["--index", index, "collection", "remove", legacyName],+ `Rename unavailable — removing legacy collection '${legacyName}' instead`,+ );+ } else {+ // Unexpected failure (locked store, CLI drift): do NOT+ // destroy the legacy collection — leave it for inspection.+ // The registration below surfaces the conflict loudly.+ warn(+ `Could not rename legacy collection '${legacyName}' — leaving it in place. ` ++ `Migrate manually: qmd --index ${index} collection rename ${legacyName} ${collectionName}`,+ );+ }+ }+ }+ // The legacy context row is keyed by the legacy path — clear it so a+ // stale summary doesn't shadow the one attached below.+ runIdempotent(+ entry,+ ["--index", index, "context", "rm", `qmd://${legacyName}/`],+ "Clearing legacy context (if any)",+ isContextRemoveBenign,+ );+ }+// Re-runs are idempotent (matcher recognises the by-name "already exists"// case); a path-collision warning is intentionally NOT swallowed.runIdempotent(diff --git a/vault-manifest.json b/vault-manifest.jsonindex 2ae524a..54626de 100644--- a/vault-manifest.json+++ b/vault-manifest.json@@ -3,6 +3,7 @@"version": "6.2.1","released": "2026-06-02","qmd_index": "obsidian-mind",+ "qmd_min_version": "2.0.0","qmd_context": "Engineer's work vault built on obsidian-mind. Active projects and archive, 1:1 notes, incidents, brag log with quarterly evidence, competency map, people and teams, decisions and patterns in brain/, reference docs and runbooks. Multi-agent (Claude Code, Codex, Gemini) with lifecycle hooks and QMD semantic search. Ground for 'what did I ship?' reviews, project status, and personal knowledge management.","infrastructure": ["CLAUDE.md",