Fastest way to scaffold your LLM powered personal knowledge base - Obsidian, Claude Code, qmd, Github
JavaScript aiampclaude-codecodexcursorgithubknowledge-baseknowledge-graphknowledge-managementllmobsidianobsidian-vaultqmdsecond-brain
feat(cli): add Cloudflare Artifacts as alternate Git remote
Claudec6ee181532f8
diff --git a/bin/create.js b/bin/create.jsindex c146cb9..2198b0c 100644--- a/bin/create.js+++ b/bin/create.js@@ -65,6 +65,136 @@ async function patchVault(targetDir, qmdPath, brainName) {}}+// Resolve the `cf` CLI as either an installed binary or `npx cf` fallback.+function resolveCfCli() {+ if (commandExists("cf")) return { cmd: "cf", prefix: [] }+ return { cmd: "npx", prefix: ["cf"] }+}++// Look up the Artifacts permission group ID via the cf CLI.+// Filters by name "Artifacts" and picks the Edit/Write scoped group.+function lookupArtifactsEditPermissionGroup(cfCli) {+ const result = spawnSync(+ cfCli.cmd,+ [...cfCli.prefix, "accounts", "tokens", "permission-groups-list", "--name", "Artifacts", "--ndjson"],+ { stdio: "pipe" }+ )+ if (result.status !== 0) return null+ const lines = result.stdout.toString().trim().split("\n").filter(Boolean)+ for (const line of lines) {+ try {+ const group = JSON.parse(line)+ const name = (group.name || "").toLowerCase()+ if (name.includes("write") || name.includes("edit")) return group.id+ } catch {+ // skip malformed lines+ }+ }+ return null+}++// End-to-end Cloudflare Artifacts setup: auth, mint API token, create repo, set remote, push.+async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {+ let cfApiToken = process.env.CLOUDFLARE_API_TOKEN+ let tokenWasMinted = false++ if (!cfApiToken) {+ const cfCli = resolveCfCli()++ const authCheck = spawnSync(cfCli.cmd, [...cfCli.prefix, "auth", "whoami"], { stdio: "pipe" })+ let loggedIn = authCheck.status === 0++ if (!loggedIn) {+ p.log.info("Not logged in to Cloudflare. Starting OAuth login...")+ loggedIn = spawnSync(cfCli.cmd, [...cfCli.prefix, "auth", "login"], { stdio: "inherit" }).status === 0+ }++ if (!loggedIn) {+ p.log.warn("Cloudflare login failed — set CLOUDFLARE_API_TOKEN and re-run, or run `cf auth login` manually.")+ return null+ }++ spin.start("Looking up Artifacts permission group")+ const permissionGroupId = lookupArtifactsEditPermissionGroup(cfCli)+ if (!permissionGroupId) {+ spin.stop("Could not find Artifacts permission group", 1)+ return null+ }+ spin.stop(`Permission group: ${pc.dim(permissionGroupId)}`)++ spin.start("Minting scoped Cloudflare API token")+ const tokenName = `claude-second-brain-${repoName}`+ const tokenBody = JSON.stringify({+ name: tokenName,+ policies: [{+ effect: "allow",+ resources: { "com.cloudflare.api.account.*": "*" },+ permission_groups: [{ id: permissionGroupId }],+ }],+ })+ const mintResult = spawnSync(+ cfCli.cmd,+ [...cfCli.prefix, "accounts", "tokens", "create", "--name", tokenName, "--body", tokenBody, "--ndjson"],+ { stdio: "pipe" }+ )+ if (mintResult.status !== 0) {+ spin.stop(`Failed to mint API token: ${mintResult.stderr.toString().trim() || "unknown error"}`, 1)+ return null+ }+ try {+ const parsed = JSON.parse(mintResult.stdout.toString().trim().split("\n")[0])+ cfApiToken = parsed.value || parsed.result?.value+ } catch (err) {+ spin.stop(`Failed to parse token response: ${err.message}`, 1)+ return null+ }+ if (!cfApiToken) {+ spin.stop("Mint succeeded but token value missing from response", 1)+ return null+ }+ tokenWasMinted = true+ spin.stop("Scoped API token minted")+ }++ spin.start(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)+ let createData+ try {+ const baseUrl = `https://artifacts.cloudflare.net/v1/api/namespaces/${namespace}`+ const res = await fetch(`${baseUrl}/repos`, {+ method: "POST",+ headers: {+ "Authorization": `Bearer ${cfApiToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ name: repoName, default_branch: "main" }),+ })+ createData = await res.json()+ } catch (err) {+ spin.stop(`Network error creating artifact: ${err.message}`, 1)+ return { cfApiToken, tokenWasMinted }+ }++ if (!createData?.success) {+ const errMsg = createData?.errors?.[0]?.message || "unknown error"+ spin.stop(`Failed to create artifact: ${errMsg}`, 1)+ return { cfApiToken, tokenWasMinted }+ }++ const { remote, token: repoToken } = createData.result+ run(["git", "remote", "add", "origin", remote], targetDir)+ const pushOk = run(+ ["git", "-c", `http.extraHeader=Authorization: Bearer ${repoToken}`, "push", "-u", "origin", "main"],+ targetDir+ )+ if (pushOk) {+ spin.stop(`Cloudflare Artifact created: ${pc.cyan(repoName)}`)+ p.log.info(`Remote: ${pc.dim(remote)}`)+ } else {+ spin.stop("Push to Cloudflare Artifact failed", 1)+ }+ return { cfApiToken, tokenWasMinted, repoToken, remote }+}+async function installGlobalSkills(qmdPath) {const globalSkillsDir = join(homedir(), ".claude", "skills")@@ -113,24 +243,40 @@ async function main() {qmdPath = defaultQmdPath}- let createGhRepo = false- let ghRepoName = null+ let remoteProvider = "none"+ let repoName = null+ let cfNamespace = "default"if (isInteractive) {- const confirm = await p.confirm({- message: "Create a private GitHub repo?",- initialValue: false,+ const provider = await p.select({+ message: "Where to host the Git remote?",+ options: [+ { value: "github", label: "GitHub", hint: "default" },+ { value: "cloudflare", label: "Cloudflare Artifacts" },+ { value: "none", label: "Skip — I'll add a remote later" },+ ],+ initialValue: "github",})- if (p.isCancel(confirm)) { p.cancel("Setup cancelled."); process.exit(0) }- createGhRepo = confirm+ if (p.isCancel(provider)) { p.cancel("Setup cancelled."); process.exit(0) }+ remoteProvider = provider- if (createGhRepo) {+ if (remoteProvider !== "none") {const answer = await p.text({- message: "GitHub repo name?",+ message: "Repo name?",placeholder: targetName,defaultValue: targetName,})if (p.isCancel(answer)) { p.cancel("Setup cancelled."); process.exit(0) }- ghRepoName = answer+ repoName = answer+ }++ if (remoteProvider === "cloudflare") {+ const ns = await p.text({+ message: "Artifacts namespace?",+ placeholder: "default",+ defaultValue: "default",+ })+ if (p.isCancel(ns)) { p.cancel("Setup cancelled."); process.exit(0) }+ cfNamespace = ns}}@@ -198,9 +344,9 @@ async function main() {}// GitHub repo (optional)- if (createGhRepo) {+ if (remoteProvider === "github") {if (!commandExists("gh")) {- p.log.warn(`gh CLI not found — install from https://cli.github.com, then run:\n gh repo create ${ghRepoName} --private --source=. --remote=origin --push`)+ 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`)} else {const authCheck = spawnSync("gh", ["auth", "status"], { stdio: "pipe" })let loggedIn = authCheck.status === 0@@ -211,33 +357,56 @@ async function main() {}if (loggedIn) {- spin.start(`Creating GitHub repo ${pc.dim(ghRepoName)}`)+ spin.start(`Creating GitHub repo ${pc.dim(repoName)}`)const ghOk = run(- ["gh", "repo", "create", ghRepoName, "--private", "--source=.", "--remote=origin", "--push"],+ ["gh", "repo", "create", repoName, "--private", "--source=.", "--remote=origin", "--push"],targetDir)if (ghOk) {- spin.stop(`GitHub repo created (private): ${pc.cyan(ghRepoName)}`)+ spin.stop(`GitHub repo created (private): ${pc.cyan(repoName)}`)} else {- spin.stop(`gh repo create failed — run: gh repo create ${ghRepoName} --private --source=. --remote=origin --push`, 1)+ spin.stop(`gh repo create failed — run: gh repo create ${repoName} --private --source=. --remote=origin --push`, 1)}}}}+ // Cloudflare Artifacts repo (optional)+ if (remoteProvider === "cloudflare") {+ const result = await setupCloudflareRemote({ targetDir, repoName, namespace: cfNamespace, spin })+ if (result?.repoToken) {+ p.log.warn(`Save your Artifacts repo token (used for git push/pull):\n ${result.repoToken}`)+ }+ if (result?.cfApiToken && result.tokenWasMinted) {+ p.log.warn(`Save your scoped Cloudflare API token (used to mint future repo tokens):\n ${result.cfApiToken}`)+ }+ }+// Install global skillsspin.start("Installing global Claude skills")await installGlobalSkills(qmdPath)spin.stop("Global skills installed")// Next steps+ const remoteSteps = remoteProvider === "cloudflare"+ ? [+ `${pc.dim("# Mint a fresh git push/pull token when needed:")}`,+ `${pc.cyan(`curl -X POST https://artifacts.cloudflare.net/v1/api/namespaces/${cfNamespace}/tokens \\`)}`,+ `${pc.cyan(` -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \\`)}`,+ `${pc.cyan(` -H "Content-Type: application/json" \\`)}`,+ `${pc.cyan(` -d '{"repo":"${repoName}","scope":"write","ttl":86400}'`)}`,+ ]+ : remoteProvider === "none"+ ? [+ `${pc.cyan("git remote add origin <url>")} connect to a remote for sync`,+ `${pc.cyan("git push -u origin main")}`,+ ]+ : []+const nextSteps = [`${pc.cyan(`cd ${targetName}`)}`,`${pc.cyan("claude")} open Claude Code, then run ${pc.bold("/setup")}`,- ...(!createGhRepo ? [- `${pc.cyan("git remote add origin <url>")} connect to GitHub for sync`,- `${pc.cyan("git push -u origin main")}`,- ] : []),+ ...remoteSteps,].join("\n")p.note(nextSteps, "Next steps")