Fastest way to scaffold your LLM powered personal knowledge base - Obsidian, Claude Code, qmd, Github
JavaScript aiampclaude-codecodexcursorgithubknowledge-baseknowledge-graphknowledge-managementllmobsidianobsidian-vaultqmdsecond-brain
fix: write `default` on upsert + surface qmd:setup errors
jessepinkman9900627a70adb4d6
diff --git a/bin/create.js b/bin/create.jsindex abb96d0..ad873e2 100755--- a/bin/create.js+++ b/bin/create.js@@ -20,6 +20,25 @@ function run(cmd, cwd) {return result.status === 0}+// Like `run`, but returns captured stdout/stderr so callers can surface the+// real failure to the user instead of a generic "failed" message.+function runCapture(cmd, cwd) {+ const result = spawnSync(cmd[0], cmd.slice(1), { cwd, stdio: "pipe", encoding: "utf8" })+ return {+ ok: result.status === 0,+ stdout: result.stdout || "",+ stderr: result.stderr || "",+ }+}++// Pick the most informative tail of a child process's output for an error message.+function tailForError({ stdout, stderr }, lines = 10) {+ const source = (stderr && stderr.trim()) ? stderr : stdout+ const trimmed = (source || "").trim()+ if (!trimmed) return ""+ return trimmed.split("\n").slice(-lines).join("\n")+}+// Interactive commands (e.g. gh auth login) — must inherit stdio; call outside spinnerfunction runInteractive(cmd, cwd) {const result = spawnSync(cmd[0], cmd.slice(1), { cwd, stdio: "inherit" })@@ -432,9 +451,18 @@ async function resolveBrain(name) {}const { defaultBrain, brains } = parseConfig(content)const target = name || defaultBrain- if (!target) throw new Error("No default brain set in config.toml.")+ if (!target) {+ const available = brains.map(b => b.name).join(", ")+ const hint = available+ ? `Pass --brain <name> (available: ${available}), or edit ${CSB_CONFIG} and set \`default = "<name>"\`.`+ : `Run \`claude-second-brain <name>\` to create your first brain.`+ throw new Error(`No default brain set in config.toml. ${hint}`)+ }const entry = brains.find(b => b.name === target)- if (!entry) throw new Error(`No brain named "${target}". Run \`claude-second-brain ls\` to see registered brains.`)+ if (!entry) {+ const available = brains.map(b => b.name).join(", ") || "(none)"+ throw new Error(`No brain named "${target}". Available: ${available}. Run \`claude-second-brain ls\` to list brains.`)+ }return entry}@@ -673,15 +701,21 @@ async function writeConfig(brainName, brainPath, qmdPath, gitRemote) {// Config doesn't exist yet — create fresh}- if (!existing) {+ if (!existing || !existing.trim()) {await writeFile(CSB_CONFIG, `default = "${brainName}"\n\n${entry}\n`, "utf8")return}// Upsert: remove existing entry for this brain name, then append updated entry.// Also migrate legacy `active = …` to `default = …` on any write.+ // If the header lacks any default/active key (e.g. user hand-edited an empty+ // file, or earlier versions of this CLI wrote entries without one), inject+ // `default = "${brainName}"` so CLI subcommands can resolve a default.const blocks = existing.split(/\n(?=\[\[brains\]\])/)- const header = blocks[0].replace(/^active\s*=/m, "default =")+ let header = blocks[0].replace(/^active\s*=/m, "default =")+ if (!/^default\s*=/m.test(header)) {+ header = `default = "${brainName}"\n\n${header.trimStart()}`+ }const otherBrains = blocks.slice(1).filter(b => !b.includes(`name = "${brainName}"`))await writeFile(CSB_CONFIG, [header, ...otherBrains, entry].join("\n").trimEnd() + "\n", "utf8")}@@ -812,9 +846,14 @@ async function createBrain(initialName) {}if (doQmdSetup) {spin.start("Registering qmd collections (wiki, raw-sources)")- const qmdOk = run(["mise", "exec", "--", "pnpm", "qmd:setup"], targetDir)- if (qmdOk) spin.stop("qmd collections registered")- else spin.stop("pnpm qmd:setup failed — run it manually inside your vault", 1)+ const qmdRes = runCapture(["mise", "exec", "--", "pnpm", "qmd:setup"], targetDir)+ if (qmdRes.ok) {+ spin.stop("qmd collections registered")+ } else {+ spin.stop("pnpm qmd:setup failed — run it manually inside your vault", 1)+ const tail = tailForError(qmdRes)+ if (tail) p.log.warn(`qmd:setup output:\n${tail}`)+ }} else {p.log.info("Skipped qmd:setup — run `pnpm qmd:setup` from the vault root when ready.")}diff --git a/template/scripts/qmd/reindex.ts b/template/scripts/qmd/reindex.tsindex 4676b34..4429768 100644--- a/template/scripts/qmd/reindex.ts+++ b/template/scripts/qmd/reindex.ts@@ -17,23 +17,30 @@ import { fileURLToPath } from "node:url"const VAULT = join(dirname(fileURLToPath(import.meta.url)), "../..")const DB = join(VAULT, ".qmd", "index.sqlite")-const store = await createStore({ dbPath: DB })+try {+ const store = await createStore({ dbPath: DB })-console.log("Updating file index...")-const result = await store.update({- onProgress: ({ collection, file, current, total }: any) => {- process.stdout.write(`\r [${collection}] ${current}/${total} ${file}`.padEnd(80))- },-})-console.log(- `\n indexed: ${result.indexed} | updated: ${result.updated} | ` +- `removed: ${result.removed} | needs embedding: ${result.needsEmbedding}`-)+ console.log("Updating file index...")+ const result = await store.update({+ onProgress: ({ collection, file, current, total }: any) => {+ process.stdout.write(`\r [${collection}] ${current}/${total} ${file}`.padEnd(80))+ },+ })+ console.log(+ `\n indexed: ${result.indexed} | updated: ${result.updated} | ` ++ `removed: ${result.removed} | needs embedding: ${result.needsEmbedding}`+ )-console.log("Generating embeddings...")-await store.embed({- onProgress: ({ current, total, collection }: any) => {- process.stdout.write(`\r [${collection}] ${current}/${total}`.padEnd(60))- },-})-console.log("\nDone.")+ console.log("Generating embeddings...")+ await store.embed({+ onProgress: ({ current, total, collection }: any) => {+ process.stdout.write(`\r [${collection}] ${current}/${total}`.padEnd(60))+ },+ })+ console.log("\nDone.")+} catch (err: any) {+ console.error(`\n[qmd:reindex] ${err?.message || err}`)+ console.error(` vault: ${VAULT}`)+ console.error(` db: ${DB}`)+ process.exit(1)+}diff --git a/template/scripts/qmd/setup.ts b/template/scripts/qmd/setup.tsindex 6a10412..aaaa3e7 100644--- a/template/scripts/qmd/setup.ts+++ b/template/scripts/qmd/setup.ts@@ -16,42 +16,49 @@ import { fileURLToPath } from "node:url"const VAULT = join(dirname(fileURLToPath(import.meta.url)), "../..")const DB = join(VAULT, ".qmd", "index.sqlite")-const store = await createStore({ dbPath: DB })+try {+ const store = await createStore({ dbPath: DB })-// --- Collections (idempotent) ----const existingCols = await store.listCollections()-const existing = new Set(existingCols.map((c: any) => c.name))+ // --- Collections (idempotent) ---+ const existingCols = await store.listCollections()+ const existing = new Set(existingCols.map((c: any) => c.name))-async function ensureCollection(name: string, relPath: string, pattern: string) {- if (existing.has(name)) {- console.log(` skip (exists): ${name}`)- return+ async function ensureCollection(name: string, relPath: string, pattern: string) {+ if (existing.has(name)) {+ console.log(` skip (exists): ${name}`)+ return+ }+ await store.addCollection(name, { path: join(VAULT, relPath), pattern })+ console.log(` added: ${name}`)}- await store.addCollection(name, { path: join(VAULT, relPath), pattern })- console.log(` added: ${name}`)-}-console.log("Collections:")-await ensureCollection("wiki", "wiki", "**/*.md")-await ensureCollection("raw-sources", "raw-sources", "**/*.md")--// --- Global context ----console.log("\nContexts:")-await store.setGlobalContext(- "Personal knowledge vault. Uses Obsidian [[wiki/page]] wikilinks. " +- "Wiki pages have YAML frontmatter: type (overview|topic|entity|source-summary|qa), " +- "tags, sources, related, updated."-)--// wiki/-await store.addContext("wiki", "", "LLM-maintained synthesized knowledge base — the authoritative wiki layer")-await store.addContext("wiki", "/sources", "Source summaries — one page per ingested source, with abstract, key claims, and synthesis notes")-await store.addContext("wiki", "/qa", "Filed Q&A answers that synthesize multiple wiki pages around a notable question")--// raw-sources/-await store.addContext("raw-sources", "", "Raw source material — immutable originals, never modified after ingestion")-await store.addContext("raw-sources", "/articles", "Web articles saved as markdown")-await store.addContext("raw-sources", "/pdfs", "PDF files or their extracted text")-await store.addContext("raw-sources", "/personal", "Personal notes flagged for wiki ingestion")--console.log("\nSetup complete. Run: pnpm qmd:reindex")+ console.log("Collections:")+ await ensureCollection("wiki", "wiki", "**/*.md")+ await ensureCollection("raw-sources", "raw-sources", "**/*.md")++ // --- Global context ---+ console.log("\nContexts:")+ await store.setGlobalContext(+ "Personal knowledge vault. Uses Obsidian [[wiki/page]] wikilinks. " ++ "Wiki pages have YAML frontmatter: type (overview|topic|entity|source-summary|qa), " ++ "tags, sources, related, updated."+ )++ // wiki/+ await store.addContext("wiki", "", "LLM-maintained synthesized knowledge base — the authoritative wiki layer")+ await store.addContext("wiki", "/sources", "Source summaries — one page per ingested source, with abstract, key claims, and synthesis notes")+ await store.addContext("wiki", "/qa", "Filed Q&A answers that synthesize multiple wiki pages around a notable question")++ // raw-sources/+ await store.addContext("raw-sources", "", "Raw source material — immutable originals, never modified after ingestion")+ await store.addContext("raw-sources", "/articles", "Web articles saved as markdown")+ await store.addContext("raw-sources", "/pdfs", "PDF files or their extracted text")+ await store.addContext("raw-sources", "/personal", "Personal notes flagged for wiki ingestion")++ console.log("\nSetup complete. Run: pnpm qmd:reindex")+} catch (err: any) {+ console.error(`\n[qmd:setup] ${err?.message || err}`)+ console.error(` vault: ${VAULT}`)+ console.error(` db: ${DB}`)+ process.exit(1)+}