clawnify 0.7.0 → 0.8.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/commands/login.ts","../src/commands/deploy.ts","../src/lib/sync-schema.ts","../src/commands/ls.ts","../src/commands/logs.ts","../src/commands/rm.ts","../src/commands/open.ts","../src/commands/whoami.ts","../src/commands/init.ts","../src/lib/skills/detect.ts","../src/lib/skills/content.gen.ts","../src/lib/skills/install.ts","../src/lib/ai-files/rules.ts","../src/lib/ai-files/mcp.ts","../src/commands/ai-files.ts","../src/commands/dev.ts","../src/commands/link.ts","../src/commands/pull.ts","../src/commands/org.ts","../src/commands/workspace.ts","../src/commands/execute.ts","../src/lib/mcp-client.ts","../src/commands/docs.ts","../src/commands/mcp-bridge.ts","../src/commands/sdk.ts","../src/commands/skills.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { deployCommand } from \"./commands/deploy.js\";\nimport { lsCommand } from \"./commands/ls.js\";\nimport { logsCommand } from \"./commands/logs.js\";\nimport { rmCommand } from \"./commands/rm.js\";\nimport { openCommand } from \"./commands/open.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { devCommand } from \"./commands/dev.js\";\nimport { linkCommand } from \"./commands/link.js\";\nimport { pullSchemaCommand } from \"./commands/pull.js\";\nimport { orgListCommand, orgUseCommand } from \"./commands/org.js\";\nimport { workspaceInitCommand } from \"./commands/workspace.js\";\nimport { executeCommand } from \"./commands/execute.js\";\nimport { docsCommand } from \"./commands/docs.js\";\nimport { mcpBridgeCommand } from \"./commands/mcp-bridge.js\";\nimport { sdkInspectCommand, sdkLoginCommand, sdkInstallCommand } from \"./commands/sdk.js\";\nimport {\n skillsAddCommand,\n skillsListCommand,\n skillsRemoveCommand,\n} from \"./commands/skills.js\";\nimport {\n aiFilesInstallCommand,\n aiFilesUninstallCommand,\n} from \"./commands/ai-files.js\";\n\nexport async function runCli() {\n const program = new Command();\n\n program\n .name(\"clawnify\")\n .description(\"Deploy apps to Clawnify\")\n .version(\"0.1.0\");\n\n program\n .command(\"init [dir]\")\n .description(\"Scaffold a new Clawnify project (app or website)\")\n .option(\"--type <type>\", \"Project type: app or website (skips prompt)\")\n .option(\"--name <name>\", \"Project name (skips prompt)\")\n .option(\"--template <template>\", \"App template: blank or crud (apps only)\")\n .option(\"--storage\", \"Enable file uploads (R2) — apps only\")\n .option(\"-y, --yes\", \"Non-interactive: use all defaults (app, blank, no storage)\")\n .option(\"--no-ai-files\", \"Skip installing AI files (rules + skills + MCP) after scaffolding\")\n .action(initCommand);\n\n program\n .command(\"dev [dir]\")\n .description(\"Start local dev server\")\n .option(\"--port <port>\", \"API server port (default: 8787)\")\n .action(devCommand);\n\n program\n .command(\"login\")\n .description(\"Authenticate with Clawnify\")\n .action(loginCommand);\n\n program\n .command(\"deploy [dir]\")\n .description(\"Deploy an app or website to Clawnify\")\n .option(\"--from <repo>\", \"Deploy from a GitHub repo (owner/repo)\")\n .option(\"--path <subdir>\", \"Subdirectory within the --from repo that holds the app (monorepo)\")\n .option(\"--name <name>\", \"Override app name\")\n .option(\"--org <slug-or-id>\", \"Deploy to a specific org (overrides active org)\")\n .option(\"-y, --yes\", \"Non-interactive: on slug conflict, update existing app\")\n .option(\"--update-existing\", \"Non-interactive: on slug conflict, overwrite existing app\")\n .option(\"--create-new\", \"Non-interactive: on slug conflict, create a new app with the suggested slug\")\n .option(\"--dry-run\", \"List files that would be uploaded; do not deploy\")\n .option(\"--no-sync\", \"Skip the post-deploy schema.sql sync into the local working directory\")\n .action(deployCommand);\n\n program\n .command(\"link <app-id-or-slug>\")\n .description(\"Link the current directory to an existing Clawnify app (accepts id or slug)\")\n .option(\"--dir <dir>\", \"Directory to link (default: cwd)\")\n .option(\"--org <slug-or-id>\", \"Restrict the app lookup to a specific org\")\n .action(linkCommand);\n\n // `clawnify pull` — sync deployed-app artifacts back into the local\n // working directory. Currently only `schema` is supported; future\n // subcommands (migrations, manifest, etc.) can slot in here.\n const pull = program\n .command(\"pull\")\n .description(\"Pull artifacts from a deployed app into the current directory\");\n\n pull\n .command(\"schema\")\n .description(\"Fetch the deployed app's current schema.sql snapshot into the local repo\")\n .option(\"--from <app-id-or-slug>\", \"App to fetch from (required)\")\n .option(\"--out <path>\", \"Where to write (default: ./schema.sql)\")\n .option(\"--force\", \"Overwrite a locally-modified or uncommitted schema.sql\")\n .option(\"--org <slug-or-id>\", \"Restrict the app lookup to a specific org\")\n .action(pullSchemaCommand);\n\n const org = program.command(\"org\").description(\"Manage organizations\");\n org.command(\"list\").description(\"List orgs you belong to\").action(orgListCommand);\n org\n .command(\"use <slug-or-id>\")\n .description(\"Set the active org for global commands (ls, whoami, etc.)\")\n .action(orgUseCommand);\n\n // `clawnify workspace` — a monorepo hosting one org's apps. Apps scaffolded\n // inside it land under apps/ and inherit the org on deploy.\n const workspace = program\n .command(\"workspace\")\n .description(\"Manage a monorepo that hosts an org's apps\");\n workspace\n .command(\"init [dir]\")\n .description(\"Scaffold a workspace monorepo bound to an org\")\n .option(\"--org <slug-or-id>\", \"Org to bind the workspace to (defaults to active org)\")\n .option(\"--name <name>\", \"Workspace display name (defaults to the org name)\")\n .action(workspaceInitCommand);\n\n program\n .command(\"ls\")\n .description(\"List deployed apps\")\n .action(lsCommand);\n\n program\n .command(\"logs <app-id>\")\n .description(\"Show build logs for an app\")\n .action(logsCommand);\n\n program\n .command(\"rm <app-id>\")\n .description(\"Delete an app\")\n .action(rmCommand);\n\n program\n .command(\"open <slug>\")\n .description(\"Open an app in the browser\")\n .action(openCommand);\n\n program\n .command(\"whoami\")\n .description(\"Show current user info\")\n .action(whoamiCommand);\n\n program\n .command(\"execute [file]\")\n .description(\"Run TypeScript code on the active org's substrate via mcp.clawnify.com\")\n .option(\"-c, --code <inline>\", \"Inline code instead of a file path\")\n .option(\"--timeout <seconds>\", \"Execution timeout in seconds (default 30)\")\n .action(executeCommand);\n\n program\n .command(\"docs [slug]\")\n .description(\"Fetch the skill-convention README for an app (or org index if slug omitted)\")\n .option(\"--caller <hint>\", \"Caller density hint: internal | dashboard | external\", \"external\")\n .action(docsCommand);\n\n program\n .command(\"mcp\")\n .description(\"Run a stdio MCP bridge that proxies to mcp.clawnify.com (for Claude Desktop / ChatGPT / bash-less clients)\")\n .action(mcpBridgeCommand);\n\n // `clawnify skills` — install Clawnify-curated skills (build-a-clawnify-app, ...)\n // into whichever coding agents have rules dirs in cwd (.claude, .cursor,\n // .openclaw, .codex, Aider CONVENTIONS.md). Skill contents are bundled in\n // the CLI; upgrade by bumping the CLI and re-running.\n const skills = program.command(\"skills\").description(\"Install Clawnify-curated skills into your coding agent(s)\");\n skills.command(\"list\").description(\"List available skills\").action(skillsListCommand);\n skills\n .command(\"add [name]\")\n .description(\"Install a skill into every detected agent (Claude, Cursor, OpenClaw, Codex, Aider)\")\n .option(\"--all\", \"Install every available skill\")\n .option(\"--agent <agent>\", \"Force a specific target (claude | cursor | openclaw | codex | aider)\")\n .action((name, opts) => skillsAddCommand(name, opts));\n skills\n .command(\"remove [name]\")\n .description(\"Remove a previously-installed skill from detected agents\")\n .option(\"--all\", \"Remove every installed skill\")\n .option(\"--agent <agent>\", \"Restrict to a specific agent\")\n .action((name, opts) => skillsRemoveCommand(name, opts));\n\n // `clawnify ai-files` — one step to make a project agent-ready: writes\n // the always-on Clawnify rules block into each detected agent's rules\n // file, installs the bundled skills, and wires the MCP server into\n // .mcp.json. Mirrors `npx convex ai-files install`.\n const aiFiles = program\n .command(\"ai-files\")\n .description(\"Install Clawnify rules + skills + MCP into your coding agent(s)\");\n aiFiles\n .command(\"install\")\n .description(\"Write rules, install skills, and wire the MCP server (defaults to Claude if no agent is detected)\")\n .option(\"--agent <agent>\", \"Force a specific target (claude | cursor | openclaw | codex | aider)\")\n .option(\"--no-mcp\", \"Skip writing .mcp.json\")\n .action((opts) => aiFilesInstallCommand(opts));\n aiFiles\n .command(\"uninstall\")\n .description(\"Remove the Clawnify rules block, skills, and MCP server entry\")\n .option(\"--agent <agent>\", \"Restrict to a specific agent\")\n .action((opts) => aiFilesUninstallCommand(opts));\n\n const sdk = program.command(\"sdk\").description(\"Inspect and manage the per-org SDK surface\");\n sdk\n .command(\"inspect <slug>\")\n .description(\"Show the typed-procedure README for an app (external density)\")\n .option(\"--caller <hint>\", \"Caller density hint: internal | dashboard | external\", \"external\")\n .action(sdkInspectCommand);\n sdk\n .command(\"login\")\n .description(\"Authenticate / rotate the OAuth grant (alias of `clawnify login`)\")\n .action(sdkLoginCommand);\n sdk\n .command(\"install\")\n .description(\"(Deferred) Install @clawnify/sdk locally — pending Phase 5b\")\n .action(sdkInstallCommand);\n\n try {\n await program.parseAsync();\n } catch (err) {\n console.error((err as Error)?.message ?? err);\n process.exitCode = 1;\n }\n\n // Force a prompt exit once a one-shot command finishes. Node's global\n // `fetch` (undici) keeps HTTP connections alive in a pool, which holds the\n // event loop open for several seconds after the command is actually done —\n // that's the \"deploy printed ✓ but the prompt doesn't come back\" hang.\n // Long-running commands (`dev`, `mcp`) never resolve `parseAsync`, so they\n // never reach this and keep running. Flush stdout first (the empty write's\n // callback fires after all prior writes drain) so piped/non-TTY output isn't\n // truncated by the exit.\n await new Promise<void>((resolve) => process.stdout.write(\"\", () => resolve()));\n process.exit(process.exitCode ?? 0);\n}\n","import crypto from \"node:crypto\";\nimport http from \"node:http\";\nimport readline from \"node:readline\";\nimport open from \"open\";\nimport {\n saveAuth,\n generatePkce,\n OAUTH_AUTHORIZE_URL,\n OAUTH_TOKEN_URL,\n OAUTH_CLIENT_ID,\n} from \"../lib/auth.js\";\n\nconst CALLBACK_PORT = 19823;\nconst REDIRECT_URI = \"https://app.clawnify.com/oauth/cli\";\nconst WEB_ORIGIN = \"https://app.clawnify.com\";\n\n/**\n * Waits for the authorization code from whichever source responds first:\n * - the local callback server (the /oauth/cli page forwards the code via\n * fetch when the browser runs on this machine)\n * - the \"Paste code here\" prompt (any browser, e.g. over SSH)\n */\nfunction waitForCode(state: string): Promise<string> {\n return new Promise((resolve, reject) => {\n let done = false;\n let rl: readline.Interface | null = null;\n\n const server = http.createServer((req, res) => {\n const url = new URL(req.url!, `http://127.0.0.1:${CALLBACK_PORT}`);\n\n // Chrome sends a private-network CORS preflight before the https\n // page may fetch a 127.0.0.1 URL.\n const corsHeaders: Record<string, string> = {\n \"Access-Control-Allow-Origin\": WEB_ORIGIN,\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Private-Network\": \"true\",\n };\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204, corsHeaders);\n res.end();\n return;\n }\n\n if (url.pathname !== \"/callback\") {\n res.writeHead(404, corsHeaders);\n res.end(\"Not found\");\n return;\n }\n\n const code = url.searchParams.get(\"code\");\n const returnedState = url.searchParams.get(\"state\");\n\n if (!code || returnedState !== state) {\n res.writeHead(400, { ...corsHeaders, \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: false }));\n return;\n }\n\n res.writeHead(200, { ...corsHeaders, \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true }));\n finish(null, code);\n });\n\n const timeout = setTimeout(() => {\n finish(new Error(\"Timed out waiting for authorization.\"));\n }, 5 * 60 * 1000);\n\n function finish(err: Error | null, code?: string) {\n if (done) return;\n done = true;\n clearTimeout(timeout);\n server.close();\n rl?.close();\n if (err) reject(err);\n else resolve(code!);\n }\n\n // If the port is taken (another login, another tool), the paste\n // prompt still works — don't fail the whole flow.\n server.on(\"error\", () => {});\n server.listen(CALLBACK_PORT);\n\n rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question(\"Paste code here if prompted > \", (answer) => {\n const input = answer.trim();\n if (!input) {\n finish(new Error(\"No code provided.\"));\n return;\n }\n const [code, pastedState] = input.split(\"#\");\n if (!code || pastedState !== state) {\n finish(new Error(\"Invalid code. Run `clawnify login` to try again.\"));\n return;\n }\n finish(null, code);\n });\n });\n}\n\nexport async function loginCommand(): Promise<void> {\n const { codeVerifier: verifier, codeChallenge: challenge } = generatePkce();\n const state = crypto.randomBytes(16).toString(\"hex\");\n\n const authUrl = new URL(OAUTH_AUTHORIZE_URL);\n authUrl.searchParams.set(\"response_type\", \"code\");\n authUrl.searchParams.set(\"client_id\", OAUTH_CLIENT_ID);\n authUrl.searchParams.set(\"redirect_uri\", REDIRECT_URI);\n authUrl.searchParams.set(\"code_challenge\", challenge);\n authUrl.searchParams.set(\"code_challenge_method\", \"S256\");\n authUrl.searchParams.set(\"scope\", \"openid email\");\n authUrl.searchParams.set(\"state\", state);\n\n console.log(\"Opening browser to authorize...\");\n console.log(\"\\nBrowser didn't open? Use the url below to sign in:\\n\");\n console.log(` ${authUrl.toString()}\\n`);\n open(authUrl.toString()).catch(() => {\n // No browser available (SSH/headless) — the printed URL is the fallback\n });\n\n const code = await waitForCode(state);\n\n const tokenRes = await fetch(OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n client_id: OAUTH_CLIENT_ID,\n redirect_uri: REDIRECT_URI,\n code_verifier: verifier,\n }),\n });\n\n if (!tokenRes.ok) {\n const err = await tokenRes.text();\n throw new Error(`Token exchange failed: ${err}`);\n }\n\n const result = (await tokenRes.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n token_type: string;\n };\n\n // Decode JWT to get email\n let email = \"unknown\";\n try {\n const payload = JSON.parse(\n Buffer.from(result.access_token.split(\".\")[1], \"base64\").toString()\n );\n email = payload.email || \"unknown\";\n } catch {\n // ignore decode errors\n }\n\n const expiresAt = Math.floor(Date.now() / 1000) + result.expires_in;\n\n // Org linking is lazy: the first command that needs an org prompts once\n // (ensureOrg in lib/api.ts) and persists it. `clawnify org use` switches.\n saveAuth({\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n expires_at: expiresAt,\n });\n\n console.log(`Logged in as ${email}`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport readline from \"node:readline\";\nimport { spawn } from \"node:child_process\";\nimport { api, listMyOrgs } from \"../lib/api.js\";\nimport { createArchive } from \"../lib/archive.js\";\nimport {\n findWorkspaceRoot,\n manifestKind,\n readManifest,\n readProject,\n readWorkspaceConfig,\n saveProject,\n type ProjectConfig,\n} from \"../lib/config.js\";\nimport { pollUntilReady } from \"../lib/poll.js\";\nimport { fetchSchema, writeSchema } from \"../lib/sync-schema.js\";\n\ninterface DeploySuccess {\n app_id: string;\n slug: string;\n app_token: string;\n}\n\ninterface SlugConflict {\n error: \"slug_exists_in_org\";\n existing_app_id: string;\n existing_app_name: string;\n slug: string;\n suggested_slug: string;\n}\n\nexport interface DeployOptions {\n from?: string;\n path?: string;\n name?: string;\n org?: string;\n yes?: boolean;\n updateExisting?: boolean;\n createNew?: boolean;\n dryRun?: boolean;\n noSync?: boolean;\n}\n\n// Exit codes: keep separate ones so CI/agents can branch on outcome.\nconst EXIT_USAGE = 64;\nconst EXIT_CONFLICT_NEEDS_DECISION = 75;\n\nfunction ask(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function uploadDeploy(\n archive: Buffer,\n name: string,\n framework: string,\n orgId?: string,\n): Promise<{ ok: true; data: DeploySuccess } | { ok: false; conflict: SlugConflict } | { ok: false; error: string }> {\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n formData.append(\"name\", name);\n formData.append(\"framework\", framework);\n\n const res = await api.postForm(\"/v1/apps/deploy\", formData, { orgId });\n if (res.ok) {\n const data = (await res.json()) as DeploySuccess;\n return { ok: true, data };\n }\n if (res.status === 409) {\n const conflict = (await res.json()) as SlugConflict;\n return { ok: false, conflict };\n }\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n return { ok: false, error: err.error || res.statusText };\n}\n\nasync function uploadRedeploy(\n appId: string,\n archive: Buffer,\n orgId?: string,\n): Promise<{ ok: true; data: DeploySuccess } | { ok: false; error: string }> {\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n\n const res = await api.postForm(`/v1/apps/${appId}/redeploy`, formData, { orgId });\n if (res.ok) {\n const data = (await res.json()) as DeploySuccess;\n return { ok: true, data };\n }\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n return { ok: false, error: err.error || res.statusText };\n}\n\nfunction assertNodeVersion() {\n const [major] = process.versions.node.split(\".\").map(Number);\n if (major < 22) {\n console.error(\n `\\n Clawnify requires Node.js v22 or later.\\n` +\n ` You are using v${process.versions.node}.\\n\\n` +\n ` Install a newer version: https://nodejs.org\\n` +\n ` Or use a version manager: nvm use 22\\n`\n );\n process.exit(1);\n }\n}\n\nasync function resolveOrgId(\n options: DeployOptions,\n linkedProject: ProjectConfig | null,\n resolvedDir?: string,\n): Promise<string | undefined> {\n if (options.org) {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === options.org || o.slug === options.org);\n if (!match) {\n console.error(\n `No org matched \"${options.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n if (linkedProject?.app_id && linkedProject.org_id && linkedProject.org_id !== match.id) {\n console.error(\n `This project is linked to a different org (${linkedProject.org_id}).\\n` +\n ` --org ${options.org} resolves to ${match.id}.\\n` +\n ` Re-link first: clawnify link ${linkedProject.app_id} --org ${options.org}`,\n );\n process.exit(1);\n }\n return match.id;\n }\n // Only honor project.json's org_id when the project is actually linked.\n // An unlinked project (no app_id) should defer to the user's active org\n // so `clawnify org use X && clawnify deploy` works in a fresh directory.\n if (linkedProject?.app_id && linkedProject.org_id) {\n return linkedProject.org_id;\n }\n // A fresh (unlinked) target inside a workspace deploys to the workspace's\n // org, not whatever global active org happens to be set. Once linked (above),\n // that link wins and this is skipped.\n if (resolvedDir) {\n const wsOrg = await workspaceOrgId(resolvedDir);\n if (wsOrg) return wsOrg;\n }\n return undefined;\n}\n\n/**\n * Resolve the org a workspace is bound to (slug or id in its clawnify.json),\n * or undefined if `resolvedDir` is not inside a workspace. Exits with a clear\n * error if the workspace names an org the user can't access.\n */\nasync function workspaceOrgId(resolvedDir: string): Promise<string | undefined> {\n const ws = findWorkspaceRoot(resolvedDir);\n if (!ws?.org) return undefined;\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === ws.org || o.slug === ws.org);\n if (!match) {\n console.error(\n `This workspace is bound to org \"${ws.org}\", but you're not a member of it ` +\n `(or it no longer exists).\\n Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n return match.id;\n}\n\ntype ConflictDecision = \"update\" | \"create\" | \"cancel\";\n\nasync function resolveConflictDecision(\n options: DeployOptions,\n conflict: SlugConflict,\n): Promise<ConflictDecision> {\n if (options.updateExisting) return \"update\";\n if (options.createNew) return \"create\";\n if (options.yes) return \"update\";\n\n if (!process.stdin.isTTY) {\n console.error(\n `\\n Slug '${conflict.slug}' is taken in this organization.\\n` +\n ` Pass one of:\\n` +\n ` --update-existing overwrite the existing app\\n` +\n ` --create-new deploy as '${conflict.suggested_slug}'\\n` +\n ` --yes default to update (safest)\\n`,\n );\n process.exit(EXIT_CONFLICT_NEEDS_DECISION);\n }\n\n console.log(\n `\\n Slug '${conflict.slug}' is taken in this organization` +\n ` (currently held by an app named '${conflict.existing_app_name}').\\n`,\n );\n console.log(` 1) Update that app — deploy this source over it`);\n console.log(` 2) Create a new app at slug '${conflict.suggested_slug}'\\n`);\n const answer = await ask(\" Choose [1/2] (default 1): \");\n\n if (answer === \"\" || answer === \"1\") return \"update\";\n if (answer === \"2\") return \"create\";\n\n console.error(\n `\\n Cancelled. Received '${answer}' — expected 1 or 2.\\n` +\n ` For non-interactive use, pass --update-existing or --create-new.\\n`,\n );\n return \"cancel\";\n}\n\nfunction summarizeArchive(buf: Buffer, files: string[], framework: string, name: string) {\n const sizeKB = (buf.length / 1024).toFixed(1);\n console.log(`\\n Dry run — would deploy '${name}' (${framework})`);\n console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped\\n`);\n const preview = files.slice(0, 25);\n for (const f of preview) console.log(` ${f}`);\n if (files.length > preview.length) {\n console.log(` ... and ${files.length - preview.length} more`);\n }\n console.log();\n}\n\ninterface WebsiteDeployResponse {\n website_id: string;\n slug: string;\n status: string;\n url: string;\n}\n\nasync function uploadWebsiteDeploy(\n archive: Buffer,\n name: string | undefined,\n orgId?: string,\n): Promise<\n | { ok: true; data: WebsiteDeployResponse }\n | { ok: false; error: string }\n> {\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n if (name) formData.append(\"name\", name);\n\n const res = await api.postForm(\"/v1/websites/deploy\", formData, { orgId });\n if (res.ok) {\n const data = (await res.json()) as WebsiteDeployResponse;\n return { ok: true, data };\n }\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n return { ok: false, error: err.error || res.statusText };\n}\n\nasync function deployWebsite(dir: string | undefined, options: DeployOptions): Promise<void> {\n if (options.from) {\n console.error(\"--from is app-only for now. Run `clawnify deploy` inside the website project directory.\");\n process.exit(EXIT_USAGE);\n }\n\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const manifest = readManifest(resolvedDir);\n const baseName = options.name || manifest?.name || path.basename(resolvedDir);\n const linkedProject = readProject(resolvedDir);\n const { archive, files } = createArchive(resolvedDir);\n\n // Org resolution mirrors the app path. A linked website's org_id wins\n // unless the user passed --org explicitly.\n let orgId: string | undefined;\n if (options.org) {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === options.org || o.slug === options.org);\n if (!match) {\n console.error(\n `No org matched \"${options.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n if (linkedProject?.website_id && linkedProject.org_id && linkedProject.org_id !== match.id) {\n console.error(\n `This project is linked to a different org (${linkedProject.org_id}).\\n` +\n ` --org ${options.org} resolves to ${match.id}.`,\n );\n process.exit(1);\n }\n orgId = match.id;\n } else if (linkedProject?.website_id && linkedProject.org_id) {\n orgId = linkedProject.org_id;\n } else {\n // Fresh website inside a workspace → deploy to the workspace's org.\n orgId = await workspaceOrgId(resolvedDir);\n }\n\n if (options.dryRun) {\n const sizeKB = (archive.length / 1024).toFixed(1);\n console.log(`\\n Dry run — would deploy website '${baseName}' (astro)`);\n console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped\\n`);\n const preview = files.slice(0, 25);\n for (const f of preview) console.log(` ${f}`);\n if (files.length > preview.length) {\n console.log(` ... and ${files.length - preview.length} more`);\n }\n console.log();\n return;\n }\n\n console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);\n const result = await uploadWebsiteDeploy(archive, baseName, orgId);\n if (!result.ok) {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n }\n\n saveProject(resolvedDir, {\n kind: \"website\",\n org_id: orgId,\n website_id: result.data.website_id,\n slug: result.data.slug,\n });\n\n const polled = await pollUntilReady(result.data.website_id, {\n kind: \"website\",\n orgId,\n });\n if (polled.status === \"error\") {\n console.error(`\\n Deploy failed: ${polled.error || \"Unknown error\"}\\n`);\n process.exit(1);\n }\n\n // Draft-first: the deploy lands on the draft tier (status 'preview').\n // Publishing to the live URL is an explicit action from the dashboard.\n if (polled.status === \"live\") {\n console.log(`\\n ✓ Published! ${result.data.url}\\n`);\n } else {\n console.log(\n `\\n ✓ Deployed to draft.\\n` +\n ` Review it in the dashboard, then \"Publish to live\" when ready.\\n`,\n );\n }\n}\n\nexport async function deployCommand(\n dir?: string,\n options: DeployOptions = {},\n): Promise<void> {\n assertNodeVersion();\n\n // Dispatch on manifest kind early — websites take a completely different\n // path (no slug conflicts, no schema sync, different API endpoint).\n if (!options.from) {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const manifest = readManifest(resolvedDir);\n // A workspace root is a monorepo of apps, not a deployable app itself.\n // Refuse to tar the whole tree; point the user at a specific app.\n if (!manifest && readWorkspaceConfig(resolvedDir)) {\n console.error(\n \"This is a Clawnify workspace root, not an app.\\n\" +\n \" Deploy a specific app: clawnify deploy apps/<name>\\n\" +\n \" Or cd into one: cd apps/<name> && clawnify deploy\",\n );\n process.exit(EXIT_USAGE);\n }\n if (manifest) {\n try {\n const kind = manifestKind(manifest);\n if (kind === \"website\") {\n return deployWebsite(dir, options);\n }\n } catch (err) {\n console.error(`${(err as Error).message}`);\n process.exit(EXIT_USAGE);\n }\n }\n // No manifest → fall through to the app path (it tolerates a missing\n // manifest by defaulting framework to vite-preact).\n }\n\n let appId: string;\n let slug: string;\n let appToken: string;\n let resolvedOrgId: string | undefined;\n let syncTargetDir: string | undefined;\n\n if (options.from) {\n const repo = options.from.replace(/^github:/, \"\");\n const subdir = options.path?.trim().replace(/^\\/+|\\/+$/g, \"\") || undefined;\n if (options.dryRun) {\n console.log(\n `\\n Dry run — would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : \"\"})\\n`,\n );\n return;\n }\n console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : \"\"}...`);\n\n const orgId = options.org ? (await resolveOrgId(options, null)) : undefined;\n const res = await api.post(\"/v1/apps/deploy\", { repo, branch: \"main\", subdir }, { orgId });\n if (!res.ok) {\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Deploy failed: ${err.error || res.statusText}`);\n process.exit(1);\n }\n\n const data = (await res.json()) as DeploySuccess;\n appId = data.app_id;\n slug = data.slug;\n appToken = data.app_token;\n resolvedOrgId = orgId;\n // syncTargetDir intentionally left undefined: deploying from a remote\n // repo has no canonical local directory to mirror back into.\n } else {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n syncTargetDir = resolvedDir;\n const manifest = readManifest(resolvedDir);\n const baseName = options.name || manifest?.name || path.basename(resolvedDir);\n const framework = manifest?.app?.framework || \"vite-preact\";\n const linkedProject = readProject(resolvedDir);\n await regenerateDrizzleMigrations(resolvedDir);\n const { archive, files } = createArchive(resolvedDir);\n const orgId = await resolveOrgId(options, linkedProject, resolvedDir);\n\n if (options.dryRun) {\n summarizeArchive(archive, files, framework, baseName);\n if (linkedProject?.app_id) {\n console.log(` Would update existing app: ${linkedProject.slug ?? linkedProject.app_id}\\n`);\n } else {\n console.log(` Would create new app: ${baseName}\\n`);\n }\n return;\n }\n\n if (linkedProject?.app_id) {\n console.log(`Updating ${baseName} (${linkedProject.slug ?? linkedProject.app_id})...`);\n const result = await uploadRedeploy(linkedProject.app_id, archive, orgId);\n if (!result.ok) {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n }\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.data.app_token;\n saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });\n } else {\n console.log(`Deploying ${baseName}...`);\n let result = await uploadDeploy(archive, baseName, framework, orgId);\n\n if (!result.ok && \"conflict\" in result) {\n const decision = await resolveConflictDecision(options, result.conflict);\n\n if (decision === \"update\") {\n const redeployResult = await uploadRedeploy(result.conflict.existing_app_id, archive, orgId);\n if (!redeployResult.ok) {\n console.error(`Deploy failed: ${redeployResult.error}`);\n process.exit(1);\n }\n appId = redeployResult.data.app_id;\n slug = redeployResult.data.slug;\n appToken = redeployResult.data.app_token;\n } else if (decision === \"create\") {\n result = await uploadDeploy(archive, result.conflict.suggested_slug, framework, orgId);\n if (!result.ok) {\n const errMsg = \"conflict\" in result ? \"Slug still conflicts\" : result.error;\n console.error(`Deploy failed: ${errMsg}`);\n process.exit(1);\n }\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.data.app_token;\n } else {\n process.exit(EXIT_CONFLICT_NEEDS_DECISION);\n }\n } else if (!result.ok) {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n } else {\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.data.app_token;\n }\n\n saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });\n resolvedOrgId = orgId;\n }\n }\n\n const result = await pollUntilReady(appId);\n\n if (result.status === \"error\") {\n console.error(`\\n Deploy failed: ${result.error || \"Unknown error\"}\\n`);\n process.exit(1);\n }\n\n const url = `https://${slug}.apps.clawnify.com`;\n console.log(`\\n ✓ Deployed! ${url}\\n`);\n console.log(` Open: clawnify open ${slug}\\n`);\n\n // Auto-sync schema.sql from the deployed app back into the local repo\n // so the local copy mirrors the deployed schema after migrations apply.\n // Skipped when deploying from a remote --from <repo> (no local dir to\n // sync into) or when --no-sync is passed. Failures here don't fail the\n // deploy — the deploy itself already succeeded.\n if (syncTargetDir && !options.noSync && resolvedOrgId) {\n try {\n const schema = await fetchSchema({ appId, orgId: resolvedOrgId });\n const target = path.join(syncTargetDir, \"schema.sql\");\n const writeResult = await writeSchema(target, schema);\n const rel = path.relative(process.cwd(), writeResult.path) || writeResult.path;\n switch (writeResult.status) {\n case \"written\":\n console.log(` Synced ${rel} (${writeResult.bytes} bytes)\\n`);\n break;\n case \"refused-uncommitted\":\n console.log(\n ` ${rel} has uncommitted changes — not overwriting.\\n` +\n ` Run \\`clawnify pull schema --force --from ${slug}\\` to overwrite.\\n`,\n );\n break;\n case \"refused-different\":\n console.log(\n ` ${rel} differs from the deployed copy (not in git).\\n` +\n ` Run \\`clawnify pull schema --force --from ${slug}\\` to overwrite.\\n`,\n );\n break;\n case \"no-schema\":\n case \"unchanged\":\n // Silent — nothing to report.\n break;\n }\n } catch (err) {\n console.log(` (schema sync skipped: ${(err as Error).message})\\n`);\n }\n }\n}\n\n/**\n * Run `drizzle-kit generate` so .clawnify/drizzle/*.sql is current\n * with src/server/schema.ts. archive.ts auto-includes those files\n * remapped to `drizzle/<file>` in the uploaded tar; the deploy\n * pipeline (PR #444) reads them from R2 and applies via the\n * existing applyPendingMigrations path.\n *\n * No-op for apps that don't use the drizzle path (legacy schema.sql,\n * no schema.ts, or no drizzle.config.ts). Failure is non-fatal:\n * we warn and continue, so a deploy never silently breaks just\n * because a user hasn't set up drizzle-kit yet.\n */\nasync function regenerateDrizzleMigrations(resolvedDir: string): Promise<void> {\n const schemaTs = path.join(resolvedDir, \"src/server/schema.ts\");\n const drizzleConfig = path.join(resolvedDir, \"drizzle.config.ts\");\n if (!fs.existsSync(schemaTs) || !fs.existsSync(drizzleConfig)) return;\n\n await new Promise<void>((resolve) => {\n const proc = spawn(\"npx\", [\"drizzle-kit\", \"generate\"], {\n cwd: resolvedDir,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n let stderr = \"\";\n proc.stderr?.on(\"data\", (d: Buffer) => { stderr += d.toString(); });\n proc.on(\"exit\", (code) => {\n if (code !== 0) {\n console.warn(\n ` warning: drizzle-kit generate failed (${stderr.trim().slice(0, 200)}). ` +\n `Continuing with existing .clawnify/drizzle/ contents.`,\n );\n }\n resolve();\n });\n proc.on(\"error\", () => resolve());\n });\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { api, listMyOrgs, type Org } from \"./api.js\";\n\ninterface AppRef {\n org: Org;\n appId: string;\n slug: string;\n}\n\ninterface AppSummary {\n id: string;\n slug: string;\n name?: string;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Resolve an app id-or-slug against the user's orgs, returning the org +\n * app id/slug. Mirrors the resolution in link.ts so `pull` can be used\n * without a pre-existing `clawnify link`.\n */\nexport async function resolveApp(idOrSlug: string, orgFilter?: string): Promise<AppRef | null> {\n const orgs = await listMyOrgs();\n if (orgs.length === 0) return null;\n\n const candidates = orgFilter\n ? orgs.filter((o) => o.id === orgFilter || o.slug === orgFilter)\n : orgs;\n if (candidates.length === 0) return null;\n\n const isUuid = UUID_RE.test(idOrSlug);\n if (isUuid) {\n for (const org of candidates) {\n const res = await api.get(`/v1/apps/${idOrSlug}`, { orgId: org.id });\n if (res.ok) {\n const app = (await res.json()) as AppSummary;\n return { org, appId: app.id, slug: app.slug };\n }\n }\n return null;\n }\n\n for (const org of candidates) {\n const res = await api.get(`/v1/apps`, { orgId: org.id });\n if (!res.ok) continue;\n const payload = (await res.json()) as { apps?: AppSummary[] } | AppSummary[];\n const apps = Array.isArray(payload) ? payload : payload.apps ?? [];\n const match = apps.find((a) => a.slug === idOrSlug);\n if (match) return { org, appId: match.id, slug: match.slug };\n }\n return null;\n}\n\n/**\n * Fetch the deployed app's current schema.sql snapshot from the API.\n * Returns null if the app has no schema.sql (pre-backfill / no DB).\n *\n * Accepts either a full AppRef (from resolveApp) or a minimal\n * { appId, orgId } pair (from deploy, which already knows both).\n */\nexport async function fetchSchema(\n ref: AppRef | { appId: string; orgId: string },\n): Promise<string | null> {\n const appId = \"appId\" in ref ? ref.appId : (ref as AppRef).appId;\n const orgId = \"orgId\" in ref ? ref.orgId : (ref as AppRef).org.id;\n const res = await api.get(`/v1/apps/${appId}/schema`, { orgId });\n if (!res.ok) {\n if (res.status === 404) return null;\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n throw new Error(`Schema fetch failed: ${err.error ?? res.statusText}`);\n }\n const data = (await res.json()) as { schema_sql: string | null };\n return data.schema_sql;\n}\n\nexport type WriteResult =\n | { status: \"written\"; path: string; bytes: number }\n | { status: \"unchanged\"; path: string }\n | { status: \"no-schema\"; path: string }\n | { status: \"refused-uncommitted\"; path: string }\n | { status: \"refused-different\"; path: string };\n\n/**\n * Write a fetched schema to disk with safety guards.\n *\n * - \"unchanged\" : on-disk file already matches what we'd\n * write; no-op.\n * - \"refused-uncommitted\" : the target file has uncommitted git\n * changes — refuse unless force=true.\n * - \"refused-different\" : the target file differs and we're not\n * in a git repo — refuse unless force=true\n * (otherwise we'd silently clobber unknown\n * local edits).\n * - \"no-schema\" : the deployed app has no schema.sql to\n * fetch; nothing written.\n * - \"written\" : wrote the file.\n */\nexport async function writeSchema(\n targetPath: string,\n schema: string | null,\n options: { force?: boolean } = {},\n): Promise<WriteResult> {\n if (schema === null) {\n return { status: \"no-schema\", path: targetPath };\n }\n\n let existing: string | null = null;\n try {\n existing = await fs.readFile(targetPath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n\n if (existing === schema) {\n return { status: \"unchanged\", path: targetPath };\n }\n\n if (existing !== null && !options.force) {\n const dir = path.dirname(path.resolve(targetPath));\n if (isInsideGitRepo(dir)) {\n if (hasUncommittedChanges(dir, targetPath)) {\n return { status: \"refused-uncommitted\", path: targetPath };\n }\n } else {\n // Outside git, can't tell intent — be conservative.\n return { status: \"refused-different\", path: targetPath };\n }\n }\n\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n await fs.writeFile(targetPath, schema, \"utf8\");\n return { status: \"written\", path: targetPath, bytes: schema.length };\n}\n\nfunction isInsideGitRepo(dir: string): boolean {\n try {\n execSync(\"git rev-parse --is-inside-work-tree\", {\n cwd: dir,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction hasUncommittedChanges(dir: string, filePath: string): boolean {\n try {\n const relative = path.relative(dir, path.resolve(filePath));\n const status = execSync(`git status --porcelain -- \"${relative}\"`, {\n cwd: dir,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n return status.length > 0;\n } catch {\n // git not available or other error — treat as uncommitted for safety.\n return true;\n }\n}\n","import { api } from \"../lib/api.js\";\n\ninterface App {\n id: string;\n name: string;\n slug: string;\n status: string;\n}\n\nexport async function lsCommand(): Promise<void> {\n const res = await api.get(\"/v1/apps\");\n if (!res.ok) {\n console.error(\"Failed to list apps.\");\n process.exit(1);\n }\n\n const payload = (await res.json()) as { apps: App[] } | App[];\n const apps = Array.isArray(payload) ? payload : payload.apps;\n\n if (apps.length === 0) {\n console.log(\"No apps deployed yet.\");\n return;\n }\n\n const nameWidth = Math.max(4, ...apps.map((a) => a.name.length));\n const slugWidth = Math.max(4, ...apps.map((a) => a.slug.length));\n\n console.log(\n `${\"Name\".padEnd(nameWidth)} ${\"Slug\".padEnd(slugWidth)} ${\"Status\".padEnd(8)} URL`\n );\n console.log(\n `${\"─\".repeat(nameWidth)} ${\"─\".repeat(slugWidth)} ${\"─\".repeat(8)} ${\"─\".repeat(30)}`\n );\n\n for (const app of apps) {\n const url = `https://${app.slug}.apps.clawnify.com`;\n console.log(\n `${app.name.padEnd(nameWidth)} ${app.slug.padEnd(slugWidth)} ${app.status.padEnd(8)} ${url}`\n );\n }\n}\n","import { api } from \"../lib/api.js\";\n\ninterface AppLogs {\n status: string;\n status_message?: string;\n logs?: string;\n}\n\nexport async function logsCommand(appId: string): Promise<void> {\n const res = await api.get(`/v1/apps/${appId}/logs`);\n if (!res.ok) {\n console.error(\"Failed to fetch logs.\");\n process.exit(1);\n }\n\n const data = (await res.json()) as AppLogs;\n\n console.log(`Status: ${data.status}`);\n if (data.status_message) {\n console.log(`Message: ${data.status_message}`);\n }\n if (data.logs) {\n console.log(\"\\n--- Build Logs ---\\n\");\n console.log(data.logs);\n }\n}\n","import readline from \"node:readline\";\nimport { api } from \"../lib/api.js\";\n\ninterface App {\n name: string;\n}\n\nexport async function rmCommand(appId: string): Promise<void> {\n const res = await api.get(`/v1/apps/${appId}`);\n if (!res.ok) {\n console.error(\"App not found.\");\n process.exit(1);\n }\n\n const app = (await res.json()) as App;\n\n const confirmed = await new Promise<boolean>((resolve) => {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question(`Delete ${app.name}? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === \"y\");\n });\n });\n\n if (!confirmed) {\n console.log(\"Cancelled.\");\n return;\n }\n\n const delRes = await api.del(`/v1/apps/${appId}`);\n if (!delRes.ok) {\n console.error(\"Failed to delete app.\");\n process.exit(1);\n }\n\n console.log(`Deleted ${app.name}`);\n}\n","import open from \"open\";\nimport { readProject } from \"../lib/config.js\";\nimport { api } from \"../lib/api.js\";\n\ninterface App {\n slug: string;\n app_token?: string;\n}\n\nexport async function openCommand(slug: string): Promise<void> {\n let appToken: string | undefined;\n\n const project = readProject();\n if (project?.slug === slug && project.app_token) {\n appToken = project.app_token;\n }\n\n if (!appToken) {\n const res = await api.get(\"/v1/apps\");\n if (res.ok) {\n const apps = (await res.json()) as App[];\n const app = apps.find((a) => a.slug === slug);\n appToken = app?.app_token;\n }\n }\n\n let url = `https://${slug}.apps.clawnify.com`;\n if (appToken) {\n url += `?token=${appToken}`;\n }\n\n await open(url);\n console.log(\"Opened in browser\");\n}\n","import { loadAuth, getEmailFromToken } from \"../lib/auth.js\";\n\nexport async function whoamiCommand(): Promise<void> {\n const auth = loadAuth();\n\n if (!auth) {\n console.log(\"Not logged in\");\n return;\n }\n\n const email = getEmailFromToken(auth.access_token) ?? \"unknown\";\n console.log(`Email: ${email}`);\n if (auth.org_id) {\n console.log(`Org: ${auth.org_id}`);\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport readline from \"node:readline\";\nimport { findWorkspaceRoot } from \"../lib/config.js\";\nimport { detectAgents, agentByName } from \"../lib/skills/detect.js\";\nimport { installAiFiles } from \"./ai-files.js\";\n\nfunction ask(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 30);\n}\n\nconst TEMPLATES = {\n blank: \"Empty app with a single API route and page\",\n crud: \"CRUD app with a database table, list, and form\",\n};\n\ntype ProjectType = \"app\" | \"website\";\n\ninterface InitOptions {\n name?: string;\n template?: string;\n storage?: boolean;\n type?: string;\n /** Non-interactive: take all defaults (app / blank / no storage / dir-based name).\n * Matches the `--yes` convention used by `npm create next-app` etc. */\n yes?: boolean;\n /** commander sets this false for `--no-ai-files`; default (undefined) installs. */\n aiFiles?: boolean;\n}\n\nasync function askProjectType(opts?: InitOptions): Promise<ProjectType> {\n if (opts?.type === \"app\" || opts?.type === \"website\") return opts.type;\n if (opts?.type) {\n console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);\n process.exit(1);\n }\n if (opts?.yes) return \"app\";\n console.log();\n console.log(\" What are you creating?\");\n console.log(\" 1) app — full-stack project (React + Hono + D1)\");\n console.log(\" 2) website — public site (Astro)\");\n console.log();\n const choice = (await ask(\"Type [1]: \")) || \"1\";\n return choice === \"2\" ? \"website\" : \"app\";\n}\n\n/**\n * Detect which package manager invoked us. npm/pnpm/yarn/bun all set\n * `npm_config_user_agent` to something like `pnpm/10.15.1 npm/? ...`\n * before exec'ing the create-* package. We mirror that PM in our\n * post-scaffold \"Get started\" hints so users don't see `pnpm dev`\n * after running `yarn create`.\n */\nfunction detectPackageManager(): \"pnpm\" | \"npm\" | \"yarn\" | \"bun\" {\n const ua = process.env.npm_config_user_agent ?? \"\";\n if (ua.startsWith(\"pnpm\")) return \"pnpm\";\n if (ua.startsWith(\"yarn\")) return \"yarn\";\n if (ua.startsWith(\"bun\")) return \"bun\";\n return \"npm\";\n}\n\nexport async function initCommand(dir?: string, opts?: InitOptions): Promise<void> {\n const type = await askProjectType(opts);\n if (type === \"website\") {\n return initWebsite(dir, opts);\n }\n return initApp(dir, opts);\n}\n\nasync function initApp(dir?: string, opts?: InitOptions): Promise<void> {\n // --yes auto-fills everything: name from dir arg or \"my-app\", template\n // blank, no storage. Matches `npm create next-app -y` behavior.\n const yes = !!opts?.yes;\n const dirArgName = dir ? path.basename(path.resolve(dir)) : undefined;\n const name = opts?.name || (yes ? (dirArgName ?? \"my-app\") : (await ask(\"App name: \")) || \"my-app\");\n const slug = slugify(name);\n // Inside a workspace (and with no explicit dir), drop the app under apps/<slug>\n // so the monorepo stays tidy. An explicit dir arg always wins.\n let targetDir: string;\n if (dir) {\n targetDir = path.resolve(dir);\n } else {\n const ws = findWorkspaceRoot(process.cwd());\n targetDir = ws ? path.join(ws.dir, \"apps\", slug) : path.resolve(slug);\n }\n\n let template: string;\n if (opts?.template) {\n template = opts.template === \"crud\" ? \"crud\" : \"blank\";\n } else if (yes) {\n template = \"blank\";\n } else {\n console.log();\n console.log(\" Templates:\");\n console.log(\" 1) blank — Empty app with a single API route and page\");\n console.log(\" 2) crud — CRUD app with database, list, and form\");\n console.log();\n const templateChoice = (await ask(\"Template [1]: \")) || \"1\";\n template = templateChoice === \"2\" ? \"crud\" : \"blank\";\n }\n\n if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n\n fs.mkdirSync(path.join(targetDir, \"src/server\"), { recursive: true });\n fs.mkdirSync(path.join(targetDir, \"src/client\"), { recursive: true });\n\n let storage: boolean;\n if (opts?.storage !== undefined) {\n storage = opts.storage;\n } else if (yes) {\n storage = false;\n } else {\n const storageChoice = (await ask(\"Enable file uploads? [y/N]: \")) || \"n\";\n storage = storageChoice.toLowerCase() === \"y\";\n }\n\n // clawnify.json\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n description: \"\",\n app: { framework: \"react+hono\", database: true, storage },\n }, null, 2));\n\n // package.json\n const devDeps: Record<string, string> = {\n \"@cloudflare/workers-types\": \"^4.0.0\",\n \"@tailwindcss/vite\": \"^4.0.0\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.0\",\n \"@vitejs/plugin-react\": \"^4.0.0\",\n clawnify: \"^0.3.0\",\n \"drizzle-kit\": \"^0.31.0\",\n tailwindcss: \"^4.0.0\",\n vite: \"^6.0.0\",\n wrangler: \"^4.0.0\",\n };\n write(targetDir, \"package.json\", JSON.stringify({\n name: slug,\n private: true,\n type: \"module\",\n scripts: {\n dev: \"clawnify dev\",\n build: \"vite build\",\n deploy: \"clawnify deploy\",\n },\n dependencies: {\n \"@clawnify/db\": \"^0.4.1\",\n \"@hono/zod-openapi\": \"^0.19.0\",\n hono: \"^4.0.0\",\n react: \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n zod: \"^3.0.0\",\n },\n devDependencies: devDeps,\n engines: { node: \">=22\" },\n pnpm: { onlyBuiltDependencies: [\"esbuild\"] },\n }, null, 2));\n\n // tsconfig.json\n write(targetDir, \"tsconfig.json\", JSON.stringify({\n compilerOptions: {\n target: \"ESNext\",\n module: \"ESNext\",\n moduleResolution: \"Bundler\",\n strict: true,\n lib: [\"ESNext\", \"DOM\", \"DOM.Iterable\"],\n jsx: \"react-jsx\",\n noEmit: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n isolatedModules: true,\n },\n include: [\"src/**/*.ts\", \"src/**/*.tsx\"],\n exclude: [\"node_modules\", \"dist\"],\n }, null, 2));\n\n // vite.config.ts\n write(targetDir, \"vite.config.ts\", `import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig({\n plugins: [react(), tailwindcss()],\n build: {\n outDir: \"dist\",\n emptyOutDir: true,\n },\n server: {\n proxy: {\n \"/api\": {\n target: \"http://localhost:8787\",\n changeOrigin: true,\n },\n },\n },\n});\n`);\n\n // index.html\n write(targetDir, \"index.html\", `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${name}</title>\n</head>\n<body>\n <div id=\"app\"></div>\n <script type=\"module\" src=\"/src/client/main.tsx\"></script>\n</body>\n</html>\n`);\n\n // .gitignore\n write(targetDir, \".gitignore\", `node_modules\ndist\n.wrangler\n.clawnify\n.env*\n!.env.example\n.dev.vars\ndata.db\ndata.db-wal\ndata.db-shm\n`);\n\n // src/server/worker-env.d.ts — Cloudflare Workers types\n write(targetDir, \"src/server/worker-env.d.ts\", `/// <reference types=\"@cloudflare/workers-types\" />\n`);\n\n // src/server/schema.ts — Drizzle DSL, the single source of truth for tables.\n // Edit this file to evolve the schema; run `pnpm db:generate` to emit a\n // new migration file under drizzle/, then commit and deploy.\n write(targetDir, \"src/server/schema.ts\", `import { sqliteTable, text, integer } from \"@clawnify/db\";\n\n/**\n * Example table. Replace with your own.\n *\n * Multi-tenancy reminder: every user-facing table should carry an\n * \\`org_id\\` column and every query should filter by the X-Clawnify-Org-Id\n * header. See docs/internal/build-a-clawnify-app.md.\n */\nexport const items = sqliteTable(\"items\", {\n id: integer(\"id\").primaryKey({ autoIncrement: true }),\n name: text(\"name\").notNull(),\n createdAt: text(\"created_at\").notNull().$default(() => new Date().toISOString()),\n});\n`);\n\n // drizzle.config.ts — points drizzle-kit at schema.ts. Migrations\n // are emitted to .clawnify/drizzle/ (gitignored). The CLI runs\n // drizzle-kit generate transparently on `clawnify dev` and\n // `clawnify deploy` — the user never has to think about it. Edit\n // schema.ts; that's it.\n write(targetDir, \"drizzle.config.ts\", `import { defineConfig } from \"drizzle-kit\";\n\nexport default defineConfig({\n schema: \"./src/server/schema.ts\",\n out: \"./.clawnify/drizzle\",\n dialect: \"sqlite\",\n});\n`);\n\n // src/server/index.ts\n if (storage) {\n write(targetDir, \"src/server/index.ts\", `import { OpenAPIHono } from \"@hono/zod-openapi\";\nimport { initUploads } from \"./uploads\";\nimport api from \"./routes\";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.use(\"*\", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route(\"/\", api);\n\napp.doc(\"/api/openapi.json\", {\n openapi: \"3.0.0\",\n info: { title: \"${name}\", version: \"1.0.0\" },\n});\n\nexport default app;\n`);\n\n // src/server/uploads.ts\n write(targetDir, \"src/server/uploads.ts\", `let _bucket: R2Bucket;\n\nexport function initUploads(bucket: R2Bucket) {\n _bucket = bucket;\n}\n\nexport async function putUpload(\n filename: string,\n data: ArrayBuffer | Uint8Array,\n contentType: string,\n): Promise<string> {\n await _bucket.put(filename, data, { httpMetadata: { contentType } });\n return \\`/api/uploads/\\${filename}\\`;\n}\n\nexport async function getUpload(\n filename: string,\n): Promise<{ data: ArrayBuffer; contentType: string } | null> {\n const obj = await _bucket.get(filename);\n if (!obj) return null;\n return {\n data: await obj.arrayBuffer(),\n contentType: obj.httpMetadata?.contentType || \"application/octet-stream\",\n };\n}\n\nexport async function deleteUpload(filename: string): Promise<void> {\n await _bucket.delete(filename);\n}\n\nexport async function readUploadAsBase64DataUrl(\n filename: string,\n): Promise<string | null> {\n const result = await getUpload(filename);\n if (!result) return null;\n const bytes = new Uint8Array(result.data);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n return \\`data:\\${result.contentType};base64,\\${btoa(binary)}\\`;\n}\n`);\n } else {\n write(targetDir, \"src/server/index.ts\", `import { OpenAPIHono } from \"@hono/zod-openapi\";\nimport api from \"./routes\";\n\ntype Env = { Bindings: { DB: D1Database } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.route(\"/\", api);\n\napp.doc(\"/api/openapi.json\", {\n openapi: \"3.0.0\",\n info: { title: \"${name}\", version: \"1.0.0\" },\n});\n\nexport default app;\n`);\n }\n\n // src/client/index.css\n write(targetDir, \"src/client/index.css\", `@import \"tailwindcss\";\n`);\n\n // src/client/main.tsx\n write(targetDir, \"src/client/main.tsx\", `import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { App } from \"./app\";\nimport \"./index.css\";\n\ncreateRoot(document.getElementById(\"app\")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n`);\n\n if (template === \"crud\") {\n writeCrudTemplate(targetDir, name);\n } else {\n writeBlankTemplate(targetDir, name);\n }\n\n // Make the scaffolded app agent-ready: rules + skills + MCP config.\n // Fresh dir has no agent marker, so default to Claude. Opt out with\n // `clawnify init --no-ai-files`.\n if (opts?.aiFiles !== false) {\n const detected = detectAgents(targetDir);\n const agents = detected.length > 0 ? detected : [agentByName(\"claude\")];\n console.log();\n console.log(\" Installing AI files (rules + skills + MCP):\");\n installAiFiles(targetDir, agents, { mcp: true });\n }\n\n const pm = detectPackageManager();\n console.log();\n console.log(` Created ${name} in ${path.relative(process.cwd(), targetDir)}/`);\n console.log();\n console.log(\" Get started:\");\n console.log(` cd ${path.relative(process.cwd(), targetDir)}`);\n console.log(` ${pm} install`);\n console.log(` ${pm} ${pm === \"npm\" ? \"run \" : \"\"}dev # local dev at http://localhost:5173`);\n console.log(` ${pm} ${pm === \"npm\" ? \"run \" : \"\"}deploy # deploy to production`);\n console.log();\n}\n\nasync function initWebsite(dir?: string, opts?: InitOptions): Promise<void> {\n const name = opts?.name || (await ask(\"Site name: \")) || \"my-site\";\n const slug = slugify(name);\n // Inside a workspace (and with no explicit dir), the org's single website\n // lives at website/. An explicit dir arg always wins.\n let targetDir: string;\n if (dir) {\n targetDir = path.resolve(dir);\n } else {\n const ws = findWorkspaceRoot(process.cwd());\n targetDir = ws ? path.join(ws.dir, \"website\") : path.resolve(slug);\n }\n\n if (fs.existsSync(targetDir)) {\n // The workspace scaffold pre-creates website/.gitkeep — tolerate that lone\n // placeholder (and clear it), but refuse any other existing content.\n const entries = fs.readdirSync(targetDir);\n const onlyGitkeep = entries.length === 1 && entries[0] === \".gitkeep\";\n if (entries.length > 0 && !onlyGitkeep) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n if (onlyGitkeep) fs.rmSync(path.join(targetDir, \".gitkeep\"));\n }\n\n fs.mkdirSync(targetDir, { recursive: true });\n\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n description: \"\",\n website: { framework: \"astro\" },\n }, null, 2));\n\n write(targetDir, \"package.json\", JSON.stringify({\n name: slug,\n private: true,\n type: \"module\",\n scripts: {\n dev: \"astro dev\",\n build: \"astro build\",\n preview: \"astro preview\",\n deploy: \"clawnify deploy\",\n },\n dependencies: {\n \"@astrojs/cloudflare\": \"^12.0.0\",\n \"@tailwindcss/vite\": \"^4.0.0\",\n astro: \"^5.0.0\",\n tailwindcss: \"^4.0.0\",\n },\n devDependencies: {\n clawnify: \"^0.1.15\",\n \"wrangler\": \"^4.0.0\",\n },\n engines: { node: \">=22\" },\n }, null, 2));\n\n write(targetDir, \"tsconfig.json\", JSON.stringify({\n extends: \"astro/tsconfigs/strict\",\n include: [\"src/**/*\", \".astro/types.d.ts\"],\n exclude: [\"dist\", \"node_modules\"],\n }, null, 2));\n\n write(targetDir, \"astro.config.mjs\", `import { defineConfig } from \"astro/config\";\nimport cloudflare from \"@astrojs/cloudflare\";\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig({\n output: \"server\",\n adapter: cloudflare(),\n vite: {\n plugins: [tailwindcss()],\n },\n});\n`);\n\n write(targetDir, \".gitignore\", `node_modules\ndist\n.astro\n.wrangler\n.clawnify\n.env*\n!.env.example\n.dev.vars\n`);\n\n write(targetDir, \"src/styles/global.css\", `@import \"tailwindcss\";\n\n:root {\n --color-primary: oklch(0.55 0.18 250);\n --color-ink: oklch(0.2 0.02 250);\n --color-canvas: oklch(0.99 0 0);\n}\n\nbody {\n background-color: var(--color-canvas);\n color: var(--color-ink);\n font-family: ui-sans-serif, system-ui, sans-serif;\n}\n`);\n\n write(targetDir, \"src/layouts/BaseLayout.astro\", `---\ninterface Props {\n title?: string;\n description?: string;\n}\n\nconst { title = \"${name}\", description = \"\" } = Astro.props;\n---\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>{title}</title>\n {description && <meta name=\"description\" content={description} />}\n <link rel=\"stylesheet\" href=\"/src/styles/global.css\" />\n </head>\n <body>\n <slot />\n </body>\n</html>\n`);\n\n write(targetDir, \"src/pages/index.astro\", `---\nimport BaseLayout from \"../layouts/BaseLayout.astro\";\n---\n<BaseLayout title=\"${name}\">\n <main class=\"mx-auto max-w-3xl px-6 py-24\">\n <h1 class=\"text-5xl font-semibold tracking-tight\">${name}</h1>\n <p class=\"mt-4 text-lg opacity-70\">\n Edit <code>src/pages/index.astro</code> to get started.\n </p>\n <p class=\"mt-8\">\n <a class=\"underline\" href=\"https://docs.astro.build\" target=\"_blank\" rel=\"noreferrer\">\n Astro docs →\n </a>\n </p>\n </main>\n</BaseLayout>\n`);\n\n console.log();\n console.log(` Created ${name} in ${path.relative(process.cwd(), targetDir)}/`);\n console.log();\n console.log(\" Get started:\");\n console.log(` cd ${path.relative(process.cwd(), targetDir)}`);\n console.log(\" pnpm install\");\n console.log(\" pnpm dev # local dev at http://localhost:4321\");\n console.log(\" pnpm deploy # deploy as your org's website\");\n console.log();\n}\n\nfunction writeBlankTemplate(dir: string, name: string) {\n // No schema.sql — the build pipeline reads drizzle/*.sql (emitted\n // by drizzle-kit generate) instead. schema.ts is the single source.\n\n write(dir, \"src/server/routes.ts\", `import { OpenAPIHono, createRoute, z } from \"@hono/zod-openapi\";\nimport { getDB, desc } from \"@clawnify/db\";\nimport * as schema from \"./schema\";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi(\"Item\");\n\napi.openapi(\n createRoute({\n method: \"get\",\n path: \"/api/items\",\n summary: \"List items\",\n responses: {\n 200: {\n description: \"List of items\",\n content: { \"application/json\": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n`);\n\n write(dir, \"src/client/app.tsx\", `export function App() {\n return (\n <main className=\"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 px-6\">\n <div className=\"max-w-xl w-full text-center\">\n <div className=\"inline-flex items-center gap-2 rounded-full bg-white/80 backdrop-blur px-3 py-1 text-xs font-medium text-slate-600 ring-1 ring-slate-200\">\n <span className=\"size-1.5 rounded-full bg-emerald-500\" />\n Clawnify · live\n </div>\n\n <h1 className=\"mt-6 text-4xl font-semibold tracking-tight text-slate-900\">\n Welcome to ${name}\n </h1>\n <p className=\"mt-3 text-base text-slate-600\">\n Edit <code className=\"rounded bg-slate-200/70 px-1.5 py-0.5 text-sm\">src/client/app.tsx</code> to get started.\n </p>\n\n <ul className=\"mt-8 grid gap-3 text-left text-sm text-slate-700\">\n <li className=\"rounded-lg border border-slate-200 bg-white px-4 py-3\">\n <span className=\"font-medium text-slate-900\">Try the API.</span> Open <code>/api/items</code> — empty list to start.\n </li>\n <li className=\"rounded-lg border border-slate-200 bg-white px-4 py-3\">\n <span className=\"font-medium text-slate-900\">Evolve the schema.</span> Edit <code>src/server/schema.ts</code>, then run <code>pnpm db:generate</code>.\n </li>\n <li className=\"rounded-lg border border-slate-200 bg-white px-4 py-3\">\n <span className=\"font-medium text-slate-900\">Deploy.</span> Run <code>pnpm deploy</code> to push live.\n </li>\n </ul>\n\n <p className=\"mt-8 text-xs text-slate-500\">\n Read{\" \"}\n <a href=\"https://github.com/clawnify/clawnify/blob/main/docs/internal/build-a-clawnify-app.md\" target=\"_blank\" rel=\"noreferrer\" className=\"underline underline-offset-2\">\n docs/internal/build-a-clawnify-app.md\n </a>{\" \"}\n for the full gold-standard guide.\n </p>\n </div>\n </main>\n );\n}\n`);\n}\n\nfunction writeCrudTemplate(dir: string, name: string) {\n // CRUD template extends the default schema with title + status.\n // Overwrites the schema.ts that initApp wrote (a minimal items\n // table). drizzle-kit generates the matching migration on first\n // `clawnify dev` / `clawnify deploy` — no SQL file shipped here.\n write(dir, \"src/server/schema.ts\", `import { sqliteTable, text, integer } from \"@clawnify/db\";\n\nexport const items = sqliteTable(\"items\", {\n id: integer(\"id\").primaryKey({ autoIncrement: true }),\n title: text(\"title\").notNull(),\n status: text(\"status\").notNull().default(\"active\"),\n createdAt: text(\"created_at\").notNull().$default(() => new Date().toISOString()),\n});\n`);\n\n write(dir, \"src/server/routes.ts\", `import { OpenAPIHono, createRoute, z } from \"@hono/zod-openapi\";\nimport { getDB, eq, desc } from \"@clawnify/db\";\nimport * as schema from \"./schema\";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi(\"Item\");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi(\"CreateItem\");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi(\"UpdateItem\");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi(\"Ok\");\n\napi.openapi(\n createRoute({\n method: \"get\",\n path: \"/api/items\",\n summary: \"List items\",\n responses: {\n 200: {\n description: \"List of items\",\n content: { \"application/json\": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: \"post\",\n path: \"/api/items\",\n summary: \"Create item\",\n request: { body: { content: { \"application/json\": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: \"Created item\",\n content: { \"application/json\": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid(\"json\");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: \"patch\",\n path: \"/api/items/:id\",\n summary: \"Update item\",\n request: {\n params: IdParamSchema,\n body: { content: { \"application/json\": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: \"Updated\", content: { \"application/json\": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid(\"param\");\n const body = c.req.valid(\"json\");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: \"delete\",\n path: \"/api/items/:id\",\n summary: \"Delete item\",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: \"Deleted\", content: { \"application/json\": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid(\"param\");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n`);\n\n write(dir, \"src/client/app.tsx\", `import { useState, useEffect } from \"react\";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState(\"\");\n\n async function load() {\n const res = await fetch(\"/api/items\");\n setItems(await res.json());\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch(\"/api/items\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ title }),\n });\n setTitle(\"\");\n load();\n }\n\n async function toggleStatus(item: Item) {\n const next = item.status === \"active\" ? \"done\" : \"active\";\n await fetch(\\`/api/items/\\${item.id}\\`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ status: next }),\n });\n load();\n }\n\n async function deleteItem(id: number) {\n await fetch(\\`/api/items/\\${id}\\`, { method: \"DELETE\" });\n load();\n }\n\n return (\n <div className=\"max-w-xl mx-auto mt-10 px-4\">\n <h1 className=\"text-2xl font-semibold mb-6\">${name}</h1>\n <form onSubmit={addItem} className=\"flex gap-2 mb-6\">\n <input\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n placeholder=\"Add an item...\"\n className=\"flex-1 px-3 py-2 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-black\"\n />\n <button\n type=\"submit\"\n className=\"px-4 py-2 rounded-lg bg-black text-white text-sm font-medium hover:bg-gray-800\"\n >\n Add\n </button>\n </form>\n <ul className=\"divide-y divide-gray-100\">\n {items.map((item) => (\n <li key={item.id} className=\"flex items-center gap-3 py-2\">\n <input\n type=\"checkbox\"\n checked={item.status === \"done\"}\n onChange={() => toggleStatus(item)}\n className=\"rounded\"\n />\n <span\n className={\\`flex-1 text-sm \\${item.status === \"done\" ? \"line-through text-gray-400\" : \"text-gray-800\"}\\`}\n >\n {item.title}\n </span>\n <button\n onClick={() => deleteItem(item.id)}\n className=\"text-gray-300 hover:text-gray-600 text-lg leading-none\"\n >\n ×\n </button>\n </li>\n ))}\n </ul>\n {items.length === 0 && (\n <p className=\"text-gray-400 text-sm mt-4\">No items yet. Add one above.</p>\n )}\n </div>\n );\n}\n`);\n}\n\nfunction write(dir: string, file: string, content: string) {\n const fullPath = path.join(dir, file);\n fs.mkdirSync(path.dirname(fullPath), { recursive: true });\n fs.writeFileSync(fullPath, content);\n}\n","/**\n * Detect which coding agents have rules/skills directories in `cwd`.\n * `clawnify skills add` installs into ALL detected agents simultaneously\n * (per Riccardo's rule), so this returns every agent whose marker is\n * present rather than picking one.\n *\n * Agent priority order doesn't matter for installation, but listing\n * matches the priority for \"no agent detected\" diagnostics.\n */\n\nimport { existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport type Agent = \"claude\" | \"cursor\" | \"openclaw\" | \"codex\" | \"aider\";\n\nexport interface DetectedAgent {\n agent: Agent;\n /** Where we'll write the skill. Relative to cwd. */\n target: string;\n /** Why this agent was detected. Shown in `--verbose` output. */\n marker: string;\n}\n\ninterface Detector {\n agent: Agent;\n /** Files/dirs whose presence triggers detection. */\n markers: string[];\n /** Where the skill goes — directory or file path, relative to cwd. */\n target: string;\n}\n\nconst DETECTORS: Detector[] = [\n { agent: \"claude\", markers: [\".claude\", \".claude.json\", \"CLAUDE.md\"], target: \".claude/skills\" },\n { agent: \"cursor\", markers: [\".cursor\", \".cursorrules\"], target: \".cursor/rules\" },\n { agent: \"openclaw\", markers: [\".openclaw\", \"openclaw.json\"], target: \".openclaw/skills\" },\n { agent: \"codex\", markers: [\".codex\", \"AGENTS.md\"], target: \".codex/skills\" },\n { agent: \"aider\", markers: [\"CONVENTIONS.md\", \".aider.conf.yml\"], target: \"CONVENTIONS.md\" },\n];\n\nfunction exists(cwd: string, name: string): boolean {\n const path = join(cwd, name);\n try {\n statSync(path);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function detectAgents(cwd: string): DetectedAgent[] {\n const found: DetectedAgent[] = [];\n for (const d of DETECTORS) {\n const hit = d.markers.find((m) => exists(cwd, m));\n if (hit) {\n found.push({ agent: d.agent, target: d.target, marker: hit });\n }\n }\n return found;\n}\n\n/**\n * Force-detect a specific agent by name (used by `--agent` override).\n * Returns the detector entry even if no marker is present — the caller\n * is opting in explicitly.\n */\nexport function agentByName(name: Agent): DetectedAgent {\n const d = DETECTORS.find((x) => x.agent === name);\n if (!d) throw new Error(`Unknown agent: ${name}`);\n return { agent: d.agent, target: d.target, marker: \"(forced)\" };\n}\n\nexport const ALL_AGENTS: Agent[] = DETECTORS.map((d) => d.agent);\n","// GENERATED by scripts/bundle-skills.mjs — do not edit by hand.\n// Source: ../../docs/<name>.md\n\nexport interface BundledSkill {\n name: string;\n description: string;\n content: string;\n}\n\nexport const CLI_VERSION = \"0.8.0\";\n\nexport const BUNDLED_SKILLS: readonly BundledSkill[] = [\n {\n name: \"build-a-clawnify-app\",\n description: \"Author a Clawnify app end-to-end — the canonical Hono + React + Vite + tRPC + @clawnify/db (Drizzle) stack, schema.ts as the single source of truth, MCP-tagged tRPC procedures, and X-Clawnify-* identity headers. Use when building or modifying an app that deploys to the Clawnify platform.\",\n content: \"# Build a Clawnify app\\n\\nCanonical skill: how to author a Clawnify app end-to-end. Same content\\nfor humans reading the docs and for AI coding agents injecting this as\\ninstructions during an app build.\\n\\nIf you're an agent: this document is enough context to produce a\\nworking app from scratch. Follow it literally. The patterns here\\nare the patterns the platform expects.\\n\\n## TL;DR\\n\\n- **One stack.** Hono + React + Vite + tRPC + `@clawnify/db` (Drizzle)\\n + Tailwind + shadcn/ui. Nothing else.\\n- **Schema lives in `schema.ts`** (Drizzle DSL) — single source of\\n truth. Never write SQL DDL by hand.\\n- **Queries through `getDB`** — `import { getDB, eq } from\\n \\\"@clawnify/db\\\"`. JSON columns auto-serialize.\\n- **`clawnify.json`** declares framework, env, and public routes.\\n Build emits `api.tools[]` from tRPC procedure meta.\\n- **No `/mcp` endpoint.** The org's MCP gateway projects tools\\n from the manifest.\\n- **Identity flows via `X-Clawnify-*` headers** injected by the\\n platform. Read them, don't fake them.\\n\\n## Stack rationale\\n\\nOne template, one set of decisions. Don't deviate unless the user has\\nexplicitly asked.\\n\\n## File layout\\n\\n```\\nmy-app/\\n clawnify.json ← Manifest (validated against /schema/v1/clawnify.json)\\n package.json\\n tsconfig.json\\n vite.config.ts\\n tailwind.config.ts\\n components.json ← shadcn/ui config\\n index.html\\n drizzle.config.ts ← Points at src/server/schema.ts → outputs to .clawnify/drizzle\\n .clawnify/ ← CLI cache (gitignored)\\n drizzle/ ← drizzle-kit generate output — never hand-edit\\n 0000_<name>.sql\\n meta/\\n applied-migrations.json ← Local-D1 applied tracker\\n wrangler.toml ← Generated per-dev wrangler config\\n src/\\n server/\\n index.ts ← Hono entry — mounts the tRPC router\\n schema.ts ← Drizzle table definitions — THE schema\\n router.ts ← tRPC router with MCP-tagged procedures\\n auth.ts ← Read X-Clawnify-* identity headers\\n env.d.ts ← Worker bindings types\\n client/\\n main.tsx ← React mount point\\n app.tsx ← Root component\\n lib/\\n trpc.ts ← Typed tRPC client\\n components/ ← shadcn/ui + your components\\n styles.css\\n```\\n\\n## `schema.ts` — the only place tables exist\\n\\n```ts\\n// src/server/schema.ts\\nimport { sqliteTable, text, integer, index } from \\\"@clawnify/db\\\";\\n\\nexport const notes = sqliteTable(\\n \\\"notes\\\",\\n {\\n id: integer(\\\"id\\\").primaryKey({ autoIncrement: true }),\\n orgId: text(\\\"org_id\\\").notNull(), // ALWAYS filter by this in queries\\n title: text(\\\"title\\\").notNull(),\\n body: text(\\\"body\\\").notNull().default(\\\"\\\"),\\n tags: text(\\\"tags\\\", { mode: \\\"json\\\" }).$type<string[]>().notNull().default([]),\\n createdAt: text(\\\"created_at\\\").notNull().$default(() => new Date().toISOString()),\\n },\\n (t) => ({\\n byOrg: index(\\\"notes_by_org\\\").on(t.orgId, t.createdAt),\\n }),\\n);\\n```\\n\\nRules:\\n- JSON columns: `text(col, { mode: \\\"json\\\" }).$type<T>()` — Drizzle\\n serializes on write and parses on read.\\n- Multi-tenancy: every user-facing table has `org_id`. Every query\\n filters by it. No exceptions.\\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\\n\\n## `drizzle.config.ts`\\n\\n```ts\\nimport { defineConfig } from \\\"drizzle-kit\\\";\\n\\nexport default defineConfig({\\n schema: \\\"./src/server/schema.ts\\\",\\n out: \\\"./.clawnify/drizzle\\\",\\n dialect: \\\"sqlite\\\",\\n});\\n```\\n\\nYou never run `drizzle-kit` manually. The CLI runs it for you:\\n\\n- **`clawnify dev`** — runs `drizzle-kit generate`, applies any new\\n migrations to local D1 via `wrangler d1 execute --local`, tracks\\n applied state in `.clawnify/applied-migrations.json` (idempotent\\n on rerun).\\n- **`clawnify deploy`** — same generate step, then auto-includes\\n `.clawnify/drizzle/*.sql` in the upload tar (remapped to\\n `drizzle/<name>` for the deploy pipeline, which applies them\\n transactionally to the live and preview databases and records them\\n in `__clawnify_migrations`).\\n\\nThe output dir (`.clawnify/drizzle/`) is gitignored. Migrations\\nare derived artifacts, not source — never commit them, never edit\\nthem. The single source of truth is `schema.ts`.\\n\\n## `src/server/index.ts` — Hono entry\\n\\n```ts\\nimport { Hono } from \\\"hono\\\";\\nimport { trpcServer } from \\\"@hono/trpc-server\\\";\\nimport { appRouter } from \\\"./router\\\";\\nimport { createContext } from \\\"./auth\\\";\\n\\nconst app = new Hono<{ Bindings: Env }>();\\n\\napp.use(\\\"/trpc/*\\\", trpcServer({\\n router: appRouter,\\n createContext: (opts, c) => createContext(opts, c.env, c.req.raw),\\n}));\\n\\n// SPA fallback — Vite-built static assets served by the platform\\napp.notFound((c) => c.env.ASSETS.fetch(c.req.raw));\\n\\nexport default app;\\n```\\n\\nThat's it. The Worker entry is thin. No MCP mounting, no inline\\nroute handlers — tRPC owns the API surface.\\n\\n## `src/server/auth.ts` — identity from headers\\n\\n```ts\\nimport type { Context } from \\\"hono\\\";\\n\\nexport interface User {\\n id: string;\\n orgId: string;\\n email: string;\\n caller: \\\"user\\\" | \\\"agent\\\" | \\\"agent-browser\\\" | \\\"system\\\";\\n}\\n\\nexport function readUser(req: Request): User | null {\\n const id = req.headers.get(\\\"X-Clawnify-User-Id\\\");\\n const orgId = req.headers.get(\\\"X-Clawnify-Org-Id\\\");\\n const email = req.headers.get(\\\"X-Clawnify-User-Email\\\") ?? \\\"\\\";\\n const caller = (req.headers.get(\\\"X-Clawnify-Caller\\\") ?? \\\"user\\\") as User[\\\"caller\\\"];\\n if (!id || !orgId) return null;\\n return { id, orgId, email, caller };\\n}\\n\\nexport function createContext(_opts: unknown, env: Env, req: Request) {\\n const user = readUser(req);\\n return { env, user };\\n}\\n```\\n\\nTrust these headers — the platform strips client-supplied versions\\nand reinjects authenticated ones at the perimeter. Never read\\n`Authorization` or session cookies directly.\\n\\n## `src/server/router.ts` — tRPC procedures with MCP meta\\n\\n```ts\\nimport { initTRPC } from \\\"@trpc/server\\\";\\nimport { z } from \\\"zod\\\";\\nimport { getDB, eq, desc, and } from \\\"@clawnify/db\\\";\\nimport * as schema from \\\"./schema\\\";\\nimport type { User } from \\\"./auth\\\";\\n\\nconst t = initTRPC.context<{ env: Env; user: User | null }>().create();\\n\\nconst authed = t.procedure.use(({ ctx, next }) => {\\n if (!ctx.user) throw new Error(\\\"UNAUTHORIZED\\\");\\n return next({ ctx: { ...ctx, user: ctx.user } });\\n});\\n\\nexport const appRouter = t.router({\\n list_notes: authed\\n .meta({ mcp: { name: \\\"list_notes\\\", description: \\\"List the user's notes.\\\" } })\\n .input(z.object({ limit: z.number().int().min(1).max(100).default(50) }))\\n .output(z.array(z.object({\\n id: z.number(),\\n title: z.string(),\\n body: z.string(),\\n tags: z.array(z.string()),\\n createdAt: z.string(),\\n })))\\n .query(async ({ ctx, input }) => {\\n const db = getDB(ctx.env, { schema });\\n return db\\n .select()\\n .from(schema.notes)\\n .where(eq(schema.notes.orgId, ctx.user.orgId))\\n .orderBy(desc(schema.notes.createdAt))\\n .limit(input.limit);\\n }),\\n\\n create_note: authed\\n .meta({ mcp: { name: \\\"create_note\\\", description: \\\"Create a new note.\\\" } })\\n .input(z.object({\\n title: z.string().min(1),\\n body: z.string().default(\\\"\\\"),\\n tags: z.array(z.string()).default([]),\\n }))\\n .mutation(async ({ ctx, input }) => {\\n const db = getDB(ctx.env, { schema });\\n const [row] = await db\\n .insert(schema.notes)\\n .values({ ...input, orgId: ctx.user.orgId })\\n .returning();\\n return row;\\n }),\\n});\\n\\nexport type AppRouter = typeof appRouter;\\n```\\n\\nPatterns to follow:\\n- **Every state-mutating procedure** that an agent might want to\\n call gets `.meta({ mcp: { name, description } })`. The build\\n picks these up into `clawnify.json api.tools[]`. The Clawnify\\n MCP gateway projects them as MCP tools.\\n- **Auth via middleware** (`authed`). Never check headers inside\\n a procedure body.\\n- **Filter by `ctx.user.orgId`** on every query. No exceptions.\\n- **Schema-validated input + output** with Zod. The output schema\\n is what the agent sees as the tool's return shape.\\n- **Procedure names are intent verbs** (`archive_old_notes`,\\n `publish_post`), not REST resource shapes (`get_notes`,\\n `update_note`). Tools describe what the agent wants to do.\\n\\n## `src/client` — React + tRPC + shadcn\\n\\n```tsx\\n// src/client/lib/trpc.ts\\nimport { createTRPCReact, httpBatchLink } from \\\"@trpc/react-query\\\";\\nimport type { AppRouter } from \\\"../../server/router\\\";\\n\\nexport const trpc = createTRPCReact<AppRouter>();\\nexport const trpcClient = trpc.createClient({\\n links: [httpBatchLink({ url: \\\"/trpc\\\" })],\\n});\\n```\\n\\n```tsx\\n// src/client/app.tsx\\nimport { useState } from \\\"react\\\";\\nimport { QueryClient, QueryClientProvider } from \\\"@tanstack/react-query\\\";\\nimport { trpc, trpcClient } from \\\"./lib/trpc\\\";\\nimport { Button } from \\\"./components/ui/button\\\";\\n\\nconst queryClient = new QueryClient();\\n\\nexport function App() {\\n return (\\n <trpc.Provider client={trpcClient} queryClient={queryClient}>\\n <QueryClientProvider client={queryClient}>\\n <NotesList />\\n </QueryClientProvider>\\n </trpc.Provider>\\n );\\n}\\n\\nfunction NotesList() {\\n const notes = trpc.list_notes.useQuery({ limit: 50 });\\n const create = trpc.create_note.useMutation({\\n onSuccess: () => notes.refetch(),\\n });\\n const [title, setTitle] = useState(\\\"\\\");\\n\\n return (\\n <div>\\n {notes.data?.map((n) => <div key={n.id}>{n.title}</div>)}\\n <Button onClick={() => create.mutate({ title, body: \\\"\\\" })}>\\n Add note\\n </Button>\\n </div>\\n );\\n}\\n```\\n\\nThe same tRPC procedures power the agent (via MCP) and the UI (via\\ntyped client). One backend, two front doors.\\n\\n## Design\\n\\nIf the project contains a `DESIGN.md`, it is the single source of\\ntruth for visuals — follow its tokens, don't restyle around it.\\nEither way, the rules every Clawnify app follows:\\n\\n- **Neutral chrome.** White canvas and surfaces, one text ramp\\n (foreground → muted → faint), hairline borders. Color is for\\n meaning, not decoration.\\n- **One primary CTA per screen**, using the theme's `primary` token.\\n Blue is reserved for links and focus rings; never a second accent.\\n- **Status colors are muted pairs** (`success` on `success-tint`,\\n etc.) — never pure-saturated fills.\\n- **Dark mode comes from the theme tokens** — don't hand-pick dark\\n colors.\\n- **Stick to shadcn/ui primitives** styled by the theme. Don't\\n install another component library or write a bespoke CSS system.\\n- **Sizes in rem**, so browser zoom and font settings are respected.\\n\\n## `clawnify.json` — the manifest\\n\\n```json\\n{\\n \\\"$schema\\\": \\\"https://app.clawnify.com/schema/v1/clawnify.json\\\",\\n \\\"version\\\": 1,\\n \\\"name\\\": \\\"Notes\\\",\\n \\\"description\\\": \\\"Take and organize notes. Searchable by tag.\\\",\\n \\\"icon\\\": \\\"icon.svg\\\",\\n \\\"tags\\\": [\\\"productivity\\\"],\\n \\\"app\\\": {\\n \\\"framework\\\": \\\"react+hono\\\",\\n \\\"database\\\": true,\\n \\\"storage\\\": false\\n },\\n \\\"env\\\": {\\n \\\"optional\\\": [\\\"OPENROUTER_API_KEY\\\"]\\n },\\n \\\"api\\\": {\\n \\\"public_routes\\\": [\\n { \\\"path\\\": \\\"/api/feed\\\", \\\"methods\\\": [\\\"GET\\\"] }\\n ]\\n }\\n}\\n```\\n\\nIf the app talks to third-party services the user has connected\\n(ads platforms, CRMs, messaging), declare them too:\\n\\n```json\\n{ \\\"app\\\": { \\\"credentials\\\": [\\\"metaads\\\", \\\"googleads\\\"] } }\\n```\\n\\n`env` supports `required` (deploy warns if missing), `optional`\\n(injected when available), and `oneOf` (at least one per group).\\n\\nRules:\\n- **Don't hand-edit `api.tools[]`** — generated at build from tRPC\\n `.meta({ mcp: { ... } })` annotations.\\n- **Public routes are the exception**, not the default. Every tRPC\\n procedure is private (auth-required) unless you explicitly add a\\n matching path to `public_routes`. Use only for webhooks, RSS,\\n embedded feeds.\\n- **`framework: \\\"react+hono\\\"`** for new apps. Never `preact+hono` or\\n `vite-preact` — those are legacy.\\n- **`database: true`** if the app uses a DB. Schema is generated\\n from `schema.ts` via drizzle-kit; no `schema.sql` to ship.\\n\\n## Connections & secrets — `@clawnify/connections`\\n\\nIf the app needs a third-party service or a provider API key, use\\nthe `@clawnify/connections` SDK. Never read credential bindings\\ndirectly, never paste API keys, never hardcode a token or endpoint.\\n\\n```ts\\nimport { connect, secret, describe, searchActions } from \\\"@clawnify/connections\\\";\\n\\n// A connected integration:\\nconst meta = connect(\\\"metaads\\\", env);\\nconst accounts = await meta.adAccounts(\\\"name,currency\\\");\\n\\n// A provider key the user supplied (null if absent):\\nconst key = secret(\\\"OPENROUTER_API_KEY\\\", env);\\n\\n// What's wired vs missing — drive your setup/empty state from this:\\nconst status = await describe(env, undefined, REQUIRES);\\n```\\n\\nHow to call a connected service — the mistake that silently breaks\\nintegration apps, so get it right:\\n\\n- **Prefer the typed client's semantic methods** where they exist\\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\\n- **For anything else, discover and run an action:**\\n ```ts\\n const [best] = await searchActions(\\\"list google ads campaigns\\\", env);\\n const data = await connect(best.service, env).run(best.slug, body);\\n ```\\n- Some integrations also expose a raw REST client\\n (`connect(\\\"bird\\\", env).get(\\\"/path\\\")`) — but if `.get()`/`.post()`\\n throws for a service, that service only supports semantic methods\\n and `run()`. When unsure, use `run()`.\\n- **Never fall back to raw `fetch`** against a provider API, and\\n never invent endpoints or guess tokens.\\n\\nBuild a `describe()`-driven setup state instead of assuming\\nconnections exist — show the user what's missing and where to\\nconnect it.\\n\\n## Migrations\\n\\nYou don't write migration SQL by hand. You don't even run a CLI\\ncommand. The workflow is:\\n\\n1. Edit `src/server/schema.ts` to reflect the new shape.\\n2. Restart `pnpm dev` (or it auto-restarts on save in some configs).\\n\\nThat's it. `clawnify dev` runs `drizzle-kit generate` under the\\nhood, applies the diff to local D1, and tracks what's been applied\\nin `.clawnify/applied-migrations.json` so reruns are no-ops.\\n\\nOn deploy, `clawnify deploy` does the same generate step, then the\\ndeploy pipeline applies the migrations transactionally to the live\\nand preview databases. Tracked in `__clawnify_migrations`.\\n\\nFor destructive changes (drop column, rename), Drizzle's generator\\nemits the SQL; the agent should default to additive changes and\\nonly do destructive ones when the user explicitly asks. Renames\\nare risky on production data — prefer \\\"add new column, backfill,\\nswitch queries, drop old column\\\" over a single-step rename.\\n\\n## What the agent must NOT do\\n\\n- Mount `/mcp` manually. The gateway projects tools from the\\n manifest.\\n- Author `schema.sql` by hand. Use `schema.ts`.\\n- Author migration SQL by hand. The CLI runs `drizzle-kit generate`\\n on dev + deploy. Never commit `drizzle/` or `.clawnify/drizzle/`.\\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\\n via Drizzle. The raw API has `json()` as a helper.\\n- Bind tRPC procedures by REST resource shape (`get_user_by_id`).\\n Use intent verbs (`onboard_user`, `archive_old_orders`).\\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\\n leak is the worst-class bug we can ship.\\n- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\\n the `X-Clawnify-*` headers via `auth.ts`.\\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\\n through `@clawnify/connections` (`connect` / `secret` / `run`).\\n- Install `drizzle-orm` as a separate top-level dependency.\\n `@clawnify/db@^0.4.0` pulls it in transitively; only add it if\\n you need to pin a specific version (rare).\\n\\n## What the agent SHOULD do\\n\\n- Import everything from `@clawnify/db` where possible\\n (`getDB`, `eq`, `and`, `sql`, `sqliteTable`, `text`, `integer`,\\n etc. are all re-exported there). Drop to `drizzle-orm` directly\\n only for things not re-exported.\\n- Add `.meta({ mcp: { name, description } })` to every state-\\n mutating procedure that the user's agent might want to call.\\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\\n publishing — the preview tier catches schema drift and\\n type errors at build time.\\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\\n README for the current API + version notes.\\n\\n## Schema-as-data exception\\n\\nApps that let END users define data shapes at runtime (CMS, no-code\\ntable editor) can't model their schema in `schema.ts` — the table\\ndefinitions live in rows. Those apps fall back to the raw SQL API\\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\\nthe canonical example.\\n\\nIf you're building this kind of app, you still use Drizzle's\\n`schema.ts` for the **registry** tables (content types, field\\ndefinitions). Only the dynamically-spawned per-collection tables\\nneed raw SQL. See open-cms's `src/server/schema-sync.ts` for the\\nruntime DDL pattern.\\n\",\n },\n {\n name: \"use-the-clawnify-cli\",\n description: \"Use the Clawnify CLI end-to-end — authenticate, scaffold, run locally, deploy apps and websites, link projects, manage orgs, and inspect deployed apps. Use when deploying to Clawnify from a terminal or wiring the CLI into scripts and coding agents.\",\n content: \"# Use the Clawnify CLI\\n\\nCanonical skill: how to drive the `clawnify` CLI. Same content for\\nhumans and for AI coding agents operating a terminal.\\n\\nFor **authoring app code** (stack, schema, tRPC patterns), use the\\n`build-a-clawnify-app` skill — this one covers the tooling around it.\\n\\n## TL;DR\\n\\n```bash\\nnpm i -g clawnify # or: npx clawnify@latest <command>\\nclawnify login # browser sign-in, paste-code fallback\\nclawnify init my-app # scaffold an app or website\\ncd my-app && clawnify dev\\nclawnify deploy # → https://<slug>.apps.clawnify.com\\n```\\n\\n- **Auth once, org lazily.** `login` only signs you in; the first\\n command that needs an organization asks once and remembers it.\\n- **A directory links to one app.** `deploy` from a linked directory\\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\\n- **Non-interactive flags exist for every prompt** — use them in\\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\\n\\n## Authenticate\\n\\n```bash\\nclawnify login # opens the browser; also prints the sign-in URL\\nclawnify whoami # current user, active org (if linked)\\n```\\n\\n`login` works from any browser: if the browser runs on the same\\nmachine, sign-in completes automatically; otherwise the page shows a\\ncode to paste back at the `Paste code here if prompted >` prompt\\n(useful over SSH — no port forwarding needed).\\n\\n### Organizations\\n\\nYou belong to one or more orgs; apps live inside an org.\\n\\n```bash\\nclawnify org list # orgs you belong to (* marks active)\\nclawnify org use <slug-or-id> # switch the active org\\n```\\n\\nNo need to pick one up front — the first org-scoped command prompts\\nonce and persists the choice. Any single command can override with\\n`--org <slug-or-id>`.\\n\\n## Create and run locally\\n\\n```bash\\nclawnify init [dir] # interactive: app or website\\nclawnify init my-app -y # non-interactive defaults (blank app)\\nclawnify init --type app --template crud --name my-app\\nclawnify init --type website --name my-site\\nclawnify dev [dir] [--port 8787] # local dev server\\n```\\n\\n`init` also installs AI files (rules + skills + MCP config) for any\\ncoding agents detected in the project; skip with `--no-ai-files`.\\n\\n## Deploy\\n\\n```bash\\nclawnify deploy # deploy the current directory\\nclawnify deploy path/to/app\\nclawnify deploy --from owner/repo # deploy straight from GitHub\\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\\nclawnify deploy --dry-run # list files that would upload\\n```\\n\\nFirst deploy creates the app and links the directory (writes a local\\nproject file); later deploys update the same app. On a slug conflict\\nyou'll be asked — or decide up front:\\n\\n```bash\\nclawnify deploy -y # reuse/update the existing app\\nclawnify deploy --update-existing # same, explicit\\nclawnify deploy --create-new # take the suggested new slug\\n```\\n\\nLink an existing deployed app to the current directory instead of\\ncreating a new one:\\n\\n```bash\\nclawnify link <app-id-or-slug>\\n```\\n\\n## Inspect and manage deployed apps\\n\\n```bash\\nclawnify ls # list deployed apps in the active org\\nclawnify logs <app-id> # build logs\\nclawnify open <slug> # open the live app in the browser\\nclawnify rm <app-id> # delete an app\\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\\nclawnify docs [slug] # usage README for an app (org index if omitted)\\n```\\n\\n`pull schema` refuses to clobber local uncommitted changes unless you\\npass `--force`.\\n\\n## Workspaces (one repo, one org's apps)\\n\\n```bash\\nclawnify workspace init [dir] [--org <slug-or-id>]\\n```\\n\\nScaffolds a monorepo bound to an org; apps scaffolded inside land\\nunder `apps/` and inherit the org on deploy.\\n\\n## Wire up coding agents\\n\\n```bash\\nclawnify ai-files install # rules + skills + MCP server in one step\\nclawnify skills list # bundled skills\\nclawnify skills add <name> # install one into detected agents\\nclawnify mcp # stdio MCP bridge (Claude Desktop, etc.)\\n```\\n\\n`ai-files install` detects agent config dirs in the project (Claude\\nCode, Cursor, OpenClaw, Codex, Aider) and writes the always-on rules\\nblock, installs bundled skills, and adds the Clawnify MCP server to\\n`.mcp.json`. Target one agent with `--agent <name>`; undo with\\n`clawnify ai-files uninstall`.\\n\\n## Tips\\n\\n- `npx clawnify@latest <command>` always runs the newest release.\\n- Every org-scoped command accepts `--org` — prefer it in scripts over\\n relying on the saved active org.\\n- If sign-in ever fails mid-flow, just run `clawnify login` again; it\\n is safe to repeat.\\n\",\n }\n];\n\nexport const RULES_CONTENT = \"You are working inside a **Clawnify app** — a full-stack project that deploys to\\nCloudflare through the Clawnify platform. Follow these rules.\\n\\n## Stack (fixed — do not swap)\\n\\n- **Frontend:** React 19 + Tailwind v4, built with Vite.\\n- **API:** Hono (`@hono/zod-openapi`) running on Cloudflare Workers.\\n- **Database:** D1 (SQLite at the edge) via `@clawnify/db` (Drizzle).\\n\\nOne app = one `clawnify.json` manifest at the repo root. Don't introduce other\\nframeworks, ORMs, or hosting targets.\\n\\n## The schema lives in `src/server/schema.ts`\\n\\n- Define tables with the Drizzle DSL there — it is the single source of truth.\\n- **Never** hand-write SQL migrations or edit a `schema.sql` by hand. `clawnify\\n dev` and `clawnify deploy` run `drizzle-kit generate` for you.\\n- Every user-facing table needs an `org_id` column, and every query must filter\\n by the `X-Clawnify-Org-Id` request header. This is how multi-tenancy works —\\n there are no exceptions.\\n\\n## Identity comes from request headers, never the client\\n\\nThe platform injects identity headers the client cannot forge:\\n`X-Clawnify-User-Id`, `X-Clawnify-Org-Id`, `X-Clawnify-User-Email`,\\n`X-Clawnify-Caller`. Read them server-side. Never trust a client-supplied user\\nor org id.\\n\\n## Integrations: use `@clawnify/connections`\\n\\nDon't store per-service API keys or OAuth secrets in the app. Declare what the\\napp needs under `app.credentials` in `clawnify.json`, then call\\n`connect(service, env)` and `secret(name, env)` from the SDK. Off-platform\\n(local dev, scripts), put a `clw_` org service token in `.dev.vars` as\\n`CLAWNIFY_TOKEN` — the SDK then resolves your **real** org connections over HTTP\\nwith no per-service secrets.\\n\\n## Commands\\n\\n- `clawnify dev` — local dev server. D1 runs as local SQLite, identical to\\n production. Leave it running in a separate terminal so generated types stay\\n fresh.\\n- `clawnify deploy` — ships the app live at `https://<slug>.apps.clawnify.com`.\\n- Don't invoke raw `wrangler` or `drizzle-kit` — the CLI wraps them. Editing\\n `schema.ts` and running `clawnify dev`/`deploy` is the whole workflow.\\n\\n## Going deeper\\n\\nFor the full gold-standard structure — routing, OpenAPI route definitions,\\nclient data-fetching patterns, file uploads — read the **build-a-clawnify-app**\\nskill installed alongside these rules.\\n\";\n","/**\n * Write a bundled skill into an agent's expected location, formatted\n * for that agent's convention. Each agent ships skills slightly\n * differently — same content underneath, different wrapper.\n *\n * Version pinning: every installed file carries an HTML comment header\n * `<!-- clawnify-skill: <name> v<X.Y.Z> -->`. On reinstall we read that\n * header; if the version matches the CLI's current version, we skip\n * (no-op idempotency). If it differs, we overwrite — the user is\n * implicitly upgrading by re-running after a CLI bump.\n */\n\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n statSync,\n rmSync,\n unlinkSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CLI_VERSION, type BundledSkill } from \"./content.gen.js\";\nimport type { DetectedAgent } from \"./detect.js\";\n\nconst VERSION_HEADER_RE = /<!--\\s*clawnify-skill:\\s*([\\w-]+)\\s+v([\\d.]+)\\s*-->/;\n\nfunction versionHeader(name: string): string {\n return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;\n}\n\nfunction readExistingVersion(path: string): string | null {\n if (!existsSync(path)) return null;\n try {\n const head = readFileSync(path, \"utf8\").slice(0, 500);\n const match = head.match(VERSION_HEADER_RE);\n return match ? match[2] : null;\n } catch {\n return null;\n }\n}\n\nexport type InstallStatus =\n | { status: \"installed\"; path: string }\n | { status: \"updated\"; path: string; previousVersion: string }\n | { status: \"skipped\"; path: string; reason: string };\n\nexport function installSkill(\n skill: BundledSkill,\n agent: DetectedAgent,\n cwd: string,\n): InstallStatus {\n switch (agent.agent) {\n case \"claude\":\n return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);\n case \"codex\":\n return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);\n case \"openclaw\":\n return writeOpenclawSkill(skill, cwd, agent.target);\n case \"cursor\":\n return writeCursorRule(skill, cwd, agent.target);\n case \"aider\":\n return writeAiderSection(skill, cwd, agent.target);\n }\n}\n\n// ── Claude Code / Codex: <target>/<name>/SKILL.md ─────────────────────\n// Both follow the same convention: a skill directory containing\n// SKILL.md. Frontmatter carries name + description so the agent's\n// indexer picks it up.\n\nfunction formatClaudeSkill(skill: BundledSkill): string {\n return `${versionHeader(skill.name)}\n---\nname: ${skill.name}\ndescription: ${JSON.stringify(skill.description)}\n---\n\n${skill.content}`;\n}\n\nfunction formatCodexSkill(skill: BundledSkill): string {\n // Codex SKILL.md uses the same frontmatter shape as Claude — keeps the\n // wrapper consistent so the underlying doc stays portable.\n return formatClaudeSkill(skill);\n}\n\nfunction writeSkillDir(\n skill: BundledSkill,\n cwd: string,\n targetDir: string,\n format: (s: BundledSkill) => string,\n): InstallStatus {\n const skillDir = join(cwd, targetDir, skill.name);\n const filePath = join(skillDir, \"SKILL.md\");\n const existing = readExistingVersion(filePath);\n if (existing === CLI_VERSION) {\n return { status: \"skipped\", path: filePath, reason: `already at v${CLI_VERSION}` };\n }\n mkdirSync(skillDir, { recursive: true });\n writeFileSync(filePath, format(skill));\n return existing\n ? { status: \"updated\", path: filePath, previousVersion: existing }\n : { status: \"installed\", path: filePath };\n}\n\n// ── OpenClaw: <target>/<name>/SKILL.md + skill.json ───────────────────\n\nfunction writeOpenclawSkill(\n skill: BundledSkill,\n cwd: string,\n targetDir: string,\n): InstallStatus {\n const skillDir = join(cwd, targetDir, skill.name);\n const mdPath = join(skillDir, \"SKILL.md\");\n const jsonPath = join(skillDir, \"skill.json\");\n const existing = readExistingVersion(mdPath);\n if (existing === CLI_VERSION) {\n return { status: \"skipped\", path: mdPath, reason: `already at v${CLI_VERSION}` };\n }\n mkdirSync(skillDir, { recursive: true });\n writeFileSync(mdPath, `${versionHeader(skill.name)}\n${skill.content}`);\n writeFileSync(\n jsonPath,\n JSON.stringify(\n {\n name: skill.name,\n displayName: skill.name\n .split(\"-\")\n .map((p) => p[0].toUpperCase() + p.slice(1))\n .join(\" \"),\n description: skill.description,\n trigger: \"manual\",\n inputs: [],\n },\n null,\n 2,\n ),\n );\n return existing\n ? { status: \"updated\", path: mdPath, previousVersion: existing }\n : { status: \"installed\", path: mdPath };\n}\n\n// ── Cursor: .cursor/rules/<name>.mdc ──────────────────────────────────\n\nfunction writeCursorRule(\n skill: BundledSkill,\n cwd: string,\n targetDir: string,\n): InstallStatus {\n const dir = join(cwd, targetDir);\n const filePath = join(dir, `${skill.name}.mdc`);\n const existing = readExistingVersion(filePath);\n if (existing === CLI_VERSION) {\n return { status: \"skipped\", path: filePath, reason: `already at v${CLI_VERSION}` };\n }\n mkdirSync(dir, { recursive: true });\n const body = `${versionHeader(skill.name)}\n---\ndescription: ${JSON.stringify(skill.description)}\nalwaysApply: false\n---\n\n${skill.content}`;\n writeFileSync(filePath, body);\n return existing\n ? { status: \"updated\", path: filePath, previousVersion: existing }\n : { status: \"installed\", path: filePath };\n}\n\n// ── Aider: append a section to CONVENTIONS.md ─────────────────────────\n// Aider doesn't have a per-skill directory model — its convention is a\n// single CONVENTIONS.md the user --reads into context. We append a\n// marker-delimited section so reruns replace cleanly.\n\nfunction writeAiderSection(\n skill: BundledSkill,\n cwd: string,\n targetFile: string,\n): InstallStatus {\n const filePath = join(cwd, targetFile);\n const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;\n const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;\n const section = `${startMarker}\n${versionHeader(skill.name)}\n${skill.content}\n${endMarker}\n`;\n\n let existing = \"\";\n let existingVersion: string | null = null;\n if (existsSync(filePath)) {\n existing = readFileSync(filePath, \"utf8\");\n const sectionRe = new RegExp(\n `${escapeRe(startMarker)}[\\\\s\\\\S]*?${escapeRe(endMarker)}\\\\n?`,\n );\n const sectionMatch = existing.match(sectionRe);\n if (sectionMatch) {\n const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);\n existingVersion = headMatch ? headMatch[2] : null;\n if (existingVersion === CLI_VERSION) {\n return { status: \"skipped\", path: filePath, reason: `already at v${CLI_VERSION}` };\n }\n // Replace the existing section in place.\n const next = existing.replace(sectionRe, section);\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, next);\n return existingVersion\n ? { status: \"updated\", path: filePath, previousVersion: existingVersion }\n : { status: \"installed\", path: filePath };\n }\n }\n\n // No existing section — append (creating the file if needed).\n mkdirSync(dirname(filePath), { recursive: true });\n const prefix = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n writeFileSync(filePath, existing + prefix + section);\n return { status: \"installed\", path: filePath };\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Remove a skill installation from an agent's target. Returns true if\n * something was removed.\n */\nexport function removeSkill(\n skillName: string,\n agent: DetectedAgent,\n cwd: string,\n): boolean {\n if (agent.agent === \"aider\") {\n const filePath = join(cwd, agent.target);\n if (!existsSync(filePath)) return false;\n const content = readFileSync(filePath, \"utf8\");\n const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;\n const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;\n const sectionRe = new RegExp(\n `${escapeRe(startMarker)}[\\\\s\\\\S]*?${escapeRe(endMarker)}\\\\n?`,\n );\n if (!sectionRe.test(content)) return false;\n writeFileSync(filePath, content.replace(sectionRe, \"\"));\n return true;\n }\n\n if (agent.agent === \"cursor\") {\n const candidate = join(cwd, agent.target, `${skillName}.mdc`);\n if (!existsSync(candidate)) return false;\n unlinkSync(candidate);\n return true;\n }\n\n // Directory-based agents (claude, codex, openclaw): blow away the whole\n // skill dir. Small contents (SKILL.md + maybe skill.json), safe to rm -r.\n const dir = join(cwd, agent.target, skillName);\n if (!existsSync(dir)) return false;\n try {\n const s = statSync(dir);\n if (!s.isDirectory()) return false;\n } catch {\n return false;\n }\n rmSync(dir, { recursive: true, force: true });\n return true;\n}\n","/**\n * Write Clawnify's always-on \"rules\" block into an agent's main rules\n * file (CLAUDE.md, AGENTS.md, …). This is the always-in-context layer —\n * distinct from `clawnify skills add`, which installs on-demand skills.\n *\n * The block is marker-delimited and version-pinned so reruns replace it\n * in place rather than appending duplicates. Like skills, the content is\n * bundled in the CLI and only changes when the CLI version changes —\n * re-run `ai-files install` after `npm i -g clawnify@latest` to upgrade.\n */\n\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CLI_VERSION, RULES_CONTENT } from \"../skills/content.gen.js\";\nimport type { Agent } from \"../skills/detect.js\";\n\n/** Where each agent reads its always-on instructions. */\nexport const RULES_FILE: Record<Agent, string> = {\n claude: \"CLAUDE.md\",\n cursor: \".cursorrules\",\n openclaw: \"AGENTS.md\",\n codex: \"AGENTS.md\",\n aider: \"CONVENTIONS.md\",\n};\n\nconst START = \"<!-- clawnify:rules:start -->\";\nconst END = \"<!-- clawnify:rules:end -->\";\nconst VERSION_RE = /<!--\\s*clawnify:rules\\s+v([\\d.]+)\\s*-->/;\n\nfunction block(): string {\n return `${START}\n<!-- clawnify:rules v${CLI_VERSION} -->\n${RULES_CONTENT.trimEnd()}\n${END}\n`;\n}\n\nexport type RulesStatus =\n | { status: \"installed\"; file: string }\n | { status: \"updated\"; file: string; previousVersion: string }\n | { status: \"skipped\"; file: string; reason: string };\n\n/**\n * Insert or refresh the rules block in `<cwd>/<file>`. Creates the file\n * if it doesn't exist.\n */\nexport function writeRules(cwd: string, file: string): RulesStatus {\n const filePath = join(cwd, file);\n const section = block();\n const sectionRe = new RegExp(`${escapeRe(START)}[\\\\s\\\\S]*?${escapeRe(END)}\\\\n?`);\n\n if (existsSync(filePath)) {\n const existing = readFileSync(filePath, \"utf8\");\n const match = existing.match(sectionRe);\n if (match) {\n const versionMatch = match[0].match(VERSION_RE);\n const previousVersion = versionMatch ? versionMatch[1] : null;\n if (previousVersion === CLI_VERSION) {\n return { status: \"skipped\", file: filePath, reason: `already at v${CLI_VERSION}` };\n }\n writeFileSync(filePath, existing.replace(sectionRe, section));\n return previousVersion\n ? { status: \"updated\", file: filePath, previousVersion }\n : { status: \"installed\", file: filePath };\n }\n // File exists but has no block — append after a blank line.\n const prefix = existing.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n writeFileSync(filePath, existing + prefix + section);\n return { status: \"installed\", file: filePath };\n }\n\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, section);\n return { status: \"installed\", file: filePath };\n}\n\n/** Strip the rules block from `<cwd>/<file>`. Returns true if removed. */\nexport function removeRules(cwd: string, file: string): boolean {\n const filePath = join(cwd, file);\n if (!existsSync(filePath)) return false;\n const existing = readFileSync(filePath, \"utf8\");\n const sectionRe = new RegExp(`\\\\n?${escapeRe(START)}[\\\\s\\\\S]*?${escapeRe(END)}\\\\n?`);\n if (!sectionRe.test(existing)) return false;\n const next = existing.replace(sectionRe, \"\\n\").replace(/^\\n+/, \"\").trimEnd();\n if (next) {\n writeFileSync(filePath, next + \"\\n\");\n } else {\n // Our block was the file's only content — don't leave a 0-byte file.\n unlinkSync(filePath);\n }\n return true;\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","/**\n * Wire the Clawnify MCP server into a project-scoped `.mcp.json` so\n * Claude Code (and other clients that read project MCP config) pick it\n * up automatically — no hand-running `claude mcp add`.\n *\n * The server entry runs the CLI's bundled local MCP server\n * (`clawnify --mcp`), which exposes deploy / list_apps / get_app /\n * delete_app. Merge is idempotent: an existing `.mcp.json` is preserved,\n * only the `clawnify` server is added or refreshed.\n */\n\nimport { existsSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nconst FILE = \".mcp.json\";\n\nconst SERVER = {\n command: \"npx\",\n args: [\"clawnify\", \"--mcp\"],\n};\n\nexport type McpStatus =\n | { status: \"installed\"; file: string }\n | { status: \"updated\"; file: string }\n | { status: \"skipped\"; file: string; reason: string };\n\ninterface McpConfig {\n mcpServers?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport function writeMcpConfig(cwd: string): McpStatus {\n const filePath = join(cwd, FILE);\n\n let config: McpConfig = {};\n let existed = false;\n if (existsSync(filePath)) {\n existed = true;\n try {\n config = JSON.parse(readFileSync(filePath, \"utf8\")) as McpConfig;\n } catch {\n return { status: \"skipped\", file: filePath, reason: \"existing .mcp.json is not valid JSON\" };\n }\n }\n\n config.mcpServers ??= {};\n const current = config.mcpServers[\"clawnify\"];\n if (current && JSON.stringify(current) === JSON.stringify(SERVER)) {\n return { status: \"skipped\", file: filePath, reason: \"already configured\" };\n }\n\n const wasPresent = current !== undefined;\n config.mcpServers[\"clawnify\"] = SERVER;\n writeFileSync(filePath, JSON.stringify(config, null, 2) + \"\\n\");\n return existed && wasPresent\n ? { status: \"updated\", file: filePath }\n : { status: \"installed\", file: filePath };\n}\n\n/** Remove the clawnify server from `.mcp.json`. Returns true if removed. */\nexport function removeMcpConfig(cwd: string): boolean {\n const filePath = join(cwd, FILE);\n if (!existsSync(filePath)) return false;\n let config: McpConfig;\n try {\n config = JSON.parse(readFileSync(filePath, \"utf8\")) as McpConfig;\n } catch {\n return false;\n }\n if (!config.mcpServers || !((\"clawnify\") in config.mcpServers)) return false;\n delete config.mcpServers[\"clawnify\"];\n // Drop an empty mcpServers object so we don't leave clutter behind.\n if (Object.keys(config.mcpServers).length === 0) delete config.mcpServers;\n // If nothing else is left, our entry was the file's only content — remove it\n // rather than leaving a meaningless `{}`.\n if (Object.keys(config).length === 0) {\n unlinkSync(filePath);\n } else {\n writeFileSync(filePath, JSON.stringify(config, null, 2) + \"\\n\");\n }\n return true;\n}\n","/**\n * `clawnify ai-files install` — make a project agent-ready in one step.\n *\n * Mirrors the `npx convex ai-files install` pattern: writes Clawnify's\n * always-on rules block into each detected agent's rules file, installs\n * the bundled Clawnify skills, and wires the Clawnify MCP server into a\n * project `.mcp.json`. Re-running after a CLI upgrade refreshes all three\n * in place. `ai-files uninstall` strips them back out.\n */\n\nimport { SKILLS, CLI_VERSION } from \"../lib/skills/registry.js\";\nimport {\n agentByName,\n detectAgents,\n ALL_AGENTS,\n type Agent,\n type DetectedAgent,\n} from \"../lib/skills/detect.js\";\nimport { installSkill, removeSkill } from \"../lib/skills/install.js\";\nimport { writeRules, removeRules, RULES_FILE } from \"../lib/ai-files/rules.js\";\nimport { writeMcpConfig, removeMcpConfig } from \"../lib/ai-files/mcp.js\";\n\ninterface InstallOptions {\n agent?: string;\n mcp?: boolean; // commander sets this false for --no-mcp\n}\n\ninterface UninstallOptions {\n agent?: string;\n}\n\n/**\n * Resolve which agents to target. Explicit `--agent` wins; otherwise we\n * detect agents in the directory; if none are present we default to\n * Claude (writing CLAUDE.md) so a freshly-scaffolded app still becomes\n * agent-ready — matching Convex's CLAUDE.md-centric default.\n */\nfunction resolveAgents(cwd: string, forced: string | undefined): { agents: DetectedAgent[]; defaulted: boolean } {\n if (forced) {\n if (!ALL_AGENTS.includes(forced as Agent)) {\n console.error(`Unknown agent: ${forced}\\nValid: ${ALL_AGENTS.join(\", \")}`);\n process.exit(1);\n }\n return { agents: [agentByName(forced as Agent)], defaulted: false };\n }\n const detected = detectAgents(cwd);\n if (detected.length > 0) return { agents: detected, defaulted: false };\n return { agents: [agentByName(\"claude\")], defaulted: true };\n}\n\ninterface InstallResult {\n rules: number;\n skills: number;\n mcp: boolean;\n}\n\n/**\n * Core install logic, shared by the command and by `clawnify init`'s\n * post-scaffold hook. Writes rules + skills + (optionally) MCP config,\n * logging each touched path. Returns a small tally.\n */\nexport function installAiFiles(\n cwd: string,\n agents: DetectedAgent[],\n opts: { mcp: boolean },\n): InstallResult {\n // Rules — dedupe by target file (codex + openclaw both use AGENTS.md).\n const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];\n let rules = 0;\n for (const file of rulesFiles) {\n const r = writeRules(cwd, file);\n if (r.status === \"skipped\") {\n console.log(` · rules → ${r.file} (${r.reason})`);\n } else if (r.status === \"updated\") {\n console.log(` ↑ rules → ${r.file} (v${r.previousVersion} → v${CLI_VERSION})`);\n rules++;\n } else {\n console.log(` ✓ rules → ${r.file}`);\n rules++;\n }\n }\n\n // Skills — install every bundled skill into every target agent.\n let skills = 0;\n for (const skill of SKILLS) {\n for (const agent of agents) {\n const s = installSkill(skill, agent, cwd);\n if (s.status === \"skipped\") {\n console.log(` · skill ${skill.name} → ${s.path} (${s.reason})`);\n } else if (s.status === \"updated\") {\n console.log(` ↑ skill ${skill.name} → ${s.path} (v${s.previousVersion} → v${CLI_VERSION})`);\n skills++;\n } else {\n console.log(` ✓ skill ${skill.name} → ${s.path}`);\n skills++;\n }\n }\n }\n\n // MCP server config.\n let mcp = false;\n if (opts.mcp) {\n const m = writeMcpConfig(cwd);\n if (m.status === \"skipped\") {\n console.log(` · mcp → ${m.file} (${m.reason})`);\n } else {\n console.log(` ${m.status === \"updated\" ? \"↑\" : \"✓\"} mcp → ${m.file}`);\n mcp = true;\n }\n }\n\n return { rules, skills, mcp };\n}\n\nexport async function aiFilesInstallCommand(opts: InstallOptions): Promise<void> {\n const cwd = process.cwd();\n const { agents, defaulted } = resolveAgents(cwd, opts.agent);\n\n console.log(`Installing Clawnify AI files (CLI v${CLI_VERSION}):`);\n if (defaulted) {\n console.log(\" No coding agent detected — defaulting to Claude (CLAUDE.md).\");\n }\n console.log(` Agents: ${agents.map((a) => a.agent).join(\", \")}\\n`);\n\n installAiFiles(cwd, agents, { mcp: opts.mcp !== false });\n\n console.log(\"\\nDone. Your project is agent-ready.\");\n console.log(\"Tip: leave `clawnify dev` running so generated types stay fresh.\");\n}\n\nexport async function aiFilesUninstallCommand(opts: UninstallOptions): Promise<void> {\n const cwd = process.cwd();\n // For uninstall, only touch what's actually present — detect, plus the\n // explicit override. Don't default to claude (nothing to guess at).\n const agents = opts.agent\n ? resolveAgents(cwd, opts.agent).agents\n : detectAgents(cwd);\n\n let removed = 0;\n const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];\n for (const file of rulesFiles) {\n if (removeRules(cwd, file)) {\n console.log(` ✗ rules removed from ${file}`);\n removed++;\n }\n }\n for (const skill of SKILLS) {\n for (const agent of agents) {\n if (removeSkill(skill.name, agent, cwd)) {\n console.log(` ✗ skill ${skill.name} removed from ${agent.agent}`);\n removed++;\n }\n }\n }\n if (removeMcpConfig(cwd)) {\n console.log(\" ✗ clawnify server removed from .mcp.json\");\n removed++;\n }\n\n console.log(`\\nDone — removed ${removed} item${removed === 1 ? \"\" : \"s\"}.`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { readManifest } from \"../lib/config.js\";\n\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 30);\n}\n\nfunction generateWranglerToml(slug: string, opts: { database: boolean; storage: boolean }): string {\n let toml = `name = \"${slug}\"\nmain = \"../src/server/index.ts\"\ncompatibility_date = \"2025-04-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n`;\n if (opts.database) {\n toml += `\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"${slug}-db\"\ndatabase_id = \"local\"\n`;\n }\n if (opts.storage) {\n toml += `\n[[r2_buckets]]\nbinding = \"UPLOADS\"\nbucket_name = \"${slug}-uploads\"\n`;\n }\n return toml;\n}\n\nfunction assertNodeVersion() {\n const [major] = process.versions.node.split(\".\").map(Number);\n if (major < 22) {\n console.error(\n `\\n Clawnify requires Node.js v22 or later.\\n` +\n ` You are using v${process.versions.node}.\\n\\n` +\n ` Install a newer version: https://nodejs.org\\n` +\n ` Or use a version manager: nvm use 22\\n`\n );\n process.exit(1);\n }\n}\n\nexport async function devCommand(dir?: string, options?: { port?: string }): Promise<void> {\n assertNodeVersion();\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const manifest = readManifest(resolvedDir);\n\n if (!manifest) {\n console.error(\"No clawnify.json found. Run `clawnify init` first.\");\n process.exit(1);\n }\n\n if (!manifest.app) {\n console.error(\n \"`clawnify dev` is for app projects only. For a website, run `pnpm dev` (astro dev) directly.\",\n );\n process.exit(1);\n }\n\n const slug = slugify(manifest.name);\n const database = manifest.app.database !== false;\n const storage = manifest.app.storage === true;\n const apiPort = options?.port || \"8787\";\n\n // Generate wrangler config in .clawnify/\n const clawnifyDir = path.join(resolvedDir, \".clawnify\");\n fs.mkdirSync(clawnifyDir, { recursive: true });\n const wranglerPath = path.join(clawnifyDir, \"wrangler.toml\");\n fs.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));\n\n // Apply schema to local D1. Two paths, preferred order:\n //\n // 1. schema.ts + drizzle.config.ts (new, gold-standard):\n // Run drizzle-kit generate to emit migrations into\n // .clawnify/drizzle/, then apply unapplied .sql files via\n // wrangler d1 execute --local. Track applied state in\n // .clawnify/applied-migrations.json so reruns are idempotent.\n // The user/agent only ever edits schema.ts.\n //\n // 2. schema.sql (legacy): apply directly. This is what older\n // scaffolds shipped before drizzle support. Kept so existing\n // apps don't regress.\n if (database) {\n const schemaTsPath = path.join(resolvedDir, \"src/server/schema.ts\");\n const drizzleConfigPath = path.join(resolvedDir, \"drizzle.config.ts\");\n if (fs.existsSync(schemaTsPath) && fs.existsSync(drizzleConfigPath)) {\n await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath);\n } else {\n const schemaCandidates = [\n path.join(resolvedDir, \"schema.sql\"),\n path.join(resolvedDir, \"src/server/schema.sql\"),\n ];\n const schemaPath = schemaCandidates.find((p) => fs.existsSync(p));\n if (schemaPath) {\n await runQuiet(resolvedDir, \"npx\", [\n \"wrangler\", \"d1\", \"execute\", `${slug}-db`,\n \"--local\", `--file=${schemaPath}`,\n `--config=${wranglerPath}`,\n ]);\n }\n }\n }\n\n console.log();\n console.log(` ${manifest.name} dev server`);\n console.log();\n console.log(` UI: http://localhost:5173`);\n console.log(` API: http://localhost:${apiPort}`);\n console.log();\n\n // Spawn vite (frontend) and wrangler dev (API) in parallel\n const vite = spawn(\"npx\", [\"vite\"], {\n cwd: resolvedDir,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n\n const wrangler = spawn(\"npx\", [\n \"wrangler\", \"dev\",\n `--port=${apiPort}`,\n `--config=${wranglerPath}`,\n ], {\n cwd: resolvedDir,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n\n // Filter output — suppress noisy wrangler/vite startup lines, show errors\n const filterVite = createFilter(\"ui\");\n const filterWrangler = createFilter(\"api\");\n\n vite.stdout?.on(\"data\", filterVite);\n vite.stderr?.on(\"data\", filterVite);\n wrangler.stdout?.on(\"data\", filterWrangler);\n wrangler.stderr?.on(\"data\", filterWrangler);\n\n // Handle exit\n const cleanup = () => {\n vite.kill();\n wrangler.kill();\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Exit when either process exits\n const exitPromise = Promise.race([\n new Promise<number>((resolve) => vite.on(\"exit\", (code) => resolve(code ?? 1))),\n new Promise<number>((resolve) => wrangler.on(\"exit\", (code) => resolve(code ?? 1))),\n ]);\n\n const code = await exitPromise;\n cleanup();\n process.exit(code);\n}\n\nfunction createFilter(label: string): (data: Buffer) => void {\n // Suppress wrangler banner, version lines, \"Ready on\" (we already printed URLs)\n const suppress = [\n /^\\s*⛅️/,\n /^\\s*wrangler\\s/,\n /^Starting local server/,\n /^Ready on http/,\n /^\\s*\\[mf:inf\\]/,\n /^\\s*╭/,\n /^\\s*│/,\n /^\\s*╰/,\n /^\\s*$/,\n // Vite startup noise\n /VITE v/,\n /ready in \\d+/,\n /Local:\\s+http/,\n /Network:/,\n /press h \\+ enter/,\n ];\n\n return (data: Buffer) => {\n const lines = data.toString().split(\"\\n\");\n for (const line of lines) {\n if (!line.trim()) continue;\n if (suppress.some((re) => re.test(line))) continue;\n // Show meaningful output with label\n console.log(` ${label} │ ${line}`);\n }\n };\n}\n\nfunction runQuiet(cwd: string, cmd: string, args: string[]): Promise<void> {\n return new Promise((resolve, reject) => {\n const proc = spawn(cmd, args, {\n cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n\n let stderr = \"\";\n proc.stderr?.on(\"data\", (d: Buffer) => { stderr += d.toString(); });\n\n proc.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else {\n console.error(` Schema init failed: ${stderr.trim()}`);\n reject(new Error(`Command exited with code ${code}`));\n }\n });\n });\n}\n\n/**\n * Ensure local D1 matches the current schema.ts via drizzle-kit.\n *\n * The contract we expose to the user is: edit schema.ts, run\n * `pnpm dev`, it just works. They never touch migration SQL by hand.\n *\n * Flow:\n * 1. `drizzle-kit generate` (writes new migrations under\n * .clawnify/drizzle/ per drizzle.config.ts). No-op if schema.ts\n * hasn't changed since the last generate.\n * 2. Read .clawnify/applied-migrations.json (or []) — the list of\n * .sql files we've already applied to this local D1.\n * 3. For each .sql file in .clawnify/drizzle/ not yet in the list,\n * apply via `wrangler d1 execute --local`, then record it.\n * 4. Write the updated list back.\n *\n * Per-app local state. Each dev's local D1 has its own applied list;\n * production D1 has its own tracking in __clawnify_migrations\n * (handled server-side by the deploy pipeline).\n */\nasync function syncDrizzleToLocalD1(\n resolvedDir: string,\n clawnifyDir: string,\n slug: string,\n wranglerPath: string,\n): Promise<void> {\n try {\n await runQuiet(resolvedDir, \"npx\", [\"drizzle-kit\", \"generate\"]);\n } catch (err) {\n console.error(\n ` drizzle-kit generate failed. Is \\`drizzle-kit\\` in devDependencies?\\n ${(err as Error).message}`,\n );\n throw err;\n }\n\n const drizzleDir = path.join(clawnifyDir, \"drizzle\");\n if (!fs.existsSync(drizzleDir)) return; // nothing to apply yet\n\n const sqlFiles = fs\n .readdirSync(drizzleDir)\n .filter((name) => name.endsWith(\".sql\"))\n .sort();\n if (sqlFiles.length === 0) return;\n\n const appliedPath = path.join(clawnifyDir, \"applied-migrations.json\");\n let applied: string[] = [];\n if (fs.existsSync(appliedPath)) {\n try {\n applied = JSON.parse(fs.readFileSync(appliedPath, \"utf8\")) as string[];\n if (!Array.isArray(applied)) applied = [];\n } catch {\n applied = [];\n }\n }\n const appliedSet = new Set(applied);\n\n for (const file of sqlFiles) {\n if (appliedSet.has(file)) continue;\n const filePath = path.join(drizzleDir, file);\n await runQuiet(resolvedDir, \"npx\", [\n \"wrangler\", \"d1\", \"execute\", `${slug}-db`,\n \"--local\", `--file=${filePath}`,\n `--config=${wranglerPath}`,\n ]);\n applied.push(file);\n }\n\n fs.writeFileSync(appliedPath, JSON.stringify(applied, null, 2) + \"\\n\");\n}\n","import path from \"node:path\";\nimport { api, listMyOrgs, type Org } from \"../lib/api.js\";\nimport { saveProject } from \"../lib/config.js\";\n\ninterface AppDetail {\n id: string;\n name: string;\n slug: string;\n app_token: string;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nasync function findByAppId(orgs: Org[], appId: string) {\n for (const org of orgs) {\n const res = await api.get(`/v1/apps/${appId}`, { orgId: org.id });\n if (res.ok) {\n return { app: (await res.json()) as AppDetail, org };\n }\n if (res.status !== 404) {\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Link failed (${org.name}): ${err.error || res.statusText}`);\n process.exit(1);\n }\n }\n return null;\n}\n\nasync function findBySlug(orgs: Org[], slug: string) {\n for (const org of orgs) {\n const res = await api.get(`/v1/apps`, { orgId: org.id });\n if (!res.ok) {\n if (res.status === 404) continue;\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Link failed (${org.name}): ${err.error || res.statusText}`);\n process.exit(1);\n }\n const payload = (await res.json()) as { apps: AppDetail[] } | AppDetail[];\n const apps = Array.isArray(payload) ? payload : payload.apps;\n const match = apps.find((a) => a.slug === slug);\n if (match) {\n // Re-fetch by id to get app_token (list endpoint may omit it).\n const detailRes = await api.get(`/v1/apps/${match.id}`, { orgId: org.id });\n if (detailRes.ok) {\n return { app: (await detailRes.json()) as AppDetail, org };\n }\n return { app: match, org };\n }\n }\n return null;\n}\n\nexport async function linkCommand(\n appIdOrSlug: string,\n options?: { dir?: string; org?: string },\n): Promise<void> {\n const dir = options?.dir ? path.resolve(options.dir) : process.cwd();\n\n const orgs = await listMyOrgs();\n if (orgs.length === 0) {\n console.error(\"No organizations found. Run `clawnify login` first.\");\n process.exit(1);\n }\n\n const candidates = options?.org\n ? orgs.filter((o) => o.id === options.org || o.slug === options.org)\n : orgs;\n\n if (candidates.length === 0) {\n console.error(\n `No org matched \"${options?.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(1);\n }\n\n const isUuid = UUID_RE.test(appIdOrSlug);\n const matched = isUuid\n ? await findByAppId(candidates, appIdOrSlug)\n : await findBySlug(candidates, appIdOrSlug);\n\n if (!matched) {\n const kind = isUuid ? \"id\" : \"slug\";\n console.error(\n `App with ${kind} '${appIdOrSlug}' not found in ${candidates.map((o) => o.slug).join(\", \")}.`,\n );\n process.exit(1);\n }\n\n saveProject(dir, {\n org_id: matched.org.id,\n app_id: matched.app.id,\n slug: matched.app.slug,\n app_token: matched.app.app_token,\n });\n\n const rel = path.relative(process.cwd(), dir) || \".\";\n console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.org.name}`);\n console.log(` Wrote ${rel}/.clawnify/project.json`);\n console.log(` Run \\`clawnify deploy\\` to push the current source to this app.`);\n}\n","import path from \"node:path\";\nimport { fetchSchema, resolveApp, writeSchema } from \"../lib/sync-schema.js\";\n\ninterface PullSchemaOptions {\n from?: string;\n out?: string;\n force?: boolean;\n org?: string;\n}\n\n/**\n * `clawnify pull schema --from <app-id-or-slug>`\n *\n * Fetch the deployed app's current schema.sql snapshot and write it to\n * the local working directory. Used to back-port a deployed instance's\n * evolved schema into an open-source template repo, or to refresh a\n * developer's local copy after agent-driven schema changes.\n *\n * Refuses to overwrite a locally-modified schema.sql unless --force is\n * passed. Refusal is git-aware: if the local file has uncommitted\n * changes (or we're outside git and the file differs), we bail with a\n * helpful message instead of silently clobbering work.\n */\nexport async function pullSchemaCommand(options: PullSchemaOptions): Promise<void> {\n if (!options.from) {\n console.error(\"Usage: clawnify pull schema --from <app-id-or-slug>\");\n process.exit(64);\n }\n\n const ref = await resolveApp(options.from, options.org);\n if (!ref) {\n console.error(`App '${options.from}' not found in your orgs.`);\n process.exit(1);\n }\n\n let schema: string | null;\n try {\n schema = await fetchSchema(ref);\n } catch (err) {\n console.error(`Failed to fetch schema: ${(err as Error).message}`);\n process.exit(1);\n }\n\n const targetPath = path.resolve(options.out ?? \"schema.sql\");\n\n const result = await writeSchema(targetPath, schema, { force: options.force });\n const rel = path.relative(process.cwd(), result.path) || result.path;\n\n switch (result.status) {\n case \"no-schema\":\n console.log(` ${ref.slug}: no schema.sql in R2 (pre-backfill app, or no database)`);\n process.exit(0);\n\n case \"unchanged\":\n console.log(` ${rel} is already up to date`);\n process.exit(0);\n\n case \"written\":\n console.log(` ✓ wrote ${rel} (${result.bytes} bytes, from ${ref.slug})`);\n process.exit(0);\n\n case \"refused-uncommitted\":\n console.error(\n ` ${rel} has uncommitted changes — refusing to overwrite.\\n` +\n ` Commit/stash first, or rerun with --force.`,\n );\n process.exit(1);\n\n case \"refused-different\":\n console.error(\n ` ${rel} exists locally and differs from the deployed copy.\\n` +\n ` Not inside a git repo — can't tell intent. Rerun with --force to overwrite.`,\n );\n process.exit(1);\n }\n}\n","import { listMyOrgs } from \"../lib/api.js\";\nimport { loadAuth, saveAuth } from \"../lib/auth.js\";\n\nexport async function orgListCommand(): Promise<void> {\n const orgs = await listMyOrgs();\n if (orgs.length === 0) {\n console.log(\"No organizations.\");\n return;\n }\n const auth = loadAuth();\n const nameWidth = Math.max(4, ...orgs.map((o) => o.name.length));\n const slugWidth = Math.max(4, ...orgs.map((o) => o.slug.length));\n console.log(`${\"Name\".padEnd(nameWidth)} ${\"Slug\".padEnd(slugWidth)} Role Active`);\n console.log(`${\"─\".repeat(nameWidth)} ${\"─\".repeat(slugWidth)} ─────── ──────`);\n for (const o of orgs) {\n const active = auth?.org_id === o.id ? \" *\" : \"\";\n console.log(\n `${o.name.padEnd(nameWidth)} ${o.slug.padEnd(slugWidth)} ${o.role.padEnd(7)}${active}`\n );\n }\n}\n\nexport async function orgUseCommand(slugOrId: string): Promise<void> {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === slugOrId || o.slug === slugOrId);\n if (!match) {\n console.error(\n `No org matched \"${slugOrId}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`\n );\n process.exit(1);\n }\n const auth = loadAuth();\n if (!auth) {\n console.error(\"Not logged in. Run `clawnify login` first.\");\n process.exit(1);\n }\n saveAuth({ ...auth, org_id: match.id });\n console.log(` Active org set to ${match.name} (${match.slug})`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { listMyOrgs, type Org } from \"../lib/api.js\";\nimport { loadAuth } from \"../lib/auth.js\";\n\ninterface WorkspaceInitOptions {\n org?: string;\n name?: string;\n}\n\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 30);\n}\n\n/**\n * Resolve which org the workspace binds to: an explicit --org wins, otherwise\n * the active org, otherwise the sole org if the user only belongs to one.\n * Errors (rather than guessing) when the choice is ambiguous.\n */\nasync function resolveOrg(opts?: WorkspaceInitOptions): Promise<Org> {\n const orgs = await listMyOrgs();\n if (orgs.length === 0) {\n console.error(\"No organizations on your account. Run `clawnify login` first.\");\n process.exit(1);\n }\n\n if (opts?.org) {\n const match = orgs.find((o) => o.id === opts.org || o.slug === opts.org);\n if (!match) {\n console.error(\n `No org matched \"${opts.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(1);\n }\n return match;\n }\n\n const auth = loadAuth();\n const active = orgs.find((o) => o.id === auth?.org_id);\n if (active) return active;\n if (orgs.length === 1) return orgs[0]!;\n\n console.error(\n \"Multiple orgs — pick one with `--org <slug>` (or set a default: `clawnify org use <slug>`).\\n\" +\n ` Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(1);\n}\n\nfunction write(dir: string, file: string, content: string) {\n const fullPath = path.join(dir, file);\n fs.mkdirSync(path.dirname(fullPath), { recursive: true });\n fs.writeFileSync(fullPath, content);\n}\n\nexport async function workspaceInitCommand(\n dir?: string,\n opts?: WorkspaceInitOptions,\n): Promise<void> {\n const org = await resolveOrg(opts);\n const name = opts?.name || org.name;\n const targetDir = dir ? path.resolve(dir) : path.resolve(slugify(org.slug));\n\n if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n\n // clawnify.json — workspace root. No app/website block; binds the org.\n // The org is stored as a slug (human-readable, matches `--org` semantics);\n // deploy resolves it to an id at push time.\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n workspace: { org: org.slug },\n }, null, 2));\n\n // pnpm workspace so one `pnpm install` hoists deps across every app, plus\n // the org's single website.\n write(targetDir, \"pnpm-workspace.yaml\", `packages:\n - \"apps/*\"\n - \"website\"\n`);\n\n write(targetDir, \"package.json\", JSON.stringify({\n name: slugify(org.slug),\n private: true,\n type: \"module\",\n }, null, 2));\n\n // Root .gitignore — per-app link state (.clawnify) and secrets stay local;\n // the org binding in clawnify.json is the only thing committed for routing.\n write(targetDir, \".gitignore\", `node_modules\ndist\n.wrangler\n.clawnify\n.env*\n!.env.example\n.dev.vars\ndata.db\ndata.db-wal\ndata.db-shm\n`);\n\n write(targetDir, \"README.md\", `# ${name}\n\nClawnify workspace for the **${org.name}** org (\\`${org.slug}\\`).\n\nLayout:\n\n- \\`apps/<name>/\\` — one folder per app; each deploys to this org automatically.\n- \\`website/\\` — the org's single public website (Astro).\n\n## Add an app / the website\n\n\\`\\`\\`bash\nclawnify init # app → apps/<name>/ (inherits the org)\nclawnify init --type website # site → website/\n\\`\\`\\`\n\n## Deploy\n\n\\`\\`\\`bash\nclawnify deploy apps/<name> # one app (or: cd apps/<name> && clawnify deploy)\nclawnify deploy website # the website\n\\`\\`\\`\n\n## Install dependencies\n\n\\`\\`\\`bash\npnpm install # hoists deps for every app + the website\n\\`\\`\\`\n\n## GitHub sync (optional)\n\nPush this repo to a single GitHub monorepo, then in the dashboard link each app\nand the website to its own subdirectory (\\`apps/<name>\\`, \\`website\\`). Pushing the\nrepo auto-deploys only the targets whose folder changed; Clawnify mirrors edits\nback under the same subdirs. See \\`docs/internal/adr-company-monorepo.md\\` § \"GitHub sync\".\n`);\n\n // Keep apps/ and website/ in git even before anything is added.\n write(targetDir, \"apps/.gitkeep\", \"\");\n write(targetDir, \"website/.gitkeep\", \"\");\n\n const rel = path.relative(process.cwd(), targetDir) || \".\";\n console.log();\n console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);\n console.log();\n console.log(\" Get started:\");\n if (rel !== \".\") console.log(` cd ${rel}`);\n console.log(` clawnify init # add an app under apps/`);\n console.log(` clawnify deploy apps/<name>`);\n console.log();\n}\n","import fs from \"node:fs\";\nimport { callTool, isError } from \"../lib/mcp-client.js\";\n\n/**\n * `clawnify execute [file]` / `clawnify execute -c \"code\"` — run\n * TypeScript on the active org's substrate via mcp.clawnify.com.\n *\n * Streams the result to stdout/stderr matching the substrate's exit\n * code. Useful for ad-hoc code-mode invocations from the terminal;\n * agent runtimes call the underlying MCP tool directly.\n */\nexport async function executeCommand(\n file: string | undefined,\n options: { code?: string; timeout?: string },\n) {\n let code: string;\n if (options.code) {\n code = options.code;\n } else if (file) {\n try {\n code = fs.readFileSync(file, \"utf-8\");\n } catch (err) {\n process.stderr.write(`Failed to read ${file}: ${String(err)}\\n`);\n process.exit(1);\n }\n } else {\n process.stderr.write(\n \"Provide a file path or --code 'inline code'.\\n\" +\n \"Usage: clawnify execute path/to/file.ts\\n\" +\n \" clawnify execute -c \\\"console.log(1 + 1)\\\"\\n\",\n );\n process.exit(1);\n }\n\n const timeout_ms = options.timeout ? Math.max(1000, parseInt(options.timeout, 10) * 1000) : 30000;\n\n const resp = await callTool(\"clawnify_execute\", { code, timeout_ms });\n if (isError(resp)) {\n process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}\\n`);\n process.exit(1);\n }\n\n const sc = resp.result.structuredContent as\n | {\n stdout?: string;\n stderr?: string;\n exit_code?: number;\n duration_ms?: number;\n timed_out?: boolean;\n substrate_id?: string;\n runtime?: string;\n }\n | undefined;\n\n if (sc) {\n if (sc.stdout) process.stdout.write(sc.stdout);\n if (sc.stderr) process.stderr.write(sc.stderr);\n if (sc.timed_out) {\n process.stderr.write(`\\n[clawnify] timed out after ${timeout_ms}ms on ${sc.substrate_id}\\n`);\n }\n process.exit(sc.exit_code ?? 0);\n }\n\n // Fallback: surface the human-readable content[] entries\n for (const c of resp.result.content) {\n if (c.type === \"text\") process.stdout.write(c.text + \"\\n\");\n }\n process.exit(resp.result.isError ? 1 : 0);\n}\n","/**\n * Thin HTTP client for mcp.clawnify.com. Talks JSON-RPC 2.0 over POST\n * per the MCP Streamable HTTP transport. Reused by the `execute`,\n * `docs`, and `sdk inspect` subcommands; the stdio bridge uses raw\n * pass-through instead.\n */\n\nimport { getValidToken, loadAuth } from \"./auth.js\";\n\nconst MCP_URL = \"https://mcp.clawnify.com/mcp\";\n\nexport interface McpToolResult {\n content: Array<\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string }\n | { type: \"resource\"; resource: { uri: string; mimeType?: string; text?: string } }\n >;\n isError?: boolean;\n structuredContent?: unknown;\n}\n\nexport interface McpErrorResponse {\n error: { code: number; message: string };\n}\n\nexport type McpToolCallResponse = { result: McpToolResult } | McpErrorResponse;\n\nexport async function callTool(\n name: string,\n args: Record<string, unknown>,\n): Promise<McpToolCallResponse> {\n const token = await getValidToken();\n if (!token) {\n process.stderr.write(\"Not logged in. Run `clawnify login` first.\\n\");\n process.exit(1);\n }\n\n const auth = loadAuth();\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: \"Bearer \" + token,\n };\n if (auth?.org_id) {\n headers[\"X-Clawnify-Org-Id\"] = auth.org_id;\n }\n\n const res = await fetch(MCP_URL, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: Date.now(),\n method: \"tools/call\",\n params: { name, arguments: args },\n }),\n });\n\n if (res.status === 401) {\n process.stderr.write(\"Authentication failed. Run `clawnify login` again.\\n\");\n process.exit(1);\n }\n\n const body = (await res.json()) as { result?: McpToolResult; error?: { code: number; message: string } };\n if (body.error) return { error: body.error };\n if (!body.result) {\n return { error: { code: -32603, message: \"Empty response from MCP gateway\" } };\n }\n return { result: body.result };\n}\n\nexport function isError(resp: McpToolCallResponse): resp is McpErrorResponse {\n return \"error\" in resp;\n}\n","import { getValidToken, loadAuth } from \"../lib/auth.js\";\n\n/**\n * `clawnify docs [<app-slug>]` — fetch the skill-convention README\n * for an app (or the org-level index) from the docs runtime worker.\n *\n * Hits clawnify-mcp-docs directly via its public workers.dev URL\n * with the caller's Supabase access_token. Today the docs worker\n * trusts that anyone reaching it has been authenticated upstream;\n * the CLI is the upstream for human invocation.\n *\n * For agent use, `clawnify_docs_search` (via mcp.clawnify.com) is\n * the equivalent — that path also goes through the docs worker via\n * Service Binding.\n */\n\nconst DOCS_URL = \"https://clawnify-mcp-docs.workers.dev\";\n\nexport async function docsCommand(\n slug: string | undefined,\n options: { caller?: string },\n) {\n const token = await getValidToken();\n if (!token) {\n process.stderr.write(\"Not logged in. Run `clawnify login` first.\\n\");\n process.exit(1);\n }\n\n const auth = loadAuth();\n if (!auth?.org_id) {\n process.stderr.write(\n \"No active org. Pick one with `clawnify org use <slug-or-id>` first.\\n\",\n );\n process.exit(1);\n }\n\n const caller = options.caller ?? \"external\";\n const path = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;\n\n const res = await fetch(DOCS_URL + path, {\n headers: {\n authorization: \"Bearer \" + token,\n },\n });\n\n if (!res.ok) {\n process.stderr.write(`Failed to fetch docs: ${res.status} ${res.statusText}\\n`);\n process.exit(1);\n }\n\n const md = await res.text();\n process.stdout.write(md);\n if (!md.endsWith(\"\\n\")) process.stdout.write(\"\\n\");\n}\n","import readline from \"node:readline\";\nimport { getValidToken, loadAuth } from \"../lib/auth.js\";\n\n/**\n * `clawnify mcp` — stdio bridge to mcp.clawnify.com.\n *\n * Reads newline-delimited JSON-RPC messages from stdin (the MCP\n * stdio transport convention), forwards each as an HTTP POST to\n * mcp.clawnify.com/mcp with the stored Bearer token, and writes\n * the JSON-RPC response back to stdout.\n *\n * Used by bash-less MCP clients (Claude Desktop, ChatGPT custom\n * apps) per docs/internal/agent-tiering.md § \"Surface 3 — MCP\". Bash-capable\n * agents should use the CLI directly (clawnify execute / docs /\n * sdk inspect) — same auth, fewer hops.\n *\n * Notifications (no `id`) yield 202 with no body; we emit nothing.\n * Errors during forwarding emit a JSON-RPC error response with the\n * original request id so the client surfaces them cleanly.\n */\n\nconst MCP_URL = \"https://mcp.clawnify.com/mcp\";\n\nexport async function mcpBridgeCommand() {\n const token = await getValidToken();\n if (!token) {\n process.stderr.write(\"Not logged in. Run `clawnify login` first.\\n\");\n process.exit(1);\n }\n\n const auth = loadAuth();\n const baseHeaders: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: \"Bearer \" + token,\n };\n if (auth?.org_id) {\n baseHeaders[\"X-Clawnify-Org-Id\"] = auth.org_id;\n }\n\n const rl = readline.createInterface({ input: process.stdin, terminal: false });\n\n rl.on(\"line\", async (line) => {\n const trimmed = line.trim();\n if (!trimmed) return;\n\n let parsedId: string | number | null = null;\n try {\n parsedId = (JSON.parse(trimmed) as { id?: string | number | null }).id ?? null;\n } catch {\n // Malformed JSON — let the gateway surface the parse error;\n // it'll respond with a JSON-RPC parse error of its own.\n }\n\n try {\n const res = await fetch(MCP_URL, {\n method: \"POST\",\n headers: baseHeaders,\n body: trimmed,\n });\n const text = await res.text();\n // 202 (notification ack) returns empty body — emit nothing.\n if (text.length > 0) {\n process.stdout.write(text);\n if (!text.endsWith(\"\\n\")) process.stdout.write(\"\\n\");\n }\n } catch (err) {\n const errResp = {\n jsonrpc: \"2.0\",\n id: parsedId,\n error: { code: -32603, message: \"bridge transport error: \" + String(err) },\n };\n process.stdout.write(JSON.stringify(errResp) + \"\\n\");\n }\n });\n\n rl.on(\"close\", () => {\n process.exit(0);\n });\n}\n","import { loginCommand } from \"./login.js\";\nimport { docsCommand } from \"./docs.js\";\n\n/**\n * `clawnify sdk inspect <slug>` — show the typed-procedure README\n * for an app. Same data as `clawnify docs <slug>` but with a\n * developer-shaped command name per docs/internal/agent-tiering.md §\n * \"Three surfaces, three jobs\".\n *\n * `clawnify sdk login` — alias for `clawnify login`, kept so the\n * full surface advertised in agent-tiering.md (`sdk install`,\n * `sdk inspect`, `sdk login`) is reachable today.\n *\n * `clawnify sdk install` — deferred to a follow-up PR. Depends on\n * publishing the `@clawnify/sdk` npm package, which depends on the\n * template-strategy / build-pipeline manifest writer landing first.\n */\n\nexport async function sdkInspectCommand(slug: string, options: { caller?: string }) {\n // External density gives the richest cut — examples + anti-patterns.\n // Best for developers inspecting an app from the terminal.\n await docsCommand(slug, { caller: options.caller ?? \"external\" });\n}\n\nexport async function sdkLoginCommand() {\n await loginCommand();\n}\n\nexport async function sdkInstallCommand() {\n process.stderr.write(\n \"`clawnify sdk install` is not yet implemented.\\n\" +\n \"It depends on the `@clawnify/sdk` npm package being published, \" +\n \"which depends on the build-pipeline manifest writer (template-strategy.md).\\n\" +\n \"Track in the Phase 5 follow-up.\\n\",\n );\n process.exit(1);\n}\n","/**\n * `clawnify skills` — install / list / remove Clawnify-curated skills\n * into whichever coding agents you have in the current directory.\n *\n * Behavior:\n * - `list` shows every skill the CLI bundles + its version.\n * - `add <name|--all>` writes the skill into EVERY detected agent\n * simultaneously (.claude, .cursor, .openclaw, .codex, aider).\n * - `remove <name|--all>` cleans them back out of every agent.\n *\n * Version semantics: each installed file carries a\n * `<!-- clawnify-skill: <name> v<X.Y.Z> -->` header. Re-running `add`\n * on the same CLI version is a no-op; upgrading the CLI (`npm install\n * -g clawnify@latest`) then re-running `add` overwrites with the new\n * content. This is the only way skills update — there is no runtime\n * network fetch.\n */\n\nimport { SKILLS, CLI_VERSION, type BundledSkill } from \"../lib/skills/registry.js\";\nimport {\n agentByName,\n detectAgents,\n ALL_AGENTS,\n type Agent,\n type DetectedAgent,\n} from \"../lib/skills/detect.js\";\nimport { installSkill, removeSkill } from \"../lib/skills/install.js\";\n\ninterface AddOptions {\n all?: boolean;\n agent?: string;\n}\n\ninterface RemoveOptions {\n all?: boolean;\n agent?: string;\n}\n\nexport function skillsListCommand(): void {\n console.log(`Clawnify skills (v${CLI_VERSION}):\\n`);\n for (const s of SKILLS) {\n console.log(` ${s.name}`);\n console.log(` ${s.description}\\n`);\n }\n console.log(`Add one: clawnify skills add <name>`);\n console.log(`Add all: clawnify skills add --all`);\n console.log(`Remove: clawnify skills remove <name>`);\n}\n\nexport async function skillsAddCommand(name: string | undefined, opts: AddOptions): Promise<void> {\n const skills = resolveSkills(name, opts.all);\n if (skills.length === 0) {\n console.error(\"No skill specified. Pass a name or --all. See `clawnify skills list`.\");\n process.exit(1);\n }\n\n const agents = resolveAgents(opts.agent);\n if (agents.length === 0) {\n console.error(\n \"No coding agent detected in this directory. Looked for:\\n\" +\n \" .claude/ (Claude Code)\\n\" +\n \" .cursor/ (Cursor)\\n\" +\n \" .openclaw/ (OpenClaw)\\n\" +\n \" .codex/ or AGENTS.md (Codex)\\n\" +\n \" CONVENTIONS.md or .aider.conf.yml (Aider)\\n\\n\" +\n \"Force a target with --agent <claude|cursor|openclaw|codex|aider>.\",\n );\n process.exit(1);\n }\n\n const cwd = process.cwd();\n console.log(\n `Installing ${skills.length} skill${skills.length === 1 ? \"\" : \"s\"} into ${agents.length} agent${agents.length === 1 ? \"\" : \"s\"}:`,\n );\n console.log(` CLI version: v${CLI_VERSION}`);\n console.log(\n ` Agents: ${agents.map((a) => `${a.agent} (${a.marker})`).join(\", \")}\\n`,\n );\n\n let installed = 0;\n let updated = 0;\n let skipped = 0;\n for (const skill of skills) {\n for (const agent of agents) {\n const result = installSkill(skill, agent, cwd);\n if (result.status === \"installed\") {\n installed++;\n console.log(` ✓ ${skill.name} → ${result.path}`);\n } else if (result.status === \"updated\") {\n updated++;\n console.log(\n ` ↑ ${skill.name} → ${result.path} (v${result.previousVersion} → v${CLI_VERSION})`,\n );\n } else {\n skipped++;\n console.log(` · ${skill.name} → ${result.path} (${result.reason})`);\n }\n }\n }\n console.log(\n `\\nDone — ${installed} installed, ${updated} updated, ${skipped} unchanged.`,\n );\n}\n\nexport async function skillsRemoveCommand(name: string | undefined, opts: RemoveOptions): Promise<void> {\n const skills = resolveSkills(name, opts.all);\n if (skills.length === 0) {\n console.error(\"No skill specified. Pass a name or --all.\");\n process.exit(1);\n }\n\n const agents = resolveAgents(opts.agent);\n if (agents.length === 0) {\n console.error(\"No coding agent detected. Nothing to remove.\");\n return;\n }\n\n const cwd = process.cwd();\n let removed = 0;\n for (const skill of skills) {\n for (const agent of agents) {\n if (removeSkill(skill.name, agent, cwd)) {\n removed++;\n console.log(` ✗ ${skill.name} removed from ${agent.agent}`);\n }\n }\n }\n console.log(`\\nDone — removed ${removed} file${removed === 1 ? \"\" : \"s\"}.`);\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────\n\nfunction resolveSkills(name: string | undefined, all: boolean | undefined): BundledSkill[] {\n if (all) return [...SKILLS];\n if (!name) return [];\n const match = SKILLS.find((s) => s.name === name);\n if (!match) {\n console.error(\n `Unknown skill: ${name}\\nAvailable: ${SKILLS.map((s) => s.name).join(\", \")}`,\n );\n process.exit(1);\n }\n return [match];\n}\n\nfunction resolveAgents(forced: string | undefined): DetectedAgent[] {\n if (forced) {\n if (!ALL_AGENTS.includes(forced as Agent)) {\n console.error(\n `Unknown agent: ${forced}\\nValid: ${ALL_AGENTS.join(\", \")}`,\n );\n process.exit(1);\n }\n return [agentByName(forced as Agent)];\n }\n return detectAgents(process.cwd());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;;;ACAxB,OAAO,YAAY;AACnB,OAAO,UAAU;AACjB,OAAO,cAAc;AACrB,OAAO,UAAU;AASjB,IAAM,gBAAgB;AACtB,IAAM,eAAe;AACrB,IAAM,aAAa;AAQnB,SAAS,YAAY,OAAgC;AACnD,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI,OAAO;AACX,QAAI,KAAgC;AAEpC,UAAM,SAAS,KAAK,aAAa,CAAC,KAAK,QAAQ;AAC7C,YAAM,MAAM,IAAI,IAAI,IAAI,KAAM,oBAAoB,aAAa,EAAE;AAIjE,YAAM,cAAsC;AAAA,QAC1C,+BAA+B;AAAA,QAC/B,gCAAgC;AAAA,QAChC,wCAAwC;AAAA,MAC1C;AAEA,UAAI,IAAI,WAAW,WAAW;AAC5B,YAAI,UAAU,KAAK,WAAW;AAC9B,YAAI,IAAI;AACR;AAAA,MACF;AAEA,UAAI,IAAI,aAAa,aAAa;AAChC,YAAI,UAAU,KAAK,WAAW;AAC9B,YAAI,IAAI,WAAW;AACnB;AAAA,MACF;AAEA,YAAM,OAAO,IAAI,aAAa,IAAI,MAAM;AACxC,YAAM,gBAAgB,IAAI,aAAa,IAAI,OAAO;AAElD,UAAI,CAAC,QAAQ,kBAAkB,OAAO;AACpC,YAAI,UAAU,KAAK,EAAE,GAAG,aAAa,gBAAgB,mBAAmB,CAAC;AACzE,YAAI,IAAI,KAAK,UAAU,EAAE,IAAI,MAAM,CAAC,CAAC;AACrC;AAAA,MACF;AAEA,UAAI,UAAU,KAAK,EAAE,GAAG,aAAa,gBAAgB,mBAAmB,CAAC;AACzE,UAAI,IAAI,KAAK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E,EAChG,OAAO,CAAC,MAAM,SAAS,iBAAiB,MAAM,IAAI,CAAC;AACtD,SACG,QAAQ,eAAe,EACvB,YAAY,0DAA0D,EACtE,OAAO,SAAS,8BAA8B,EAC9C,OAAO,mBAAmB,8BAA8B,EACxD,OAAO,CAAC,MAAM,SAAS,oBAAoB,MAAM,IAAI,CAAC;AAMzD,QAAM,UAAU,QACb,QAAQ,UAAU,EAClB,YAAY,iEAAiE;AAChF,UACG,QAAQ,SAAS,EACjB,YAAY,mGAAmG,EAC/G,OAAO,mBAAmB,sEAAsE,EAChG,OAAO,YAAY,wBAAwB,EAC3C,OAAO,CAAC,SAAS,sBAAsB,IAAI,CAAC;AAC/C,UACG,QAAQ,WAAW,EACnB,YAAY,+DAA+D,EAC3E,OAAO,mBAAmB,8BAA8B,EACxD,OAAO,CAAC,SAAS,wBAAwB,IAAI,CAAC;AAEjD,QAAM,MAAM,QAAQ,QAAQ,KAAK,EAAE,YAAY,4CAA4C;AAC3F,MACG,QAAQ,gBAAgB,EACxB,YAAY,+DAA+D,EAC3E,OAAO,mBAAmB,wDAAwD,UAAU,EAC5F,OAAO,iBAAiB;AAC3B,MACG,QAAQ,OAAO,EACf,YAAY,mEAAmE,EAC/E,OAAO,eAAe;AACzB,MACG,QAAQ,SAAS,EACjB,YAAY,kEAA6D,EACzE,OAAO,iBAAiB;AAE3B,MAAI;AACF,UAAM,QAAQ,WAAW;AAAA,EAC3B,SAAS,KAAK;AACZ,YAAQ,MAAO,KAAe,WAAW,GAAG;AAC5C,YAAQ,WAAW;AAAA,EACrB;AAUA,QAAM,IAAI,QAAc,CAAC,YAAY,QAAQ,OAAO,MAAM,IAAI,MAAM,QAAQ,CAAC,CAAC;AAC9E,UAAQ,KAAK,QAAQ,YAAY,CAAC;AACpC;","names":["fs","path","readline","readline","path","result","fs","readline","readline","open","open","fs","path","readline","path","existsSync","statSync","join","path","existsSync","join","statSync","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","dirname","join","join","escapeRe","existsSync","readFileSync","writeFileSync","mkdirSync","dirname","unlinkSync","existsSync","readFileSync","unlinkSync","writeFileSync","join","ask","readline","ask","path","fs","fs","path","spawn","slugify","assertNodeVersion","path","fs","spawn","code","path","UUID_RE","path","path","path","fs","path","slugify","write","path","fs","fs","fs","path","readline","MCP_URL","readline","resolveAgents"]}
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ if (process.argv.includes("--mcp")) {
5
5
  const { startMcpServer } = await import("./mcp-3JPAW35L.js");
6
6
  await startMcpServer();
7
7
  } else {
8
- const { runCli } = await import("./cli-KCTCHVPG.js");
8
+ const { runCli } = await import("./cli-GFWOUUMF.js");
9
9
  await runCli();
10
10
  }
11
11
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawnify",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Deploy your apps and website to Clawnify from the terminal with Claude Code, Codex, and Cursor",
5
5
  "type": "module",
6
6
  "bin": {