claude-second-brain 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/create.js CHANGED
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { cp, rename, access, readFile, writeFile, mkdir, rm } from "fs/promises"
3
- import { readFileSync } from "fs"
3
+ import { readFileSync, readdirSync } from "fs"
4
4
  import { join, dirname } from "path"
5
5
  import { fileURLToPath } from "url"
6
- import { spawnSync } from "child_process"
6
+ import { spawn, spawnSync } from "child_process"
7
7
  import { homedir } from "os"
8
8
  import * as p from "@clack/prompts"
9
9
  import pc from "picocolors"
10
+ import {
11
+ AGENTS, AGENT_IDS, CANONICAL_GLOBAL_DIR, detectAgents,
12
+ installProjectSkills, linkGlobalSkill, parseAgentFlags, resolveAgents, writeCanonicalSkill,
13
+ } from "./agents.js"
10
14
 
11
15
  const __dirname = dirname(fileURLToPath(import.meta.url))
12
16
  const TEMPLATE = join(__dirname, "../template")
@@ -39,6 +43,62 @@ function tailForError({ stdout, stderr }, lines = 10) {
39
43
  return trimmed.split("\n").slice(-lines).join("\n")
40
44
  }
41
45
 
46
+ // Async variant for long-running steps: doesn't block the event loop, so the
47
+ // spinner keeps animating. `onLine` receives each non-empty output line.
48
+ function runAsync(cmd, cwd, { onLine } = {}) {
49
+ return new Promise(resolve => {
50
+ let stdout = ""
51
+ let stderr = ""
52
+ let child
53
+ try {
54
+ child = spawn(cmd[0], cmd.slice(1), { cwd, stdio: ["ignore", "pipe", "pipe"] })
55
+ } catch (err) {
56
+ resolve({ ok: false, stdout, stderr: err.message })
57
+ return
58
+ }
59
+ const feed = chunk => {
60
+ if (!onLine) return
61
+ for (const line of chunk.split(/\r?\n|\r/)) {
62
+ const clean = stripAnsi(line).trim()
63
+ if (clean) onLine(clean)
64
+ }
65
+ }
66
+ child.stdout.on("data", d => { const t = d.toString(); stdout += t; feed(t) })
67
+ child.stderr.on("data", d => { const t = d.toString(); stderr += t; feed(t) })
68
+ child.on("error", err => resolve({ ok: false, stdout, stderr: stderr + err.message }))
69
+ child.on("close", code => resolve({ ok: code === 0, stdout, stderr }))
70
+ })
71
+ }
72
+
73
+ // Run a long step under the spinner, showing elapsed time and the latest
74
+ // line of output so it's obvious the CLI isn't stuck.
75
+ async function runStep(spin, label, cmd, cwd) {
76
+ const started = Date.now()
77
+ let last = ""
78
+ const render = () => {
79
+ const secs = Math.round((Date.now() - started) / 1000)
80
+ const detail = last ? ` ${pc.dim(truncate(last, 60))}` : ""
81
+ spin.message(`${label} ${pc.dim(`(${secs}s)`)}${detail}`)
82
+ }
83
+ spin.start(label)
84
+ const timer = setInterval(render, 1000)
85
+ try {
86
+ const res = await runAsync(cmd, cwd, { onLine: l => { last = l } })
87
+ return { ...res, seconds: Math.round((Date.now() - started) / 1000) }
88
+ } finally {
89
+ clearInterval(timer)
90
+ }
91
+ }
92
+
93
+ // Use the pnpm already on PATH when it's recent enough (the CLI itself runs on
94
+ // Node >= 22), so a fresh scaffold doesn't download node + pnpm through mise.
95
+ function systemPnpmUsable() {
96
+ const r = spawnSync("pnpm", ["--version"], { stdio: "pipe", encoding: "utf8" })
97
+ if (r.status !== 0) return false
98
+ const major = parseInt((r.stdout || "").trim().split(".")[0], 10)
99
+ return major >= 10 && parseInt(process.versions.node.split(".")[0], 10) >= 22
100
+ }
101
+
42
102
  // Interactive commands (e.g. gh auth login) — must inherit stdio; call outside spinner
43
103
  function runInteractive(cmd, cwd) {
44
104
  const result = spawnSync(cmd[0], cmd.slice(1), { cwd, stdio: "inherit" })
@@ -87,6 +147,24 @@ function extractBearerToken(stdout) {
87
147
  return candidates[0] || null
88
148
  }
89
149
 
150
+ // Spinner wrapper: clack redraws the spinner line in place, which breaks into
151
+ // one new line per frame if the message wraps past the terminal width. Clamp
152
+ // every start/message to a single line that fits.
153
+ function fitLine(msg) {
154
+ const max = Math.max(20, (process.stdout.columns || 80) - 6)
155
+ const oneLine = String(msg).replace(/\s*\n\s*/g, " ")
156
+ const plain = stripAnsi(oneLine)
157
+ return plain.length > max ? plain.slice(0, max - 1) + "…" : oneLine
158
+ }
159
+ function makeSpinner() {
160
+ const spin = p.spinner()
161
+ return {
162
+ start: msg => spin.start(fitLine(msg)),
163
+ message: msg => spin.message(fitLine(msg)),
164
+ stop: (msg, code) => spin.stop(msg, code),
165
+ }
166
+ }
167
+
90
168
  function truncate(s, n = 80) {
91
169
  if (!s) return ""
92
170
  return s.length > n ? s.slice(0, n) + "…" : s
@@ -95,6 +173,111 @@ function truncate(s, n = 80) {
95
173
  // End-to-end Cloudflare Artifacts setup: auth, create repo, set remote, push.
96
174
  // Every failure logs the exact step, exit codes, stderr, and HTTP bodies so the
97
175
  // user can see where in the flow the break happened.
176
+ // Artifacts REST API: https://developers.cloudflare.com/artifacts/api/rest-api/
177
+ // Routes are account-scoped under the standard Cloudflare v4 API. (The
178
+ // artifacts.cloudflare.net/v1/api host from the beta announcement rejects
179
+ // wrangler OAuth tokens with 403 / code 10002.)
180
+ // Icons for the git-remote picker. Terminals can't draw SVG inside a prompt
181
+ // that redraws on every keypress, so the real logos come from Nerd Font
182
+ // glyphs: Ghostty, WezTerm and kitty bundle them, so they're on by default
183
+ // there. Anywhere else (iTerm2, Terminal.app, …) we fall back to emoji unless
184
+ // CSB_ICONS=nerd says a Nerd Font is installed. CSB_ICONS=emoji|none override.
185
+ function iconStyle() {
186
+ const forced = process.env.CSB_ICONS?.trim().toLowerCase()
187
+ if (forced === "nerd" || forced === "emoji" || forced === "none") return forced
188
+ const term = process.env.TERM_PROGRAM?.toLowerCase() || ""
189
+ if (term === "ghostty" || term === "wezterm" || process.env.KITTY_WINDOW_ID || process.env.TERM === "xterm-kitty") return "nerd"
190
+ return "emoji"
191
+ }
192
+ const CF_ORANGE = (s) => (pc.isColorSupported ? `\x1b[38;2;243;128;32m${s}\x1b[39m` : s)
193
+ const REMOTE_ICONS = {
194
+ // nf-fa-github, nf-fa-cloud (filled, in Cloudflare orange — the
195
+ // nf-dev-cloudflare glyph renders tiny), nf-oct-file_directory.
196
+ // Each entry includes its trailing gap: Nerd glyphs are drawn ~1.5 cells
197
+ // wide so one space reads right; emoji are 2 cells and want two.
198
+ nerd: { github: "\uf09b ", cloudflare: CF_ORANGE("\uf0c2") + " ", none: "\uf413 " },
199
+ emoji: { github: "🐙 ", cloudflare: "⛅ ", none: "📁 " },
200
+ none: { github: "", cloudflare: "", none: "" },
201
+ }[iconStyle()]
202
+
203
+ const CF_API = "https://api.cloudflare.com/client/v4"
204
+ function artifactsBase(accountId, namespace) {
205
+ return `${CF_API}/accounts/${accountId}/artifacts/namespaces/${namespace}`
206
+ }
207
+
208
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
209
+
210
+ function cfErrorCodes(rawBody) {
211
+ try { return (JSON.parse(rawBody)?.errors || []).map((e) => e?.code) } catch { return [] }
212
+ }
213
+
214
+ function isNamespaceInactive(res, rawBody) {
215
+ return res.status === 404 && (cfErrorCodes(rawBody).includes(10200) || /namespace is not active/i.test(rawBody))
216
+ }
217
+
218
+ // Make sure an Artifacts namespace exists and is usable. Creates it when
219
+ // missing; tolerates "already exists" and 409 (activation / deletion in
220
+ // progress) by polling until it settles. Returns { ok, error? }.
221
+ async function ensureArtifactsNamespace({ accountId, namespace, token }) {
222
+ const url = `${CF_API}/accounts/${accountId}/artifacts/namespaces`
223
+ const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
224
+ let lastError = "unknown error"
225
+ for (let attempt = 0; attempt < 8; attempt++) {
226
+ let res, body = ""
227
+ try {
228
+ res = await fetch(url, { method: "POST", headers, body: JSON.stringify({ namespace }) })
229
+ body = await res.text()
230
+ } catch (err) {
231
+ return { ok: false, error: `network error: ${err.message}` }
232
+ }
233
+ if (res.ok) return { ok: true, created: true }
234
+ let msg = "unknown error"
235
+ try { msg = JSON.parse(body)?.errors?.[0]?.message || msg } catch {}
236
+ lastError = `HTTP ${res.status}: ${msg}`
237
+ if (res.status === 401 || res.status === 403) return { ok: false, error: lastError }
238
+ // Already exists → fine, the repo-create retry loop handles activation lag.
239
+ if (/already exists/i.test(msg)) return { ok: true, created: false }
240
+ // 409 = activation or deletion in progress; anything else, back off and retry.
241
+ await sleep(Math.min(1000 * 2 ** attempt, 8000))
242
+ }
243
+ return { ok: false, error: lastError }
244
+ }
245
+
246
+ // Account ID from a repo remote like https://<ACCOUNT_ID>.artifacts.cloudflare.net/git/<ns>/<repo>.git
247
+ function accountIdFromRemote(url) {
248
+ const m = (url || "").match(/^https?:\/\/([0-9a-f]{32})\.artifacts\.cloudflare\.net\//i)
249
+ return m ? m[1] : null
250
+ }
251
+
252
+ // Resolve the Cloudflare account to create the repo in:
253
+ // CLOUDFLARE_ACCOUNT_ID, else the token's only account, else ask.
254
+ async function resolveCloudflareAccountId(token, { interactive = false } = {}) {
255
+ const fromEnv = process.env.CLOUDFLARE_ACCOUNT_ID?.trim()
256
+ if (fromEnv) return { id: fromEnv }
257
+ let data
258
+ try {
259
+ const res = await fetch(`${CF_API}/accounts?per_page=50`, { headers: { Authorization: `Bearer ${token}` } })
260
+ data = await res.json()
261
+ if (!res.ok || !data?.success) {
262
+ return { error: `listing accounts failed (HTTP ${res.status}): ${data?.errors?.[0]?.message || "unknown error"}` }
263
+ }
264
+ } catch (err) {
265
+ return { error: `listing accounts failed: ${err.message}` }
266
+ }
267
+ const accounts = data.result || []
268
+ if (accounts.length === 0) return { error: "this token can't see any Cloudflare accounts" }
269
+ if (accounts.length === 1) return { id: accounts[0].id, name: accounts[0].name }
270
+ if (!interactive) {
271
+ return { error: `token can access ${accounts.length} accounts — set CLOUDFLARE_ACCOUNT_ID to pick one` }
272
+ }
273
+ const picked = await p.select({
274
+ message: "Which Cloudflare account?",
275
+ options: accounts.map(a => ({ value: a.id, label: a.name, hint: a.id })),
276
+ })
277
+ if (p.isCancel(picked)) return { error: "no account selected" }
278
+ return { id: picked, name: accounts.find(a => a.id === picked)?.name }
279
+ }
280
+
98
281
  async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
99
282
  // Honor an existing API token as a shortcut — skip wrangler entirely.
100
283
  let cfApiToken = process.env.CLOUDFLARE_API_TOKEN
@@ -174,13 +357,17 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
174
357
 
175
358
  p.log.info(`Using token from ${tokenSource} (length ${cfApiToken.length}, prefix ${cfApiToken.slice(0, 8)}…)`)
176
359
 
177
- const baseUrl = `https://artifacts.cloudflare.net/v1/api/namespaces/${namespace}`
178
- spin.start(`Creating Cloudflare Artifact ${pc.dim(repoName)} at ${pc.dim(baseUrl)}`)
360
+ const account = await resolveCloudflareAccountId(cfApiToken, { interactive: Boolean(process.stdin.isTTY) })
361
+ if (!account.id) {
362
+ p.log.warn(`Could not determine your Cloudflare account: ${account.error}`)
363
+ return null
364
+ }
365
+ const baseUrl = artifactsBase(account.id, namespace)
366
+ p.log.info(`Artifacts API: ${pc.dim(baseUrl)}`)
367
+ spin.start(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)
179
368
 
180
- let res
181
- let rawBody = ""
182
- try {
183
- res = await fetch(`${baseUrl}/repos`, {
369
+ const createRepo = async () => {
370
+ const r = await fetch(`${baseUrl}/repos`, {
184
371
  method: "POST",
185
372
  headers: {
186
373
  "Authorization": `Bearer ${cfApiToken}`,
@@ -188,7 +375,38 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
188
375
  },
189
376
  body: JSON.stringify({ name: repoName, default_branch: "main" }),
190
377
  })
191
- rawBody = await res.text()
378
+ return { res: r, rawBody: await r.text() }
379
+ }
380
+
381
+ let res
382
+ let rawBody = ""
383
+ try {
384
+ ;({ res, rawBody } = await createRepo())
385
+ // A namespace that was deleted (or is still being deleted) answers
386
+ // 404 / code 10200 "Namespace is not active". Recreate it, wait for it
387
+ // to become active, and retry the repo create.
388
+ if (isNamespaceInactive(res, rawBody)) {
389
+ spin.message(`Namespace ${pc.dim(namespace)} is not active — creating it`)
390
+ const ns = await ensureArtifactsNamespace({ accountId: account.id, namespace, token: cfApiToken })
391
+ if (!ns.ok) {
392
+ spin.stop(`Could not activate Artifacts namespace "${namespace}": ${ns.error}`, 1)
393
+ p.log.warn([
394
+ "To fix:",
395
+ ` • wait a minute and run ${pc.cyan("csb")} again (a just-deleted namespace can take a moment to clear), or`,
396
+ ` • pick a different namespace when prompted, or`,
397
+ ` • create it in the Cloudflare dashboard (Artifacts → Namespaces → Create "${namespace}")`,
398
+ ].join("\n"))
399
+ return null
400
+ }
401
+ spin.stop(`Cloudflare namespace ${ns.created ? "created" : "reactivated"}: ${namespace}`)
402
+ spin.start(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)
403
+ for (let attempt = 0; attempt < 8; attempt++) {
404
+ spin.message(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)
405
+ ;({ res, rawBody } = await createRepo())
406
+ if (!isNamespaceInactive(res, rawBody)) break
407
+ await sleep(Math.min(1000 * 2 ** attempt, 8000))
408
+ }
409
+ }
192
410
  } catch (err) {
193
411
  spin.stop(`Network error calling Artifacts API: ${err.message}`, 1)
194
412
  return null
@@ -207,6 +425,14 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
207
425
  const errMsg = createData?.errors?.[0]?.message || createData?.message || "unknown error"
208
426
  spin.stop(`Artifacts API failed (HTTP ${res.status}): ${errMsg}`, 1)
209
427
  p.log.warn(`full response: ${truncate(rawBody, 400)}`)
428
+ if (res.status === 401 || res.status === 403) {
429
+ p.log.warn([
430
+ "Check that:",
431
+ ` • Artifacts is enabled for account ${account.name ? `"${account.name}" ` : ""}(${account.id}) — it needs the Workers Paid plan`,
432
+ " • your token has Artifacts > Edit (API token) or the artifacts:write scope (wrangler login)",
433
+ " • CLOUDFLARE_ACCOUNT_ID points at the right account, if you set it",
434
+ ].join("\n"))
435
+ }
210
436
  return null
211
437
  }
212
438
 
@@ -236,12 +462,12 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
236
462
  const stdout = pushResult.stdout?.toString().trim()
237
463
  if (stderr) p.log.warn(`git stderr: ${truncate(stderr, 400)}`)
238
464
  if (stdout) p.log.warn(`git stdout: ${truncate(stdout, 400)}`)
239
- return { repoToken, remote }
465
+ return { repoToken, remote, accountId: account.id, pushed: false }
240
466
  }
241
467
 
242
468
  spin.stop(`Cloudflare Artifact created: ${pc.cyan(repoName)}`)
243
469
  p.log.info(`Remote: ${pc.dim(remote)}`)
244
- return { repoToken, remote }
470
+ return { repoToken, remote, accountId: account.id, pushed: true }
245
471
  }
246
472
 
247
473
  function parseGithubRepo(url) {
@@ -252,10 +478,11 @@ function parseGithubRepo(url) {
252
478
 
253
479
  function parseCloudflareArtifact(url) {
254
480
  if (!url || !/artifacts\.cloudflare/.test(url)) return null
481
+ const accountId = accountIdFromRemote(url)
255
482
  const explicit = url.match(/namespaces\/([^/]+)\/repos\/([^/.]+)/)
256
- if (explicit) return { namespace: explicit[1], repo: explicit[2] }
483
+ if (explicit) return { namespace: explicit[1], repo: explicit[2], accountId }
257
484
  const parts = url.replace(/\.git$/, "").split("/").filter(Boolean)
258
- if (parts.length >= 2) return { namespace: parts[parts.length - 2], repo: parts[parts.length - 1] }
485
+ if (parts.length >= 2) return { namespace: parts[parts.length - 2], repo: parts[parts.length - 1], accountId }
259
486
  return null
260
487
  }
261
488
 
@@ -281,11 +508,16 @@ function deleteGithubRepo(slug) {
281
508
  return { ok: true }
282
509
  }
283
510
 
284
- async function deleteCloudflareArtifact({ namespace, repo }) {
511
+ async function deleteCloudflareArtifact({ namespace, repo, accountId }) {
285
512
  const auth = await resolveCloudflareToken()
286
513
  if (!auth) return { ok: false, error: "no Cloudflare API token (set CLOUDFLARE_API_TOKEN or run `wrangler login`)" }
514
+ if (!accountId) {
515
+ const account = await resolveCloudflareAccountId(auth.token, { interactive: Boolean(process.stdin.isTTY) })
516
+ if (!account.id) return { ok: false, error: account.error }
517
+ accountId = account.id
518
+ }
287
519
  try {
288
- const res = await fetch(`https://artifacts.cloudflare.net/v1/api/namespaces/${namespace}/repos/${repo}`, {
520
+ const res = await fetch(`${artifactsBase(accountId, namespace)}/repos/${repo}`, {
289
521
  method: "DELETE",
290
522
  headers: { Authorization: `Bearer ${auth.token}` },
291
523
  })
@@ -300,6 +532,11 @@ async function deleteCloudflareArtifact({ namespace, repo }) {
300
532
  }
301
533
 
302
534
  const GLOBAL_SKILLS = ["brain-ingest", "brain-search", "brain-refresh"]
535
+ // Vault-local skills: every template skill that isn't global.
536
+ const LOCAL_SKILLS = readdirSync(join(TEMPLATE, ".claude", "skills"), { withFileTypes: true })
537
+ .filter(d => d.isDirectory() && !GLOBAL_SKILLS.includes(d.name))
538
+ .map(d => d.name)
539
+ const CANONICAL_PROJECT_DIR_LABEL = ".agents/skills (project) and ~/.agents/skills (global)"
303
540
 
304
541
  async function readSkillVersion(skillDir) {
305
542
  try {
@@ -310,6 +547,14 @@ async function readSkillVersion(skillDir) {
310
547
  }
311
548
  }
312
549
 
550
+ // Installed version of a global skill: the canonical ~/.agents/skills copy,
551
+ // falling back to a legacy ~/.claude/skills copy from releases before
552
+ // multi-agent install.
553
+ async function readInstalledGlobalVersion(name) {
554
+ return (await readSkillVersion(join(CANONICAL_GLOBAL_DIR, name)))
555
+ || (await readSkillVersion(join(homedir(), ".claude", "skills", name)))
556
+ }
557
+
313
558
  // Decide whether to (re)install each global skill. Returns a map name→"install"|"skip".
314
559
  // Interactive mismatch prompts once per run with update-all / skip-all / ask-per-skill.
315
560
  async function planGlobalSkillInstall({ isInteractive }) {
@@ -317,12 +562,13 @@ async function planGlobalSkillInstall({ isInteractive }) {
317
562
  const mismatches = []
318
563
 
319
564
  for (const name of GLOBAL_SKILLS) {
320
- const destDir = join(homedir(), ".claude", "skills", name)
321
- const installed = await readSkillVersion(destDir)
565
+ const installed = await readInstalledGlobalVersion(name)
566
+ const hasCanonical = await readSkillVersion(join(CANONICAL_GLOBAL_DIR, name))
322
567
  if (!installed) {
323
568
  decisions[name] = "install"
324
569
  } else if (installed === version) {
325
- decisions[name] = "skip"
570
+ // Same version but only a legacy copy exists: migrate to the canonical dir.
571
+ decisions[name] = hasCanonical ? "skip" : "install"
326
572
  } else {
327
573
  mismatches.push({ name, installed })
328
574
  }
@@ -366,40 +612,230 @@ async function planGlobalSkillInstall({ isInteractive }) {
366
612
  return decisions
367
613
  }
368
614
 
369
- async function installGlobalSkills({ isInteractive }) {
370
- const globalSkillsDir = join(homedir(), ".claude", "skills")
615
+ // Install the global skills for each selected agent, the way `npx skills` does:
616
+ // one real copy in ~/.agents/skills/<name>, then a symlink (or copy, with
617
+ // --copy or when symlinks fail) in every agent's own global skills dir.
618
+ // Universal agents (Codex, Cursor, Copilot, …) read ~/.agents/skills directly.
619
+ async function installGlobalSkills({ isInteractive, agents, copy = false }) {
371
620
  const decisions = await planGlobalSkillInstall({ isInteractive })
372
621
 
373
622
  const installed = []
374
623
  const skipped = []
375
624
  const sameVersion = []
625
+ const links = []
376
626
 
377
- await Promise.all(GLOBAL_SKILLS.map(async name => {
378
- const destDir = join(globalSkillsDir, name)
627
+ for (const name of GLOBAL_SKILLS) {
379
628
  const decision = decisions[name]
629
+ const canonical = join(CANONICAL_GLOBAL_DIR, name)
380
630
 
381
631
  if (decision === "skip") {
382
632
  // Differentiate "already at this version" from "user declined update" for logging.
383
- const current = await readSkillVersion(destDir)
633
+ const current = await readInstalledGlobalVersion(name)
384
634
  if (current === version) sameVersion.push(name)
385
635
  else skipped.push(name)
386
- return
636
+ // A declined update with only a legacy copy: leave everything untouched.
637
+ if (!(await readSkillVersion(canonical))) continue
638
+ } else {
639
+ const content = await readFile(join(TEMPLATE, ".claude/skills", name, "SKILL.md"), "utf8")
640
+ await writeCanonicalSkill(name, {
641
+ "SKILL.md": content,
642
+ ".csb-version": JSON.stringify({ version, installed: new Date().toISOString() }, null, 2) + "\n",
643
+ })
644
+ installed.push(name)
645
+ }
646
+
647
+ // (Re)link for every selected agent — idempotent, so newly added agents
648
+ // pick up skills even when the canonical copy is already current.
649
+ for (const id of agents) {
650
+ links.push({ name, ...(await linkGlobalSkill(id, name, { copy })) })
387
651
  }
652
+ }
388
653
 
389
- const srcFile = join(TEMPLATE, ".claude/skills", name, "SKILL.md")
390
- const content = await readFile(srcFile, "utf8")
654
+ return { installed, skipped, sameVersion, links }
655
+ }
391
656
 
392
- await mkdir(destDir, { recursive: true })
393
- await writeFile(join(destDir, "SKILL.md"), content, "utf8")
394
- await writeFile(
395
- join(destDir, ".csb-version"),
396
- JSON.stringify({ version, installed: new Date().toISOString() }, null, 2) + "\n",
397
- "utf8",
398
- )
399
- installed.push(name)
400
- }))
657
+ function summarizeAgentInstall(agents, links, toDisplayPath) {
658
+ return agents.map(id => {
659
+ const own = links.filter(l => l.agent === id)
660
+ const mode = own.some(l => l.mode === "copy") ? "copy"
661
+ : own.some(l => l.mode === "symlink") ? "symlink" : "canonical"
662
+ const where = mode === "canonical"
663
+ ? toDisplayPath(CANONICAL_GLOBAL_DIR)
664
+ : toDisplayPath(dirname(own[0]?.path || ""))
665
+ return ` ${AGENTS[id].displayName.padEnd(15)} ${pc.dim(`${where}${mode === "canonical" ? "" : ` (${mode})`}`)}`
666
+ }).join("\n")
667
+ }
401
668
 
402
- return { installed, skipped, sameVersion }
669
+ // "Next steps" lines for the agents the user picked: how to open each one in
670
+ // the vault. Agents without a CLI get an "open this folder in …" hint.
671
+ function agentLaunchSteps(agents) {
672
+ const lines = agents.map(id => {
673
+ const { launch, displayName } = AGENTS[id]
674
+ return launch?.cmd
675
+ ? `${pc.cyan(launch.cmd.padEnd(16))} open ${displayName} and start ingesting sources`
676
+ : `${pc.dim("# ")}open this folder in ${launch?.app || displayName}${displayName !== launch?.app && launch?.app ? ` (${displayName})` : ""}`
677
+ })
678
+ return lines.length ? lines : [`${pc.cyan("claude".padEnd(16))} open Claude Code and start ingesting sources`]
679
+ }
680
+
681
+ // Mint a repo-scoped Artifacts git token and store it as an http.extraHeader
682
+ // for that remote in the brain's .git/config (local only, never committed),
683
+ // so plain `git push` / `git pull` work until it expires.
684
+ // Artifacts git tokens: minimum 60s, maximum 1 year (API limit). We default
685
+ // to 90 days so a brain keeps syncing for a season without renewing.
686
+ const GIT_TOKEN_TTL_DEFAULT = 90 * 86400
687
+ const GIT_TOKEN_TTL_MAX = 365 * 86400
688
+
689
+ // "90d", "12h", "30m", "1y", or plain seconds → seconds.
690
+ function parseTtl(v) {
691
+ const m = String(v ?? "").trim().match(/^(\d+)\s*([smhdwy]?)$/i)
692
+ if (!m) return NaN
693
+ const mult = { "": 1, s: 1, m: 60, h: 3600, d: 86400, w: 604800, y: 31536000 }[m[2].toLowerCase()]
694
+ return parseInt(m[1], 10) * mult
695
+ }
696
+
697
+ function formatTtl(secs) {
698
+ if (secs % 31536000 === 0) return `${secs / 31536000} year${secs === 31536000 ? "" : "s"}`
699
+ if (secs % 86400 === 0) return `${secs / 86400} day${secs === 86400 ? "" : "s"}`
700
+ if (secs % 3600 === 0) return `${secs / 3600}h`
701
+ return `${Math.round(secs / 60)} min`
702
+ }
703
+
704
+ async function mintArtifactsGitToken({ remote, cwd, ttl = GIT_TOKEN_TTL_DEFAULT, scope = "write", interactive = false }) {
705
+ const parsed = parseCloudflareArtifact(remote)
706
+ if (!parsed) return { ok: false, error: `not a Cloudflare Artifacts remote: ${remote || "(none)"}` }
707
+ const auth = await resolveCloudflareToken()
708
+ if (!auth) return { ok: false, error: "no Cloudflare credentials — run `wrangler login` or set CLOUDFLARE_API_TOKEN" }
709
+ let accountId = parsed.accountId
710
+ if (!accountId) {
711
+ const account = await resolveCloudflareAccountId(auth.token, { interactive })
712
+ if (!account.id) return { ok: false, error: account.error }
713
+ accountId = account.id
714
+ }
715
+ let data
716
+ try {
717
+ const res = await fetch(`${artifactsBase(accountId, parsed.namespace)}/tokens`, {
718
+ method: "POST",
719
+ headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
720
+ body: JSON.stringify({ repo: parsed.repo, scope, ttl }),
721
+ })
722
+ data = await res.json().catch(() => ({}))
723
+ if (!res.ok || !data?.success) {
724
+ return { ok: false, error: `Artifacts API (HTTP ${res.status}): ${data?.errors?.[0]?.message || "unknown error"}` }
725
+ }
726
+ } catch (err) {
727
+ return { ok: false, error: err.message }
728
+ }
729
+ const token = data.result?.plaintext || data.result?.token
730
+ if (!token) return { ok: false, error: "Artifacts API response had no token" }
731
+ const expiresAt = data.result?.expires_at || null
732
+ if (cwd) setGitAuthHeader(cwd, remote, token)
733
+ return { ok: true, token, expiresAt, ...parsed, accountId }
734
+ }
735
+
736
+ function setGitAuthHeader(cwd, remote, token) {
737
+ const key = `http.${remote}.extraHeader`
738
+ spawnSync("git", ["config", "--local", "--unset-all", key], { cwd, stdio: "pipe" })
739
+ const r = spawnSync("git", ["config", "--local", "--add", key, `Authorization: Bearer ${token}`], { cwd, stdio: "pipe" })
740
+ return r.status === 0
741
+ }
742
+
743
+ // `csb git-token [--brain <name>] [--ttl <duration>] [--read] [--print]`
744
+ async function cmdGitToken(args) {
745
+ let brainName = null
746
+ let ttl = GIT_TOKEN_TTL_DEFAULT
747
+ let scope = "write"
748
+ let printOnly = false
749
+ for (let i = 0; i < args.length; i++) {
750
+ const a = args[i]
751
+ if (a === "--brain") brainName = args[++i]
752
+ else if (a === "--ttl") ttl = parseTtl(args[++i])
753
+ else if (a.startsWith("--ttl=")) ttl = parseTtl(a.slice(6))
754
+ else if (a === "--read") scope = "read"
755
+ else if (a === "--print") printOnly = true
756
+ else if (!a.startsWith("-") && !brainName) brainName = a
757
+ else throw new Error(`Unknown option: ${a}. Run \`csb git-token --help\`.`)
758
+ }
759
+ if (!Number.isFinite(ttl) || ttl < 60 || ttl > GIT_TOKEN_TTL_MAX) {
760
+ throw new Error("--ttl must be between 60s and 1 year, e.g. 3600, 12h, 90d, 1y")
761
+ }
762
+ const brain = await resolveBrain(brainName)
763
+ let remote = brain.git_remote
764
+ if (!remote) {
765
+ const r = spawnSync("git", ["remote", "get-url", "origin"], { cwd: brain.path, stdio: "pipe", encoding: "utf8" })
766
+ remote = r.status === 0 ? r.stdout.trim() : ""
767
+ }
768
+ const result = await mintArtifactsGitToken({
769
+ remote, cwd: printOnly ? null : brain.path, ttl, scope, interactive: Boolean(process.stdin.isTTY),
770
+ })
771
+ if (!result.ok) throw new Error(`Could not mint a git token for "${brain.name}": ${result.error}`)
772
+ if (printOnly) {
773
+ process.stdout.write(result.token + "\n")
774
+ return
775
+ }
776
+ const until = result.expiresAt ? new Date(result.expiresAt).toLocaleString() : `${formatTtl(ttl)} from now`
777
+ console.log(`${pc.green("✓")} ${scope} token for ${pc.cyan(`${result.namespace}/${result.repo}`)} saved to ${pc.dim(`${brain.path}/.git/config`)} — git push/pull work until ${until}.`)
778
+ }
779
+
780
+ function globalSkillSummary({ installed, skipped }) {
781
+ return [
782
+ installed.length > 0 ? `installed ${installed.length}` : null,
783
+ skipped.length > 0 ? `kept ${skipped.length}` : null,
784
+ ].filter(Boolean).join(", ") || "already up to date"
785
+ }
786
+
787
+ // `csb skills [--agent <ids>] [--copy] [--brain <name>] [--list]`
788
+ // Install / update the global skills for more agents without creating a brain,
789
+ // and copy the vault-local skills into the brain for agents that need them.
790
+ async function cmdSkills(args) {
791
+ const { agents: explicit, copy, rest } = parseAgentFlags(args)
792
+ const toDisplayPath = p => p && p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
793
+
794
+ if (rest.includes("--list") || rest[0] === "ls" || rest[0] === "list") {
795
+ const detected = detectAgents()
796
+ const lines = AGENT_IDS.map(id => {
797
+ const a = AGENTS[id]
798
+ const global = a.globalSkillsDir ? toDisplayPath(a.globalSkillsDir) : `${toDisplayPath(CANONICAL_GLOBAL_DIR)} (shared)`
799
+ const mark = detected.includes(id) ? pc.green("●") : pc.dim("○")
800
+ return `${mark} ${id.padEnd(15)} ${pc.dim(`project: ${a.skillsDir.padEnd(17)} global: ${global}`)}`
801
+ })
802
+ console.log(lines.join("\n"))
803
+ console.log(pc.dim(`\n● detected on this machine. Universal agents read ${CANONICAL_PROJECT_DIR_LABEL} directly.`))
804
+ return
805
+ }
806
+
807
+ let brainName = null
808
+ for (let i = 0; i < rest.length; i++) {
809
+ if (rest[i] === "--brain") brainName = rest[++i]
810
+ }
811
+
812
+ const isInteractive = Boolean(process.stdin.isTTY)
813
+ p.intro(`${pc.bgCyan(pc.black(" csb skills "))} v${version}`)
814
+ const agents = await resolveAgents({ explicit, isInteractive, prompts: p })
815
+ if (!agents) { p.cancel("Cancelled."); process.exit(0) }
816
+
817
+ const spin = makeSpinner()
818
+ spin.start("Installing global skills")
819
+ const result = await installGlobalSkills({ isInteractive, agents, copy })
820
+ spin.stop(`Global skills ${globalSkillSummary(result)}`)
821
+ p.log.message(summarizeAgentInstall(agents, result.links, toDisplayPath))
822
+
823
+ let brain = null
824
+ try { brain = await resolveBrain(brainName) } catch (err) {
825
+ if (brainName) throw err
826
+ }
827
+ if (brain) {
828
+ try {
829
+ await access(join(brain.path, ".claude", "skills"))
830
+ const dirs = await installProjectSkills(brain.path, join(brain.path, ".claude", "skills"), LOCAL_SKILLS, agents)
831
+ if (dirs.length > 0) {
832
+ p.log.step(`Vault skills for ${pc.cyan(brain.name)} copied to ${dirs.map(d => pc.dim(d)).join(", ")} — commit them in the vault to sync.`)
833
+ }
834
+ } catch {
835
+ p.log.warn(`No .claude/skills in ${toDisplayPath(brain.path)} — skipped vault skills.`)
836
+ }
837
+ }
838
+ p.outro("done")
403
839
  }
404
840
 
405
841
  function parseConfig(content) {
@@ -425,20 +861,180 @@ function parseConfig(content) {
425
861
  return { defaultBrain: defaultMatch ? defaultMatch[1] : null, brains, header }
426
862
  }
427
863
 
428
- function printHelp() {
429
- const lines = [
430
- `${pc.bold("claude-second-brain")} v${version}`,
431
- "",
432
- "Usage:",
433
- ` ${pc.cyan("claude-second-brain")} create a new brain (interactive)`,
434
- ` ${pc.cyan("claude-second-brain <name>")} create a new brain named <name>`,
435
- ` ${pc.cyan("claude-second-brain ls")} list all brains`,
436
- ` ${pc.cyan("claude-second-brain rm [<name>…]")} remove one or more brains (space to multi-select)`,
437
- ` ${pc.cyan("claude-second-brain path [--brain N] [flag]")} print a path (flags: --root, --qmd, --config)`,
438
- ` ${pc.cyan("claude-second-brain qmd [--brain N] -- …")} run qmd against the resolved brain`,
439
- ` ${pc.cyan("claude-second-brain help")} show this message`,
440
- ]
441
- console.log(lines.join("\n"))
864
+ function hasHelpFlag(args) {
865
+ return args.some(a => a === "--help" || a === "-h")
866
+ }
867
+
868
+ async function readConfigStatus() {
869
+ try {
870
+ const content = await readFile(CSB_CONFIG, "utf8")
871
+ const { defaultBrain, brains } = parseConfig(content)
872
+ return { defaultBrain, brains }
873
+ } catch {
874
+ return { defaultBrain: null, brains: [] }
875
+ }
876
+ }
877
+
878
+ function printHelp(topic = "top") {
879
+ const c = pc.cyan
880
+ const topics = {
881
+ top: async () => {
882
+ const { defaultBrain, brains } = await readConfigStatus()
883
+ const lines = [
884
+ `${pc.bold("claude-second-brain")} v${version} ${pc.dim("(alias: csb)")}`,
885
+ "",
886
+ "Usage:",
887
+ ` ${c("csb")} create a new brain (interactive)`,
888
+ ` ${c("csb <name>")} create a new brain named <name>`,
889
+ ` ${c("csb ls")} list all brains (default marked with *)`,
890
+ ` ${c("csb use <name>")} set the default brain`,
891
+ ` ${c("csb rm [<name>…]")} remove brains + their folders`,
892
+ ` ${c("csb path [qmd|config|root]")} print a path (default: root)`,
893
+ ` ${c("csb qmd [--brain N] <qmd args…>")} run qmd against the resolved brain`,
894
+ ` ${c("csb exec [--brain N] -- <cmd…>")} run a command inside the resolved brain`,
895
+ ` ${c("csb skills [--agent <ids>]")} install/update skills for more agents`,
896
+ ` ${c("csb git-token [<name>]")} renew a Cloudflare Artifacts git token`,
897
+ ` ${c("csb doctor")} verify your setup and suggest fixes`,
898
+ ` ${c("csb help [<command>]")} show help for a command`,
899
+ "",
900
+ "Create options:",
901
+ ` ${c("--agent, -a <ids>")} agents to install skills for (comma-separated, or \`all\`; env: CSB_AGENTS)`,
902
+ ` ${c("--copy")} copy skills into each agent dir instead of symlinking`,
903
+ "",
904
+ "Environment:",
905
+ ` ${c("CSB_USE_MISE=1")} always fetch node + pnpm with mise, even if pnpm 10+ is installed`,
906
+ ` ${c("CSB_ICONS=nerd|emoji|none")} icons in the git-remote picker`,
907
+ ` ${c("CLOUDFLARE_API_TOKEN")}, ${c("CLOUDFLARE_ACCOUNT_ID")} Cloudflare Artifacts credentials / account`,
908
+ "",
909
+ "Examples:",
910
+ ` ${c('csb qmd query -c wiki "distributed systems"')}`,
911
+ ` ${c("csb path qmd")}`,
912
+ ` ${c("csb use work")}`,
913
+ ` ${c("csb exec -- pnpm qmd:reindex")}`,
914
+ "",
915
+ `Config: ${pc.dim(CSB_CONFIG)}`,
916
+ brains.length === 0
917
+ ? pc.dim("No brains registered yet.")
918
+ : `Default brain: ${defaultBrain ? pc.cyan(defaultBrain) : pc.yellow("(none set — run `csb use <name>`)")} ${pc.dim(`(${brains.length} registered)`)}`,
919
+ ]
920
+ console.log(lines.join("\n"))
921
+ },
922
+ path: () => console.log([
923
+ `${pc.bold("csb path")} — print a path for the default (or named) brain`,
924
+ "",
925
+ "Usage:",
926
+ ` ${c("csb path [qmd|config|root] [--brain <name>]")}`,
927
+ "",
928
+ "Positional (canonical):",
929
+ ` ${c("root")} the brain's directory (default)`,
930
+ ` ${c("qmd")} the brain's qmd SQLite index`,
931
+ ` ${c("config")} the central config.toml`,
932
+ "",
933
+ "Flags:",
934
+ ` ${c("--brain <name>")} target a specific brain instead of the default`,
935
+ ` ${c("--root | --qmd | --config")} ${pc.dim("(deprecated — use positional form)")}`,
936
+ ].join("\n")),
937
+ qmd: () => console.log([
938
+ `${pc.bold("csb qmd")} — run qmd against the default (or named) brain`,
939
+ "",
940
+ "Usage:",
941
+ ` ${c("csb qmd [--brain <name>] [--] <qmd args…>")}`,
942
+ "",
943
+ `${pc.dim("`--` is optional; use it only to pass a literal `--brain` through to qmd.")}`,
944
+ "",
945
+ "Examples:",
946
+ ` ${c('csb qmd query -c wiki "kafka"')}`,
947
+ ` ${c("csb qmd --brain work search -c wiki kafka")}`,
948
+ ].join("\n")),
949
+ exec: () => console.log([
950
+ `${pc.bold("csb exec")} — run a command inside the resolved brain's directory`,
951
+ "",
952
+ "Usage:",
953
+ ` ${c("csb exec [--brain <name>] -- <cmd…>")}`,
954
+ "",
955
+ `Sets ${c("INDEX_PATH")} to the brain's qmd index and ${c("cwd")} to the brain's root.`,
956
+ "",
957
+ "Examples:",
958
+ ` ${c("csb exec -- pnpm qmd:reindex")}`,
959
+ ` ${c("csb exec --brain work -- git status")}`,
960
+ ].join("\n")),
961
+ use: () => console.log([
962
+ `${pc.bold("csb use")} — set the default brain`,
963
+ "",
964
+ "Usage:",
965
+ ` ${c("csb use <name>")} ${pc.dim("(aliases: default, switch)")}`,
966
+ "",
967
+ "Rewrites the `default = …` line in config.toml. Affects every command that resolves the default brain (path, qmd, exec, global skills).",
968
+ ].join("\n")),
969
+ rm: () => console.log([
970
+ `${pc.bold("csb rm")} — remove one or more brains`,
971
+ "",
972
+ "Usage:",
973
+ ` ${c("csb rm [<name>…] [-y|--yes] [--delete-remote|--keep-remote]")} ${pc.dim("(alias: remove)")}`,
974
+ "",
975
+ "Flags:",
976
+ ` ${c("-y, --yes")} skip the confirmation prompt`,
977
+ ` ${c("--delete-remote")} also delete GitHub/Cloudflare remotes (no prompt)`,
978
+ ` ${c("--keep-remote")} keep remotes (no prompt)`,
979
+ "",
980
+ `${pc.dim("With -y and no remote flag, remotes are preserved (safe default).")}`,
981
+ `${pc.dim("Without -y and no remote flag, you'll be prompted per brain.")}`,
982
+ ].join("\n")),
983
+ ls: () => console.log([
984
+ `${pc.bold("csb ls")} — list all brains ${pc.dim("(alias: list)")}`,
985
+ "",
986
+ "Prints each registered brain with its path, creation date, and remote.",
987
+ "The default brain is shown in bold with a `*` marker.",
988
+ ].join("\n")),
989
+ skills: () => console.log([
990
+ `${pc.bold("csb skills")} — install or update the wiki skills for any agent`,
991
+ "",
992
+ "Usage:",
993
+ ` ${c("csb skills [--agent <ids>] [--copy] [--brain <name>]")}`,
994
+ ` ${c("csb skills --list")} list supported agents and their skills dirs`,
995
+ "",
996
+ "Global skills (brain-ingest, brain-search, brain-refresh) are written once to",
997
+ `${pc.dim("~/.agents/skills/<name>")} and symlinked into each agent's own global skills dir`,
998
+ `(e.g. ${pc.dim("~/.claude/skills")}). Codex, Cursor, Copilot, Gemini CLI, OpenCode, Amp and Cline`,
999
+ `read ${pc.dim("~/.agents/skills")} directly. Vault-local skills (lint, brain-rebuild) are copied`,
1000
+ "into the default brain's per-agent skills dir (e.g. .agents/skills).",
1001
+ "",
1002
+ "Options:",
1003
+ ` ${c("--agent, -a <ids>")} agents to install for, comma-separated, or \`all\``,
1004
+ ` ${pc.dim(`(default: claude-code + detected; env: CSB_AGENTS)`)}`,
1005
+ ` ${c("--copy")} copy instead of symlink`,
1006
+ ` ${c("--brain <name>")} brain whose vault-local skills to update (default brain otherwise)`,
1007
+ "",
1008
+ `Agents: ${pc.dim(AGENT_IDS.join(", "))}`,
1009
+ ].join("\n")),
1010
+ "git-token": () => console.log([
1011
+ `${pc.bold("csb git-token")} — renew the git token for a Cloudflare Artifacts brain`,
1012
+ "",
1013
+ "Usage:",
1014
+ ` ${c("csb git-token [<name>] [--ttl <duration>] [--read] [--print]")}`,
1015
+ "",
1016
+ "Artifacts git tokens expire (90 days by default, 1 year max). This mints a new one with",
1017
+ "your wrangler login (or CLOUDFLARE_API_TOKEN) and stores it as an http.extraHeader",
1018
+ "for the brain's remote in its .git/config, so plain `git push` / `git pull` work.",
1019
+ "",
1020
+ "Options:",
1021
+ ` ${c("--brain <name>")} brain to renew (default: the default brain; also positional)`,
1022
+ ` ${c("--ttl <duration>")} token lifetime: seconds or 12h / 90d / 1y (default 90d, max 1y)`,
1023
+ ` ${c("--read")} read-only token instead of write`,
1024
+ ` ${c("--print")} print the token instead of saving it to .git/config`,
1025
+ ].join("\n")),
1026
+ doctor: () => console.log([
1027
+ `${pc.bold("csb doctor")} — verify your setup and suggest fixes`,
1028
+ "",
1029
+ "Checks required and optional tools (gh, mise, pnpm, wrangler),",
1030
+ "the central config, each registered brain's path and qmd index, and whether",
1031
+ "the global skills in ~/.agents/skills match this release.",
1032
+ "Prints a `Fix:` hint under each failing check.",
1033
+ ].join("\n")),
1034
+ }
1035
+ const renderer = topics[topic] || topics.top
1036
+ const out = renderer()
1037
+ if (out && typeof out.then === "function") return out
442
1038
  }
443
1039
 
444
1040
  // Resolve a brain entry from config. Name defaults to the `default` field.
@@ -454,8 +1050,8 @@ async function resolveBrain(name) {
454
1050
  if (!target) {
455
1051
  const available = brains.map(b => b.name).join(", ")
456
1052
  const hint = available
457
- ? `Pass --brain <name> (available: ${available}), or edit ${CSB_CONFIG} and set \`default = "<name>"\`.`
458
- : `Run \`claude-second-brain <name>\` to create your first brain.`
1053
+ ? `Quick fix: \`csb use <name>\` (available: ${available}), or pass --brain <name>.`
1054
+ : `Run \`csb <name>\` to create your first brain.`
459
1055
  throw new Error(`No default brain set in config.toml. ${hint}`)
460
1056
  }
461
1057
  const entry = brains.find(b => b.name === target)
@@ -466,17 +1062,70 @@ async function resolveBrain(name) {
466
1062
  return entry
467
1063
  }
468
1064
 
1065
+ // Rewrites config.toml so `name` is the new default. Returns {previous, current}.
1066
+ // Strips any existing `active = …` / `default = …` line from the header first.
1067
+ async function setDefaultBrain(name) {
1068
+ let content
1069
+ try {
1070
+ content = await readFile(CSB_CONFIG, "utf8")
1071
+ } catch {
1072
+ throw new Error(`No config at ${CSB_CONFIG}. Run \`csb <name>\` to create your first brain.`)
1073
+ }
1074
+ const { defaultBrain, brains, header } = parseConfig(content)
1075
+ if (!brains.find(b => b.name === name)) {
1076
+ const available = brains.map(b => b.name).join(", ") || "(none)"
1077
+ throw new Error(`No brain named "${name}". Available: ${available}.`)
1078
+ }
1079
+ if (defaultBrain === name) {
1080
+ return { previous: name, current: name, changed: false }
1081
+ }
1082
+ const blocks = content.split(/\n(?=\[\[brains\]\])/)
1083
+ let newHeader = (blocks[0] || "")
1084
+ .replace(/^active\s*=\s*"[^"]*"\s*\n?/m, "")
1085
+ .replace(/^default\s*=\s*"[^"]*"\s*\n?/m, "")
1086
+ .replace(/^\s+|\s+$/g, "")
1087
+ newHeader = `default = "${name}"${newHeader ? "\n" + newHeader : ""}`
1088
+ const entries = blocks.slice(1).map(b => b.replace(/^\s+|\s+$/g, ""))
1089
+ const out = [newHeader, ...entries].filter(Boolean).join("\n\n").trimEnd() + "\n"
1090
+ await writeFile(CSB_CONFIG, out, "utf8")
1091
+ return { previous: defaultBrain, current: name, changed: true }
1092
+ }
1093
+
1094
+ async function cmdUse(args) {
1095
+ const name = args.find(a => !a.startsWith("-"))
1096
+ if (!name) {
1097
+ throw new Error("Usage: csb use <name>")
1098
+ }
1099
+ const { previous, current, changed } = await setDefaultBrain(name)
1100
+ if (!changed) {
1101
+ console.log(`default is already ${pc.cyan(current)}`)
1102
+ return
1103
+ }
1104
+ if (previous) {
1105
+ console.log(`default: ${pc.dim(previous)} → ${pc.cyan(current)}`)
1106
+ } else {
1107
+ console.log(`default set to ${pc.cyan(current)}`)
1108
+ }
1109
+ }
1110
+
469
1111
  async function cmdPath(args) {
470
- // Parse flags: --brain <name>, --root | --qmd | --config (default: --root)
1112
+ // Canonical: csb path [qmd|config|root] [--brain <name>]
1113
+ // Deprecated: csb path --qmd | --config | --root
471
1114
  let name = null
472
- let mode = "root"
1115
+ let mode = null
1116
+ let sawLegacyFlag = false
473
1117
  for (let i = 0; i < args.length; i++) {
474
1118
  const a = args[i]
475
1119
  if (a === "--brain") { name = args[++i]; continue }
476
- if (a === "--root") { mode = "root"; continue }
477
- if (a === "--qmd") { mode = "qmd"; continue }
478
- if (a === "--config") { mode = "config"; continue }
479
- throw new Error(`Unknown path arg: ${a}`)
1120
+ if (a === "--root") { mode = "root"; sawLegacyFlag = true; continue }
1121
+ if (a === "--qmd") { mode = "qmd"; sawLegacyFlag = true; continue }
1122
+ if (a === "--config") { mode = "config"; sawLegacyFlag = true; continue }
1123
+ if (a === "root" || a === "qmd" || a === "config") { mode = a; continue }
1124
+ throw new Error(`Unknown path arg: ${a}. Run \`csb help path\` for usage.`)
1125
+ }
1126
+ if (!mode) mode = "root"
1127
+ if (sawLegacyFlag) {
1128
+ process.stderr.write(`${pc.yellow("warning:")} \`--${mode}\` is deprecated — use \`csb path ${mode}\` instead.\n`)
480
1129
  }
481
1130
  if (mode === "config") {
482
1131
  process.stdout.write(CSB_CONFIG + "\n")
@@ -487,8 +1136,9 @@ async function cmdPath(args) {
487
1136
  process.stdout.write(out + "\n")
488
1137
  }
489
1138
 
490
- async function cmdQmd(args) {
491
- // `claude-second-brain qmd [--brain N] [--] <qmd args…>`
1139
+ // Parse [--brain <name>] [--] <rest…>. `--` is optional; use it only to pass a
1140
+ // literal `--brain` through to the inner command.
1141
+ function parseBrainAndRest(args) {
492
1142
  let name = null
493
1143
  const rest = []
494
1144
  for (let i = 0; i < args.length; i++) {
@@ -497,14 +1147,154 @@ async function cmdQmd(args) {
497
1147
  if (a === "--") { rest.push(...args.slice(i + 1)); break }
498
1148
  rest.push(a)
499
1149
  }
500
- const brain = await resolveBrain(name)
501
- const result = spawnSync("npx", ["-y", "@tobilu/qmd", ...rest], {
1150
+ return { name, rest }
1151
+ }
1152
+
1153
+ async function runInBrain(brain, cmd) {
1154
+ if (cmd.length === 0) {
1155
+ throw new Error("No command to run. Usage: csb exec [--brain <name>] -- <cmd…>")
1156
+ }
1157
+ const result = spawnSync(cmd[0], cmd.slice(1), {
1158
+ cwd: brain.path,
502
1159
  stdio: "inherit",
503
1160
  env: { ...process.env, INDEX_PATH: brain.qmd_index },
504
1161
  })
505
1162
  process.exit(result.status ?? 1)
506
1163
  }
507
1164
 
1165
+ async function cmdQmd(args) {
1166
+ const { name, rest } = parseBrainAndRest(args)
1167
+ const brain = await resolveBrain(name)
1168
+ await runInBrain(brain, ["npx", "-y", "@tobilu/qmd", ...rest])
1169
+ }
1170
+
1171
+ async function cmdExec(args) {
1172
+ const { name, rest } = parseBrainAndRest(args)
1173
+ const brain = await resolveBrain(name)
1174
+ await runInBrain(brain, rest)
1175
+ }
1176
+
1177
+ async function cmdDoctor() {
1178
+ const toDisplayPath = p => p && p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
1179
+ const ok = s => ` ${pc.green("✓")} ${s}`
1180
+ const warn = (s, fix) => ` ${pc.yellow("⚠")} ${s}${fix ? `\n ${pc.dim("Fix:")} ${fix}` : ""}`
1181
+ const fail = (s, fix) => ` ${pc.red("✗")} ${s}${fix ? `\n ${pc.dim("Fix:")} ${fix}` : ""}`
1182
+ const lines = []
1183
+ let failures = 0
1184
+ let warnings = 0
1185
+
1186
+ p.intro(`${pc.bgCyan(pc.black(" csb doctor "))} v${version}`)
1187
+
1188
+ // Tools
1189
+ lines.push(pc.bold("Tools"))
1190
+ lines.push(commandExists("gh")
1191
+ ? ok("gh (GitHub CLI) installed")
1192
+ : (warnings++, warn("gh (GitHub CLI) not installed — required for GitHub remotes", "brew install gh | https://cli.github.com")))
1193
+ if (commandExists("gh")) {
1194
+ const auth = spawnSync("gh", ["auth", "status"], { stdio: "pipe" })
1195
+ lines.push(auth.status === 0
1196
+ ? ok("gh authenticated")
1197
+ : (warnings++, warn("gh is installed but not authenticated", "gh auth login")))
1198
+ }
1199
+ lines.push(commandExists("mise")
1200
+ ? ok("mise installed")
1201
+ : systemPnpmUsable()
1202
+ ? ok("mise not installed — using system node + pnpm instead")
1203
+ : (failures++, fail("neither mise nor pnpm >= 10 installed — one is required for scaffolded vaults", "npm install -g pnpm | npm install -g @jdxcode/mise")))
1204
+ lines.push(commandExists("wrangler") || commandExists("npx")
1205
+ ? ok(commandExists("wrangler") ? "wrangler installed" : "wrangler available via npx (optional — for Cloudflare Artifacts)")
1206
+ : (warnings++, warn("wrangler not installed — required only for Cloudflare Artifacts remotes", "npm install -g wrangler")))
1207
+
1208
+ // Config
1209
+ lines.push("")
1210
+ lines.push(pc.bold("Config"))
1211
+ let parsed = null
1212
+ try {
1213
+ const content = await readFile(CSB_CONFIG, "utf8")
1214
+ parsed = parseConfig(content)
1215
+ lines.push(ok(`config readable at ${pc.dim(toDisplayPath(CSB_CONFIG))}`))
1216
+ } catch {
1217
+ failures++
1218
+ lines.push(fail(`no config at ${toDisplayPath(CSB_CONFIG)}`, "csb <name> # create your first brain"))
1219
+ }
1220
+
1221
+ if (parsed) {
1222
+ if (parsed.brains.length === 0) {
1223
+ warnings++
1224
+ lines.push(warn("no brains registered", "csb <name> # create your first brain"))
1225
+ } else {
1226
+ lines.push(ok(`${parsed.brains.length} brain${parsed.brains.length === 1 ? "" : "s"} registered`))
1227
+ if (parsed.defaultBrain) {
1228
+ const entry = parsed.brains.find(b => b.name === parsed.defaultBrain)
1229
+ if (entry) {
1230
+ lines.push(ok(`default brain: ${pc.cyan(parsed.defaultBrain)}`))
1231
+ } else {
1232
+ failures++
1233
+ lines.push(fail(`default brain "${parsed.defaultBrain}" is not registered`, `csb use <name> # pick one of: ${parsed.brains.map(b => b.name).join(", ")}`))
1234
+ }
1235
+ } else {
1236
+ warnings++
1237
+ lines.push(warn("no default brain set", `csb use <name> # pick one of: ${parsed.brains.map(b => b.name).join(", ")}`))
1238
+ }
1239
+ }
1240
+
1241
+ // Per-brain checks
1242
+ if (parsed.brains.length > 0) {
1243
+ lines.push("")
1244
+ lines.push(pc.bold("Brains"))
1245
+ for (const b of parsed.brains) {
1246
+ lines.push(pc.cyan(b.name))
1247
+ try {
1248
+ await access(b.path)
1249
+ lines.push(ok(`path exists: ${pc.dim(toDisplayPath(b.path))}`))
1250
+ } catch {
1251
+ failures++
1252
+ lines.push(fail(`path missing: ${toDisplayPath(b.path)}`, `csb rm ${b.name} # drop the dead entry, then recreate`))
1253
+ }
1254
+ try {
1255
+ await access(b.qmd_index)
1256
+ lines.push(ok(`qmd index exists: ${pc.dim(toDisplayPath(b.qmd_index))}`))
1257
+ } catch {
1258
+ warnings++
1259
+ lines.push(warn(`qmd index missing: ${toDisplayPath(b.qmd_index)}`, `csb exec --brain ${b.name} -- pnpm qmd:reindex`))
1260
+ }
1261
+ }
1262
+ }
1263
+ }
1264
+
1265
+ // Global skills
1266
+ lines.push("")
1267
+ lines.push(pc.bold("Skills"))
1268
+ for (const name of GLOBAL_SKILLS) {
1269
+ const canonical = join(CANONICAL_GLOBAL_DIR, name)
1270
+ const v = await readSkillVersion(canonical)
1271
+ if (!v) {
1272
+ const legacy = await readSkillVersion(join(homedir(), ".claude", "skills", name))
1273
+ warnings++
1274
+ lines.push(legacy
1275
+ ? warn(`${name} only in ~/.claude/skills (v${legacy}) — other agents can't see it`, "csb skills")
1276
+ : warn(`${name} not installed in ${toDisplayPath(CANONICAL_GLOBAL_DIR)}`, "csb skills"))
1277
+ } else if (v !== version) {
1278
+ warnings++
1279
+ lines.push(warn(`${name} is v${v} (this release is v${version})`, "csb skills"))
1280
+ } else {
1281
+ lines.push(ok(`${name} v${v} ${pc.dim(toDisplayPath(canonical))}`))
1282
+ }
1283
+ }
1284
+
1285
+ p.note(lines.join("\n"), "Checks")
1286
+
1287
+ if (failures > 0) {
1288
+ p.outro(`${pc.red(`${failures} failure${failures === 1 ? "" : "s"}`)}${warnings > 0 ? `, ${pc.yellow(`${warnings} warning${warnings === 1 ? "" : "s"}`)}` : ""}`)
1289
+ process.exit(1)
1290
+ }
1291
+ if (warnings > 0) {
1292
+ p.outro(`${pc.yellow(`${warnings} warning${warnings === 1 ? "" : "s"}`)}`)
1293
+ return
1294
+ }
1295
+ p.outro(pc.green("all checks passed"))
1296
+ }
1297
+
508
1298
  async function listBrains() {
509
1299
  const toDisplayPath = p => p && p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
510
1300
  let content
@@ -537,7 +1327,7 @@ async function listBrains() {
537
1327
  p.outro(defaultBrain ? `default: ${pc.cyan(defaultBrain)}` : "no default brain")
538
1328
  }
539
1329
 
540
- async function removeBrain(names, { yes = false } = {}) {
1330
+ async function removeBrain(names, { yes = false, remoteMode = "ask" } = {}) {
541
1331
  p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
542
1332
 
543
1333
  let content
@@ -592,14 +1382,27 @@ async function removeBrain(names, { yes = false } = {}) {
592
1382
  }
593
1383
  }
594
1384
 
595
- // Ask per-target whether to also delete the remote. Skip in -y mode — remote
596
- // deletion is destructive beyond the local vault and requires explicit opt-in.
1385
+ // Decide per-target whether to also delete the remote.
1386
+ // remoteMode === "keep" → never delete remotes
1387
+ // remoteMode === "delete" → always delete remotes (no prompt)
1388
+ // remoteMode === "ask" → default: prompt unless -y (then keep)
597
1389
  const remoteDecisions = new Map()
598
- if (!yes) {
1390
+ const resolvedRemoteMode =
1391
+ remoteMode === "keep" ? "keep"
1392
+ : remoteMode === "delete" ? "delete"
1393
+ : yes ? "keep" : "ask"
1394
+
1395
+ if (resolvedRemoteMode !== "keep") {
599
1396
  for (const target of targets) {
600
1397
  const gh = parseGithubRepo(target.git_remote)
601
1398
  const cf = parseCloudflareArtifact(target.git_remote)
602
1399
  if (!gh && !cf) continue
1400
+ if (resolvedRemoteMode === "delete") {
1401
+ remoteDecisions.set(target.name, gh
1402
+ ? { kind: "github", slug: gh }
1403
+ : { kind: "cloudflare", namespace: cf.namespace, repo: cf.repo })
1404
+ continue
1405
+ }
603
1406
  const label = gh ? `GitHub repo ${pc.cyan(gh)}` : `Cloudflare Artifact ${pc.cyan(`${cf.namespace}/${cf.repo}`)}`
604
1407
  const ok = await p.confirm({
605
1408
  message: `Also delete ${label} for "${target.name}"?`,
@@ -614,7 +1417,7 @@ async function removeBrain(names, { yes = false } = {}) {
614
1417
  }
615
1418
  }
616
1419
 
617
- const spin = p.spinner()
1420
+ const spin = makeSpinner()
618
1421
 
619
1422
  for (const target of targets) {
620
1423
  spin.start(`Deleting ${toDisplayPath(target.path)}`)
@@ -647,7 +1450,7 @@ async function removeBrain(names, { yes = false } = {}) {
647
1450
  spin.stop(`Removed Cloudflare Artifact ${pc.dim(`${decision.namespace}/${decision.repo}`)}`)
648
1451
  } else {
649
1452
  spin.stop(`Failed to delete Cloudflare Artifact for ${name}: ${result.error}`, 1)
650
- p.log.warn(`Delete it manually:\n ${pc.cyan(`TOKEN=$(wrangler auth token)`)}\n ${pc.cyan(`curl -X DELETE https://artifacts.cloudflare.net/v1/api/namespaces/${decision.namespace}/repos/${decision.repo} \\`)}\n ${pc.cyan(` -H "Authorization: Bearer $TOKEN"`)}`)
1453
+ p.log.warn(`Delete it manually:\n ${pc.cyan(`TOKEN=$(wrangler auth token)`)}\n ${pc.cyan(`curl -X DELETE https://api.cloudflare.com/client/v4/accounts/${decision.accountId || "<ACCOUNT_ID>"}/artifacts/namespaces/${decision.namespace}/repos/${decision.repo} \\`)}\n ${pc.cyan(` -H "Authorization: Bearer $TOKEN"`)}`)
651
1454
  }
652
1455
  }
653
1456
  }
@@ -720,7 +1523,7 @@ async function writeConfig(brainName, brainPath, qmdPath, gitRemote) {
720
1523
  await writeFile(CSB_CONFIG, [header, ...otherBrains, entry].join("\n").trimEnd() + "\n", "utf8")
721
1524
  }
722
1525
 
723
- async function createBrain(initialName) {
1526
+ async function createBrain(initialName, { agents: explicitAgents = null, copy = false } = {}) {
724
1527
  const isInteractive = Boolean(process.stdin.isTTY)
725
1528
 
726
1529
  p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
@@ -748,9 +1551,9 @@ async function createBrain(initialName) {
748
1551
  const provider = await p.select({
749
1552
  message: "Where to host the Git remote?",
750
1553
  options: [
751
- { value: "github", label: "GitHub", hint: "default" },
752
- { value: "cloudflare", label: "Cloudflare Artifacts" },
753
- { value: "none", label: "Skip — I'll add a remote later" },
1554
+ { value: "github", label: `${REMOTE_ICONS.github}GitHub`, hint: "private repo via gh · default" },
1555
+ { value: "cloudflare", label: `${REMOTE_ICONS.cloudflare}Cloudflare Artifacts`, hint: "git remote via wrangler" },
1556
+ { value: "none", label: `${REMOTE_ICONS.none}Skip — I'll add a remote later`, hint: "local git only" },
754
1557
  ],
755
1558
  initialValue: "github",
756
1559
  })
@@ -778,6 +1581,23 @@ async function createBrain(initialName) {
778
1581
  }
779
1582
  }
780
1583
 
1584
+ // Ask every question before the slow steps, so setup can run unattended.
1585
+ let doQmdSetup = true
1586
+ if (isInteractive) {
1587
+ const ok = await p.confirm({
1588
+ message: "Register qmd collections after install? (wiki + raw-sources)",
1589
+ initialValue: true,
1590
+ })
1591
+ if (p.isCancel(ok)) { p.cancel("Setup cancelled."); process.exit(0) }
1592
+ doQmdSetup = ok
1593
+ }
1594
+
1595
+ const agents = await resolveAgents({ explicit: explicitAgents, isInteractive, prompts: p })
1596
+ if (!agents) { p.cancel("Setup cancelled."); process.exit(0) }
1597
+ if (!isInteractive || explicitAgents) {
1598
+ p.log.step(`Install skills for which agents?\n${pc.dim(agents.map(id => AGENTS[id].displayName).join(", "))}`)
1599
+ }
1600
+
781
1601
  await mkdir(CSB_ROOT, { recursive: true })
782
1602
  const targetDir = join(CSB_ROOT, targetName)
783
1603
 
@@ -811,44 +1631,43 @@ async function createBrain(initialName) {
811
1631
  await patchVault(targetDir, targetName)
812
1632
  spin.stop("README patched")
813
1633
 
814
- // Install mise if not present
815
- if (!commandExists("mise")) {
816
- spin.start("Installing mise")
817
- const ok = run(["npm", "install", "-g", "@jdxcode/mise"])
818
- if (ok) spin.stop("mise installed")
819
- else spin.stop("Failed to install mise — run: npm install -g @jdxcode/mise", 1)
820
- }
1634
+ // Toolchain: reuse a system pnpm (>= 10) when there is one; otherwise let
1635
+ // mise install node + pnpm from the vault's mise.toml.
1636
+ const useSystemPnpm = process.env.CSB_USE_MISE !== "1" && systemPnpmUsable()
1637
+ const pnpmCmd = useSystemPnpm ? ["pnpm"] : ["mise", "exec", "--", "pnpm"]
1638
+ const fmt = secs => pc.dim(`(${secs}s)`)
821
1639
 
822
- // Run mise install inside the new vault to install node + pnpm
823
- spin.start("Installing node + pnpm via mise")
824
- run(["mise", "trust"], targetDir)
825
- const miseOk = run(["mise", "install"], targetDir)
826
- if (miseOk) spin.stop("node + pnpm installed")
827
- else spin.stop("mise install failed — run it manually inside your vault", 1)
1640
+ if (useSystemPnpm) {
1641
+ p.log.step(`Using system node ${process.versions.node} + pnpm ${pc.dim("(set CSB_USE_MISE=1 to use mise instead)")}`)
1642
+ } else {
1643
+ if (!commandExists("mise")) {
1644
+ const r = await runStep(spin, "Installing mise", ["npm", "install", "-g", "@jdxcode/mise"])
1645
+ if (r.ok) spin.stop(`mise installed ${fmt(r.seconds)}`)
1646
+ else spin.stop("Failed to install mise — run: npm install -g @jdxcode/mise", 1)
1647
+ }
1648
+ run(["mise", "trust"], targetDir)
1649
+ const r = await runStep(spin, "Installing node + pnpm via mise", ["mise", "install"], targetDir)
1650
+ if (r.ok) spin.stop(`node + pnpm installed ${fmt(r.seconds)}`)
1651
+ else spin.stop("mise install failed — run it manually inside your vault", 1)
1652
+ }
828
1653
 
829
1654
  // Install vault dependencies via pnpm
830
- spin.start("Installing vault dependencies")
831
- const pnpmOk = run(["mise", "exec", "--", "pnpm", "install"], targetDir)
832
- if (pnpmOk) spin.stop("dependencies installed")
833
- else spin.stop("pnpm install failed — run it manually inside your vault", 1)
1655
+ const install = await runStep(spin, "Installing vault dependencies", [...pnpmCmd, "install", "--prefer-offline"], targetDir)
1656
+ const pnpmOk = install.ok
1657
+ if (pnpmOk) spin.stop(`dependencies installed ${fmt(install.seconds)}`)
1658
+ else {
1659
+ spin.stop("pnpm install failed — run it manually inside your vault", 1)
1660
+ const tail = tailForError(install)
1661
+ if (tail) p.log.warn(`pnpm install output:\n${tail}`)
1662
+ }
834
1663
 
835
1664
  // Register qmd collections + contexts. Skip reindex — first reindex downloads
836
1665
  // ~2GB of GGUF models; user runs it explicitly when ready.
837
1666
  if (pnpmOk) {
838
- let doQmdSetup = true
839
- if (isInteractive) {
840
- const ok = await p.confirm({
841
- message: "Register qmd collections now? (wiki + raw-sources)",
842
- initialValue: true,
843
- })
844
- if (p.isCancel(ok)) { p.cancel("Setup cancelled."); process.exit(0) }
845
- doQmdSetup = ok
846
- }
847
1667
  if (doQmdSetup) {
848
- spin.start("Registering qmd collections (wiki, raw-sources)")
849
- const qmdRes = runCapture(["mise", "exec", "--", "pnpm", "qmd:setup"], targetDir)
1668
+ const qmdRes = await runStep(spin, "Registering qmd collections (wiki, raw-sources)", [...pnpmCmd, "qmd:setup"], targetDir)
850
1669
  if (qmdRes.ok) {
851
- spin.stop("qmd collections registered")
1670
+ spin.stop(`qmd collections registered ${fmt(qmdRes.seconds)}`)
852
1671
  } else {
853
1672
  spin.stop("pnpm qmd:setup failed — run it manually inside your vault", 1)
854
1673
  const tail = tailForError(qmdRes)
@@ -859,16 +1678,17 @@ async function createBrain(initialName) {
859
1678
  }
860
1679
  }
861
1680
 
1681
+ // Vault-local skills for agents that don't read .claude/skills
1682
+ const projectDirs = await installProjectSkills(targetDir, join(targetDir, ".claude", "skills"), LOCAL_SKILLS, agents)
1683
+ if (projectDirs.length > 0) {
1684
+ p.log.step(`Vault skills copied to ${projectDirs.map(d => pc.dim(d)).join(", ")}`)
1685
+ }
1686
+
862
1687
  // Install global skills (version-aware — prompts to update when versions differ)
863
- spin.start("Installing global Claude skills")
864
- const skillResult = await installGlobalSkills({ isInteractive })
865
- const installedCount = skillResult.installed.length
866
- const skippedCount = skillResult.skipped.length
867
- const summary = [
868
- installedCount > 0 ? `installed ${installedCount}` : null,
869
- skippedCount > 0 ? `kept ${skippedCount}` : null,
870
- ].filter(Boolean).join(", ") || "already up to date"
871
- spin.stop(`Global skills ${summary} → ${pc.dim(toDisplayPath(join(homedir(), ".claude", "skills")))}`)
1688
+ spin.start("Installing global skills")
1689
+ const skillResult = await installGlobalSkills({ isInteractive, agents, copy })
1690
+ spin.stop(`Global skills ${globalSkillSummary(skillResult)}`)
1691
+ p.log.message(summarizeAgentInstall(agents, skillResult.links, toDisplayPath))
872
1692
 
873
1693
  // Git init
874
1694
  spin.start("Initializing git repo")
@@ -881,10 +1701,15 @@ async function createBrain(initialName) {
881
1701
  spin.stop("git init failed — run it manually inside your vault", 1)
882
1702
  }
883
1703
 
1704
+ // Remote setup outcome, surfaced in Next steps / outro instead of a silent
1705
+ // success-looking finish. null = no remote requested.
1706
+ let remoteProblem = null
1707
+
884
1708
  // GitHub repo (optional)
885
1709
  if (remoteProvider === "github") {
886
1710
  if (!commandExists("gh")) {
887
1711
  p.log.warn(`gh CLI not found — install from https://cli.github.com, then run:\n gh repo create ${repoName} --private --source=. --remote=origin --push`)
1712
+ remoteProblem = "GitHub repo not created (gh CLI not found)"
888
1713
  } else {
889
1714
  const authCheck = spawnSync("gh", ["auth", "status"], { stdio: "pipe" })
890
1715
  let loggedIn = authCheck.status === 0
@@ -904,7 +1729,10 @@ async function createBrain(initialName) {
904
1729
  spin.stop(`GitHub repo created (private): ${pc.cyan(repoName)}`)
905
1730
  } else {
906
1731
  spin.stop(`gh repo create failed — run: gh repo create ${repoName} --private --source=. --remote=origin --push`, 1)
1732
+ remoteProblem = "GitHub repo not created (gh repo create failed)"
907
1733
  }
1734
+ } else {
1735
+ remoteProblem = "GitHub repo not created (not logged in to gh)"
908
1736
  }
909
1737
  }
910
1738
  }
@@ -916,12 +1744,24 @@ async function createBrain(initialName) {
916
1744
  return r.status === 0 ? r.stdout.toString().trim() : ""
917
1745
  })()
918
1746
  : ""
1747
+ let cfAccountId = null
919
1748
  if (remoteProvider === "cloudflare") {
920
1749
  const result = await setupCloudflareRemote({ targetDir, repoName, namespace: cfNamespace, spin })
921
- if (result?.repoToken) {
922
- p.log.warn(`Save your Artifacts repo token — it expires and you'll need to mint a new one:\n ${result.repoToken}`)
923
- }
924
1750
  gitRemote = result?.remote || ""
1751
+ cfAccountId = result?.accountId || null
1752
+ if (result?.remote && result?.repoToken) {
1753
+ // The create response carries a 24h token; swap it for a long-lived one.
1754
+ setGitAuthHeader(targetDir, result.remote, result.repoToken)
1755
+ const long = await mintArtifactsGitToken({ remote: result.remote, cwd: targetDir, interactive: false })
1756
+ if (long.ok) {
1757
+ const until = long.expiresAt ? ` (until ${new Date(long.expiresAt).toLocaleDateString()})` : ""
1758
+ p.log.info(`Git token saved to the vault's .git/config — push/pull work for ${formatTtl(GIT_TOKEN_TTL_DEFAULT)}${until}; renew with ${pc.cyan("csb git-token")}`)
1759
+ } else {
1760
+ p.log.warn(`Could not mint a ${formatTtl(GIT_TOKEN_TTL_DEFAULT)} git token (${long.error}); using the 24h one. Run ${pc.cyan("csb git-token")} to get a longer one.`)
1761
+ }
1762
+ }
1763
+ if (!result) remoteProblem = "Cloudflare Artifact not created (see the error above)"
1764
+ else if (!result.pushed) remoteProblem = "Cloudflare Artifact created, but the initial push failed (see the error above)"
925
1765
  }
926
1766
 
927
1767
  // Write central config
@@ -931,14 +1771,20 @@ async function createBrain(initialName) {
931
1771
 
932
1772
  // Next steps
933
1773
  const brainDisplayPath = toDisplayPath(targetDir)
934
- const remoteSteps = remoteProvider === "cloudflare"
1774
+ const remoteSteps = remoteProblem
1775
+ ? [
1776
+ `${pc.yellow("⚠")} ${pc.yellow(remoteProblem)}`,
1777
+ ...(remoteProvider === "github"
1778
+ ? [`${pc.cyan(`gh repo create ${repoName} --private --source=. --remote=origin --push`)} retry`]
1779
+ : [
1780
+ `${pc.dim("# fix the error above, then delete this brain and re-run, or add any git remote:")}`,
1781
+ `${pc.cyan(`csb rm ${targetName} && csb ${targetName}`)}`,
1782
+ ]),
1783
+ `${pc.cyan("git remote add origin <url> && git push -u origin main")} any other remote`,
1784
+ ]
1785
+ : remoteProvider === "cloudflare"
935
1786
  ? [
936
- `${pc.dim("# Mint a fresh git push/pull token when the current one expires:")}`,
937
- `${pc.cyan(`TOKEN=$(wrangler auth token)`)}`,
938
- `${pc.cyan(`curl -X POST https://artifacts.cloudflare.net/v1/api/namespaces/${cfNamespace}/tokens \\`)}`,
939
- `${pc.cyan(` -H "Authorization: Bearer $TOKEN" \\`)}`,
940
- `${pc.cyan(` -H "Content-Type: application/json" \\`)}`,
941
- `${pc.cyan(` -d '{"repo":"${repoName}","scope":"write","ttl":86400}'`)}`,
1787
+ `${pc.cyan(`csb git-token${targetName ? ` ${targetName}` : ""}`)} ${pc.dim("# renew the git push/pull token (expires in 90 days)")}`,
942
1788
  ]
943
1789
  : remoteProvider === "none"
944
1790
  ? [
@@ -950,21 +1796,49 @@ async function createBrain(initialName) {
950
1796
  const nextSteps = [
951
1797
  `${pc.cyan(`cd ${brainDisplayPath}`)}`,
952
1798
  `${pc.cyan("pnpm qmd:reindex")} ${pc.dim("# first run downloads ~2GB of embedding models")}`,
953
- `${pc.cyan("claude")} open Claude Code and start ingesting sources`,
1799
+ ...agentLaunchSteps(agents),
954
1800
  ...remoteSteps,
955
1801
  ].join("\n")
956
1802
 
957
1803
  p.note(nextSteps, "Next steps")
958
- p.outro("Happy knowledge building!")
1804
+ if (remoteProblem) {
1805
+ p.outro(pc.yellow(`Brain created, but the git remote isn't set up: ${remoteProblem}.`))
1806
+ process.exitCode = 1
1807
+ } else {
1808
+ p.outro("Happy knowledge building!")
1809
+ }
959
1810
  }
960
1811
 
1812
+ const SUBCOMMANDS = new Set([
1813
+ "help", "--help", "-h",
1814
+ "ls", "list",
1815
+ "rm", "remove",
1816
+ "path",
1817
+ "qmd",
1818
+ "exec",
1819
+ "use", "default", "switch",
1820
+ "doctor",
1821
+ "skills",
1822
+ "git-token",
1823
+ ])
1824
+
961
1825
  async function main() {
962
1826
  const [, , cmd, ...rest] = process.argv
963
1827
 
964
1828
  if (cmd === "help" || cmd === "--help" || cmd === "-h") {
965
- printHelp()
1829
+ // `csb help <topic>` or `csb help`
1830
+ const topic = rest[0]
1831
+ await printHelp(topic || "top")
966
1832
  return
967
1833
  }
1834
+
1835
+ // Per-subcommand --help / -h — intercept before any prompts run.
1836
+ if (SUBCOMMANDS.has(cmd) && hasHelpFlag(rest)) {
1837
+ const topicMap = { list: "ls", remove: "rm", default: "use", switch: "use" }
1838
+ await printHelp(topicMap[cmd] || cmd)
1839
+ return
1840
+ }
1841
+
968
1842
  if (cmd === "ls" || cmd === "list") {
969
1843
  await listBrains()
970
1844
  return
@@ -972,7 +1846,13 @@ async function main() {
972
1846
  if (cmd === "rm" || cmd === "remove") {
973
1847
  const names = rest.filter(a => !a.startsWith("-"))
974
1848
  const yes = rest.some(a => a === "-y" || a === "--yes")
975
- await removeBrain(names, { yes })
1849
+ const deleteRemote = rest.some(a => a === "--delete-remote")
1850
+ const keepRemote = rest.some(a => a === "--keep-remote")
1851
+ if (deleteRemote && keepRemote) {
1852
+ throw new Error("Cannot use --delete-remote and --keep-remote together.")
1853
+ }
1854
+ const remoteMode = deleteRemote ? "delete" : keepRemote ? "keep" : "ask"
1855
+ await removeBrain(names, { yes, remoteMode })
976
1856
  return
977
1857
  }
978
1858
  if (cmd === "path") {
@@ -983,7 +1863,32 @@ async function main() {
983
1863
  await cmdQmd(rest)
984
1864
  return
985
1865
  }
986
- await createBrain(cmd)
1866
+ if (cmd === "exec") {
1867
+ await cmdExec(rest)
1868
+ return
1869
+ }
1870
+ if (cmd === "use" || cmd === "default" || cmd === "switch") {
1871
+ await cmdUse(rest)
1872
+ return
1873
+ }
1874
+ if (cmd === "git-token") {
1875
+ await cmdGitToken(rest)
1876
+ return
1877
+ }
1878
+ if (cmd === "doctor") {
1879
+ await cmdDoctor()
1880
+ return
1881
+ }
1882
+ if (cmd === "skills") {
1883
+ await cmdSkills(rest)
1884
+ return
1885
+ }
1886
+ // `csb [<name>] [--agent <ids>] [--copy]`
1887
+ const createArgs = cmd === undefined ? rest : [cmd, ...rest]
1888
+ const { agents, copy, rest: positional } = parseAgentFlags(createArgs)
1889
+ const unknownFlag = positional.find(a => a.startsWith("-"))
1890
+ if (unknownFlag) throw new Error(`Unknown option: ${unknownFlag}. Run \`csb help\`.`)
1891
+ await createBrain(positional[0], { agents, copy })
987
1892
  }
988
1893
 
989
1894
  main().catch(err => {