clawnify 0.20.3 → 0.20.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -14
- package/dist/{chunk-E36OET5K.js → chunk-BTI5OR7H.js} +1 -2
- package/dist/{cli-XTCM7DWW.js → cli-NXHUAPDU.js} +5 -6
- package/dist/index.js +2 -3
- package/dist/{mcp-GVVQUTUK.js → mcp-KHPD6OPV.js} +1 -2
- package/package.json +1 -1
- package/dist/chunk-E36OET5K.js.map +0 -1
- package/dist/cli-XTCM7DWW.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp-GVVQUTUK.js.map +0 -1
package/dist/cli-XTCM7DWW.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commands/login.ts","../src/commands/deploy.ts","../src/lib/anon.ts","../src/lib/sync-schema.ts","../src/lib/drizzle.ts","../src/lib/servers.ts","../src/commands/ls.ts","../src/commands/logs.ts","../src/commands/sessions.ts","../src/commands/agents.ts","../src/commands/servers.ts","../src/commands/env.ts","../src/commands/api.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/db.ts","../src/commands/link.ts","../src/commands/pull.ts","../src/commands/org.ts","../src/commands/connections.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","../src/commands/flows.ts"],"sourcesContent":["import { Command, Option } from \"commander\";\n\nimport { loginCommand } from \"./commands/login.js\";\nimport { deployCommand } from \"./commands/deploy.js\";\nimport { VERSION } from \"./version.js\";\nimport { lsCommand } from \"./commands/ls.js\";\nimport { logsCommand } from \"./commands/logs.js\";\nimport { sessionsListCommand, sessionsHistoryCommand } from \"./commands/sessions.js\";\nimport { agentsListCommand, agentsPullCommand, agentsPushCommand, agentsSkillsCommand, agentsGrantSkillCommand, agentsCreateCommand } from \"./commands/agents.js\";\nimport { serversListCommand } from \"./commands/servers.js\";\nimport { envSetCommand, envUnsetCommand } from \"./commands/env.js\";\nimport { apiCommand } from \"./commands/api.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 { dbGenerateCommand } from \"./commands/db.js\";\nimport { linkCommand } from \"./commands/link.js\";\nimport { pullSchemaCommand } from \"./commands/pull.js\";\nimport { orgListCommand, orgUseCommand } from \"./commands/org.js\";\nimport { connectionsListCommand, connectionsConnectCommand } from \"./commands/connections.js\";\nimport { workspaceInitCommand, workspaceStatusCommand, workspaceConnectCommand } 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 flowsCreateCommand,\n flowsEditCommand,\n flowsListCommand,\n flowsPublishCommand,\n flowsReadCommand,\n} from \"./commands/flows.js\";\nimport {\n aiFilesInstallCommand,\n aiFilesUninstallCommand,\n} from \"./commands/ai-files.js\";\n\n/**\n * Which agent to target, for the rare org that has more than one. Normally\n * omitted — a single-agent org resolves silently (see lib/servers.ts), which is\n * why the platform's underlying \"server\" never has to surface at all.\n */\nfunction agentIdOption(): Option {\n return new Option(\n \"--agent-id <id>\",\n \"Target agent (default: the org's agent, or a linked project)\",\n );\n}\n\n/**\n * Back-compat alias of --agent-id. Hidden, never printed, never documented —\n * but still honoured so scripts, CI, and already-installed `ai-files` rules\n * blocks written against the old flag keep working. Normalized to `server` by\n * the preAction hook below, which is what every handler reads.\n */\nfunction legacyServerOption(): Option {\n return new Option(\"--server <id>\").hideHelp();\n}\n\nexport async function runCli() {\n const program = new Command();\n\n program\n .name(\"clawnify\")\n .description(\"Deploy apps to Clawnify\")\n .version(VERSION)\n .addHelpText(\n \"after\",\n \"\\nCoding agent? Start with `clawnify workspace` — it prints the org's synced\\nGitHub repo, what maps where, and how local editing works.\\n\",\n );\n\n // Fold the hidden legacy --server alias onto --agent-id before any handler\n // runs, so handlers only ever read one option. Explicit --server still wins\n // when both are passed (it's the more specific, older intent).\n program.hook(\"preAction\", (_program, actionCommand) => {\n const opts = actionCommand.opts();\n if (opts.agentId && !opts.server) actionCommand.setOptionValue(\"server\", opts.agentId);\n });\n\n program\n .command(\"init [dir]\")\n .description(\"Scaffold a new Clawnify project (app, website, or agent)\")\n .option(\"--type <type>\", \"Project type: app, website, or agent (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 const db = program.command(\"db\").description(\"Database schema tooling\");\n db.command(\"generate [dir]\")\n .description(\"Generate migration SQL from src/server/schema.ts (dev/deploy run this automatically)\")\n .action(dbGenerateCommand);\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, website, or agent to Clawnify\")\n .option(\"--from <repo>\", \"Deploy from a GitHub repo (owner/repo)\")\n .addOption(\n new Option(\n \"--agent-id <id>\",\n \"Agent deploy: which agent to push to when the org has several (saved as a link)\",\n ),\n )\n .addOption(legacyServerOption())\n .option(\"--agent <name>\", \"Agent deploy: the named agent to push to (default: main)\")\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 conflict, update the existing app\")\n .option(\"--update-existing\", \"Non-interactive: on conflict, overwrite the existing app\")\n .option(\"--create-new\", \"Non-interactive: on 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 .option(\"--force\", \"Deploy even if it would overwrite newer changes in the synced GitHub repo\")\n .option(\"--discard-draft\", \"Replace the app's unpublished chat changes with this deploy instead of keeping them for review\")\n .option(\"--replace\", \"Website deploy: replace the organization's existing website with this folder, which isn't linked to it\")\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 connections` — the org's naming catalog (docs §3.5): canonical\n // integration ids, provider-key names, custom env. The read to make before\n // declaring `requires` — never invent an identifier.\n const connections = program\n .command(\"connections\")\n .description(\"Org integrations & the naming catalog\");\n connections\n .command(\"list\")\n .description(\"List canonical integration ids, provider keys, and custom env for the active org\")\n .option(\"--json\", \"Print the full catalog payload (includes docs + spec_url per integration)\")\n .action(connectionsListCommand);\n connections\n .command(\"connect <id>\")\n .description(\"Explain how to connect an integration (OAuth in the dashboard — the CLI/agent can't do it for you)\")\n .option(\"--json\", \"Print the steps as JSON\")\n .action(connectionsConnectCommand);\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. Bare invocation\n // prints orientation (org, synced repo, subdir↔target map, editing contract)\n // — the entry point for coding agents.\n const workspace = program\n .command(\"workspace\")\n .description(\"Show the org's workspace: synced GitHub repo, targets, and how to edit locally\")\n .option(\"--json\", \"Machine-readable output\")\n .action(workspaceStatusCommand);\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 workspace\n .command(\"connect\")\n .description(\"Enable GitHub sync: create/join the org's workspace repo and link the website\")\n .option(\"--account <login-or-id>\", \"GitHub account to use when several are connected\")\n .action(workspaceConnectCommand);\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 // `clawnify servers` — HIDDEN. The infrastructure view of the same rows\n // `clawnify agents list` renders as agents. Kept for back-compat and for\n // debugging provisioning (it shows raw status/region), but deliberately\n // absent from help: exposing boxes alongside agents is what let a coding\n // agent read a provisioned agent as \"not an agent\" and create a duplicate.\n // Discovery is agents → sub-agents → sessions, with no infrastructure tier.\n const servers = program\n .command(\"servers\", { hidden: true })\n .description(\"Deprecated — use `clawnify agents list`\");\n servers\n .command(\"list\", { isDefault: true })\n .description(\"Deprecated — use `clawnify agents list`\")\n .action(serversListCommand);\n\n // `clawnify sessions` — the FDE observe verb: list stored sessions across an\n // agent and its sub-agents, and read one session's transcript.\n // See docs/internal/fde-strategy.md.\n const sessions = program\n .command(\"sessions\")\n .description(\"Observe agent sessions (list + read transcripts)\");\n sessions\n .command(\"list\", { isDefault: true })\n .description(\"List stored sessions across an agent and its sub-agents\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--agent <slug>\", \"Only this agent's sessions\")\n .option(\"--active <minutes>\", \"Only sessions active within N minutes\")\n .option(\"--limit <n>\", \"Max rows (default 100)\")\n .option(\"--json\", \"Print the raw JSON payload\")\n .action(sessionsListCommand);\n sessions\n .command(\"history <key>\")\n .description(\"Read one session's transcript by key (e.g. agent:dnz---theo:lead:row_8268)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--agent <slug>\", \"Owning agent (else derived from the key prefix)\")\n .option(\"--limit <n>\", \"Max transcript entries (default 100)\")\n .option(\"--json\", \"Print the raw JSON payload\")\n .action(sessionsHistoryCommand);\n\n // `clawnify agents` — the FDE's agent-management verbs: list the org's agents\n // and their sub-agents, pull an agent's AGENTS.md/skills/flows to edit, push\n // edits back. See docs/internal/fde-strategy.md.\n const agents = program\n .command(\"agents\")\n .description(\"Manage agents: list, pull config to edit, push edits back\");\n agents\n .command(\"list\", { isDefault: true })\n .description(\"List the org's agents and their sub-agents\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .action(agentsListCommand);\n agents\n .command(\"pull [dir]\")\n .description(\"Fetch an agent's AGENTS.md + skills/ + flows/ into a directory to edit\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--agent <slug>\", \"Which agent (default: main)\")\n .action(agentsPullCommand);\n agents\n .command(\"push [dir]\")\n .description(\"Push edited AGENTS.md + skills/ + flows/ back (additive; picked up next session)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--agent <slug>\", \"Which agent (default: the pulled agent, else main)\")\n .action(agentsPushCommand);\n agents\n .command(\"skills [agent]\")\n .description(\"Show an agent's effective skill inventory (what it can actually run, not just its workspace)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .action(agentsSkillsCommand);\n agents\n .command(\"grant-skill <skill>\")\n .description(\"Grant an existing (main-authored) skill to one agent (--to) or every agent (--all)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--to <agent>\", \"Grant to one sub-agent\")\n .option(\"--all\", \"Grant to every agent (shared managed root; includes future agents)\")\n .action(agentsGrantSkillCommand);\n agents\n .command(\"create <slug>\")\n .description(\"Create a new sub-agent (RESTARTS the gateway — needs --yes)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--name <name>\", \"Display name (default: the slug)\")\n .option(\"--description <role>\", \"The agent's role/specialization (seeded into its AGENTS.md)\")\n .option(\"--yes\", \"Confirm — proceed with the gateway restart\")\n .action(agentsCreateCommand);\n\n // `clawnify flows` — ClawFlow management: create/edit drafts and publish\n // numbered versions. Flows belong to the MAIN agent: one ClawFlow instance\n // runs per gateway, bound to main's workspace/flows (a sub-agent's flows/\n // dir is never executed). Validation runs agent-side against the\n // live engine registry and publishing snapshots via the engine itself, so\n // flows using Clawnify custom steps (clawnify_app, clawnify_action,\n // send_email) behave exactly as flow_run will see them.\n const flows = program\n .command(\"flows\")\n .description(\"Manage the main agent's ClawFlows: create/edit drafts, publish versions\");\n flows\n .command(\"list\", { isDefault: true })\n .description(\"List flow drafts and their latest published version\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .option(\"--json\", \"Print the raw JSON payload\")\n .action(flowsListCommand);\n flows\n .command(\"read <name>\")\n .description(\"Print a flow's current draft definition\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .action(flowsReadCommand);\n flows\n .command(\"create <name>\")\n .description(\"Create a flow draft from a local JSON definition\")\n .option(\"--file <path>\", \"Flow definition JSON (required)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .action(flowsCreateCommand);\n flows\n .command(\"edit <name>\")\n .description(\"Replace a flow draft — from --file, or interactively via $EDITOR\")\n .option(\"--file <path>\", \"Flow definition JSON (default: open the current draft in $EDITOR)\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .action(flowsEditCommand);\n flows\n .command(\"publish <name>\")\n .description(\"Validate the draft and publish it as the next numbered version\")\n .addOption(agentIdOption())\n .addOption(legacyServerOption())\n .action(flowsPublishCommand);\n\n // `clawnify env` — the org's custom environment variables (all agents). Read\n // via `connections list`; set/unset here. NOT for secrets — those go in the\n // dashboard (Settings → Environment Variables / API Keys).\n const env = program\n .command(\"env\")\n .description(\"Org custom environment variables (read via `connections list`)\");\n env\n .command(\"set <key> <value>\")\n .description(\"Set an org-wide custom env var (NON-SECRET config; restarts the gateway to apply)\")\n .action(envSetCommand);\n env\n .command(\"unset <key>\")\n .description(\"Remove an org-wide custom env var (restarts the gateway to apply)\")\n .action(envUnsetCommand);\n\n // `clawnify api` — raw authenticated request; the escape hatch so the\n // porcelain never has to be complete (see gh api / stripe get).\n program\n .command(\"api <path>\")\n .description(\"Raw authenticated request to the Clawnify API — for anything without a dedicated command\")\n .option(\"-X, --method <method>\", \"HTTP method (default GET, or POST when -d is given)\")\n .option(\"-d, --data <json>\", \"JSON request body\")\n .option(\"--org <slug-or-id>\", \"Org to scope the request to\")\n .action(apiCommand);\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 LOCAL_REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;\nconst HOSTED_REDIRECT_URI = \"https://app.clawnify.com/oauth/cli\";\nconst WEB_ORIGIN = \"https://app.clawnify.com\";\n\ninterface AuthCode {\n code: string;\n redirectUri: string; // the redirect_uri the code was issued for\n}\n\n/**\n * Waits for the authorization code from whichever source responds first:\n * - the local server receiving the OAuth redirect directly (the browser\n * we opened uses the localhost redirect_uri — classic seamless flow)\n * - the local server receiving a notify fetch from the hosted /oauth/cli\n * page (user opened the printed URL in a same-machine browser)\n * - the \"Paste code here\" prompt (any browser, e.g. over SSH)\n *\n * The two flows use distinct `state` values, which is how we know which\n * redirect_uri to use in the token exchange.\n */\nfunction waitForCode(stateLocal: string, stateRemote: string): Promise<AuthCode> {\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 const error = url.searchParams.get(\"error\");\n\n // Direct OAuth redirect (browser we opened, localhost redirect_uri):\n // respond with human-facing HTML.\n if (returnedState === stateLocal) {\n if (error || !code) {\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n \"<html><body><h2>Authorization denied.</h2><p>You can close this window.</p></body></html>\"\n );\n finish(new Error(`Authorization denied: ${error ?? \"no code returned\"}`));\n return;\n }\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n \"<html><body><h2>Logged in!</h2><p>You can close this window and return to the terminal.</p></body></html>\"\n );\n finish(null, { code, redirectUri: LOCAL_REDIRECT_URI });\n return;\n }\n\n // Notify fetch from the hosted /oauth/cli page (hosted redirect_uri):\n // respond with JSON for the page's script.\n if (returnedState === stateRemote && code) {\n res.writeHead(200, { ...corsHeaders, \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true }));\n finish(null, { code, redirectUri: HOSTED_REDIRECT_URI });\n return;\n }\n\n res.writeHead(400, { ...corsHeaders, \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: false }));\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, result?: AuthCode) {\n if (done) return;\n done = true;\n clearTimeout(timeout);\n server.close();\n rl?.close();\n if (err) reject(err);\n else resolve(result!);\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 !== stateRemote) {\n finish(new Error(\"Invalid code. Run `clawnify login` to try again.\"));\n return;\n }\n finish(null, { code, redirectUri: HOSTED_REDIRECT_URI });\n });\n });\n}\n\nexport async function loginCommand(): Promise<void> {\n const { codeVerifier: verifier, codeChallenge: challenge } = generatePkce();\n const stateLocal = crypto.randomBytes(16).toString(\"hex\");\n const stateRemote = crypto.randomBytes(16).toString(\"hex\");\n\n const buildAuthUrl = (redirectUri: string, state: string): string => {\n const url = new URL(OAUTH_AUTHORIZE_URL);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", OAUTH_CLIENT_ID);\n url.searchParams.set(\"redirect_uri\", redirectUri);\n url.searchParams.set(\"code_challenge\", challenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"scope\", \"openid email\");\n url.searchParams.set(\"state\", state);\n return url.toString();\n };\n\n // The browser we open completes via the localhost redirect (seamless);\n // the printed URL works from any browser via the hosted code page.\n const localAuthUrl = buildAuthUrl(LOCAL_REDIRECT_URI, stateLocal);\n const hostedAuthUrl = buildAuthUrl(HOSTED_REDIRECT_URI, stateRemote);\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(` ${hostedAuthUrl}\\n`);\n open(localAuthUrl).catch(() => {\n // No browser available (SSH/headless) — the printed URL is the fallback\n });\n\n const { code, redirectUri } = await waitForCode(stateLocal, stateRemote);\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: redirectUri,\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 // Credentials only — no org. Org is resolved per folder on every command\n // (resolveOrgContext in lib/api.ts); nothing about it is stored per machine.\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 { execFileSync, 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 {\n isLoggedOut,\n getOrCreateAnonContext,\n anonPostForm,\n explainAnonUnauthorized,\n printClaimBlock,\n healStaleAnonLink,\n} from \"../lib/anon.js\";\nimport { fetchSchema, writeSchema } from \"../lib/sync-schema.js\";\nimport { ensureDrizzleConfig } from \"../lib/drizzle.js\";\nimport { resolveServerId } from \"../lib/servers.js\";\n\ninterface DeploySuccess {\n app_id: string;\n slug: string;\n app_token: string;\n}\n\ninterface SlugConflict {\n /** `slug_exists_in_org`: another app in this org owns the derived slug.\n * `app_from_repo_exists_in_org`: this org already has an app deployed from\n * the same repo/branch/subdir — redeploy it instead of duplicating. */\n error: \"slug_exists_in_org\" | \"app_from_repo_exists_in_org\";\n existing_app_id: string;\n existing_app_name: string;\n /** Absent on API versions older than the repo-identity conflict. */\n existing_app_slug?: 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 /** Agent deploy: which agent to push this member to (--agent-id, or the\n * hidden --server alias). Saved as a link on first deploy, then reused.\n * Omitted for a single-agent org — it resolves automatically. */\n server?: string;\n agent?: string;\n /** Deploy even if it would overwrite newer changes in the synced GitHub repo. */\n force?: boolean;\n /** Replace the app's unpublished chat changes instead of keeping them for review. */\n discardDraft?: boolean;\n /** Website deploy: replace the org's existing website from a folder that isn't linked to it. */\n replace?: 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\n/**\n * Upload with a bounded retry on *transport* failures.\n *\n * `api.postForm` throws (rather than returning a response) when the request\n * never completes — undici surfaces this as a bare `fetch failed`, and the\n * build sandbox also produces \"Durable Object reset because its code was\n * updated\" when it is recycled mid-deploy. Both are transient and clear on a\n * retry, but the user only sees an unexplained failure and is left guessing\n * whether their app is broken.\n *\n * HTTP error *statuses* are deliberately not retried — those are returned, not\n * thrown, and a 4xx will never succeed by trying again. For the create path a\n * lost-response retry surfaces as a 409 slug conflict, which the caller already\n * knows how to resolve, so this cannot silently create a duplicate app.\n */\nasync function postFormWithRetry(\n path: string,\n formData: FormData,\n orgId: string | undefined,\n attempts = 3,\n): Promise<Response> {\n let lastErr: unknown;\n for (let i = 0; i < attempts; i++) {\n try {\n return await api.postForm(path, formData, { orgId });\n } catch (err) {\n lastErr = err;\n if (i === attempts - 1) break;\n const waitMs = 1000 * 2 ** i;\n console.warn(\n ` upload failed (${String(err).slice(0, 120)}) — retrying in ${waitMs / 1000}s ` +\n `[${i + 2}/${attempts}]`,\n );\n await new Promise((r) => setTimeout(r, waitMs));\n }\n }\n throw lastErr;\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 postFormWithRetry(\"/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\n/**\n * The last commit this folder shares with GitHub: where its upstream branch\n * forked from HEAD, else HEAD itself. Undefined outside a git checkout.\n */\nfunction gitSyncBase(dir: string): string | undefined {\n const git = (...args: string[]) => {\n try {\n return execFileSync(\"git\", [\"-C\", dir, ...args], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim() || undefined;\n } catch {\n return undefined;\n }\n };\n return git(\"merge-base\", \"HEAD\", \"@{upstream}\") ?? git(\"rev-parse\", \"HEAD\");\n}\n\n/**\n * What the server needs to refuse an upload that would revert newer changes\n * in a GitHub-synced target. Unsynced targets ignore both fields.\n */\nfunction appendSyncFields(formData: FormData, dir: string, force?: boolean): void {\n if (force) {\n formData.append(\"force\", \"true\");\n return;\n }\n const base = gitSyncBase(dir);\n if (base) formData.append(\"git_base\", base);\n}\n\nasync function uploadRedeploy(\n appId: string,\n archive: Buffer,\n orgId: string | undefined,\n sync: { dir: string; force?: boolean; discardDraft?: boolean },\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 appendSyncFields(formData, sync.dir, sync.force);\n appendDraftFields(formData, sync.discardDraft);\n\n const res = await postFormWithRetry(`/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; code?: string };\n return { ok: false, error: redeployError(err, res.statusText) };\n}\n\n/**\n * An app with unpublished chat changes: this CLI can report a deploy that\n * joins them as a draft (`accepts_draft`), and --discard-draft replaces them.\n * Without the first, the server refuses rather than let the poll time out.\n */\nfunction appendDraftFields(formData: FormData, discardDraft?: boolean): void {\n formData.append(\"accepts_draft\", \"true\");\n if (discardDraft) formData.append(\"discard_draft\", \"true\");\n}\n\n/** The server's refusal text is written for CLIs that predate --discard-draft\n * (\"update the CLI\"); this one has the flag, so say it directly. */\nfunction redeployError(err: { error?: string; code?: string }, fallback: string): string {\n if (err.code === \"draft_pending\") {\n return (\n \"This app has unpublished changes from the chat, and this deploy would overwrite them. \" +\n \"Review and publish them in the dashboard first, or deploy again with --discard-draft to replace them.\"\n );\n }\n return err.error || fallback;\n}\n\n/**\n * Create an app from a GitHub repo. A 409 means the org already has this repo\n * deployed (or the derived slug is taken) — the caller decides update vs. new,\n * exactly like the local-directory path. Passing `createNew` is the deliberate\n * \"yes, a second copy\" opt-out.\n */\nasync function repoDeploy(\n opts: {\n repo: string;\n subdir?: string;\n name?: string;\n createNew?: boolean;\n orgId?: string;\n },\n): Promise<{ ok: true; data: DeploySuccess } | { ok: false; conflict: SlugConflict } | { ok: false; error: string }> {\n const res = await api.post(\n \"/v1/apps/deploy\",\n {\n repo: opts.repo,\n branch: \"main\",\n subdir: opts.subdir,\n name: opts.name,\n create_new: opts.createNew,\n },\n { orgId: opts.orgId },\n );\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\n/** Rebuild an existing app from its GitHub repo — same app id, so the slug,\n * hostname, token and database are all preserved. */\nasync function repoRedeploy(\n appId: string,\n opts: { repo: string; subdir?: string; discardDraft?: boolean },\n orgId?: string,\n): Promise<{ ok: true; data: DeploySuccess } | { ok: false; error: string }> {\n const res = await api.post(\n `/v1/apps/${appId}/redeploy`,\n {\n repo: opts.repo,\n branch: \"main\",\n subdir: opts.subdir,\n accepts_draft: true,\n ...(opts.discardDraft ? { discard_draft: true } : {}),\n },\n { orgId },\n );\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; code?: string };\n return { ok: false, error: redeployError(err, 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?.org_id && linkedProject.org_id !== match.id) {\n console.error(\n `This folder is linked to a different org (${linkedProject.org_slug ?? linkedProject.org_id}).\\n` +\n ` --org ${options.org} resolves to ${match.id}.\\n` +\n ` Re-link with \\`clawnify link\\`, or deploy from another directory.`,\n );\n process.exit(1);\n }\n return match.id;\n }\n // Honor the folder link's org_id whenever present (app linked or not). A\n // truly unlinked folder falls through to the workspace org (below), then the\n // global active org.\n if (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\n/** One-line explanation of what actually conflicted, for both the interactive\n * prompt and the non-TTY error. */\nfunction describeConflict(conflict: SlugConflict): string {\n const existing = conflict.existing_app_slug\n ? `'${conflict.existing_app_name}' (${conflict.existing_app_slug})`\n : `'${conflict.existing_app_name}'`;\n return conflict.error === \"app_from_repo_exists_in_org\"\n ? `This organization already has an app deployed from this repo: ${existing}.`\n : `Slug '${conflict.slug}' is taken in this organization (currently held by an app named ${existing}).`;\n}\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 ${describeConflict(conflict)}\\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 ${describeConflict(conflict)}\\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 | undefined,\n sync: { dir: string; force?: boolean },\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 appendSyncFields(formData, sync.dir, sync.force);\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\n/**\n * The org's existing website that deploying this folder would replace, or null.\n *\n * An org has one website, and the server deploys any upload over it, so a\n * freshly scaffolded folder silently replaced a live site's pages and theme.\n * A folder linked to the site is updating it, not replacing it. A synced site\n * steps aside too: a clone of its repo carries no link (.clawnify/ is\n * gitignored), and the server's sync guard already refuses a stale upload.\n * A lookup that fails exits: guessing \"no site\" would be the unsafe answer.\n */\nasync function websiteToReplace(\n orgId: string | undefined,\n linkedWebsiteId: string | undefined,\n): Promise<{ slug: string } | null> {\n const opts = orgId ? { orgId } : undefined;\n const res = await api.get(\"/v1/websites\", opts);\n if (!res.ok) {\n console.error(\n `Could not check this organization's existing website (HTTP ${res.status}). ` +\n `Retry, or pass --replace to deploy anyway.`,\n );\n process.exit(1);\n }\n const { website } = (await res.json()) as { website: { id: string; slug: string } | null };\n if (!website || website.id === linkedWebsiteId) return null;\n const links = await api.get(\"/v1/github/links\", opts);\n if (links.ok) {\n const data = (await links.json()) as { links?: Array<{ target: { type: string; slug?: string } }> };\n if (data.links?.some((l) => l.target.type === \"website\" && l.target.slug === website.slug)) return null;\n }\n return { slug: website.slug };\n}\n\nasync function refuseWebsiteReplace(\n orgId: string | undefined,\n linkedWebsiteId: string | undefined,\n options: DeployOptions,\n): Promise<void> {\n if (options.replace) return;\n const existing = await websiteToReplace(orgId, linkedWebsiteId);\n if (!existing) return;\n console.error(\n `This organization already has a website (${existing.slug}), and this folder isn't linked to it.\\n` +\n `Deploying replaces that site's pages, theme and code with this folder. The live site\\n` +\n `stays up until someone publishes.\\n\\n` +\n ` To edit the existing site: use the website editor in the dashboard, or ask an admin\\n` +\n ` to connect GitHub and work in a clone of the workspace repo.\\n` +\n ` To replace it on purpose: run this again with --replace.\\n`,\n );\n process.exit(EXIT_CONFLICT_NEEDS_DECISION);\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 // Not signed in → deploy into an unclaimed org (anonymous surface) instead\n // of dying at requireAuth. Must branch BEFORE org resolution — that path\n // makes authed calls. See lib/anon.ts.\n if (isLoggedOut() && !options.org) {\n if (options.dryRun) {\n const sizeKB = (archive.length / 1024).toFixed(1);\n console.log(`\\n Dry run — would deploy website '${baseName}' anonymously (astro)`);\n console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped\\n`);\n return;\n }\n const { ctx, created } = await getOrCreateAnonContext(resolvedDir, baseName, manifest?.deploy?.agents);\n console.log(\n created\n ? `No account detected — deploying ${baseName} to a temporary workspace...`\n : `Updating ${baseName} (temporary workspace)...`,\n );\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n formData.append(\"name\", baseName);\n const res = await anonPostForm(\"/v1/anon/websites/deploy\", formData, ctx);\n if (res.status === 401) explainAnonUnauthorized(resolvedDir);\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 const data = (await res.json()) as WebsiteDeployResponse;\n saveProject(resolvedDir, {\n ...(readProject(resolvedDir) ?? {}),\n kind: \"website\",\n org_id: ctx.org_id,\n website_id: data.website_id,\n slug: data.slug,\n anon: ctx,\n });\n const polled = await pollUntilReady(data.website_id, {\n kind: \"website\",\n anonToken: ctx.deploy_token,\n });\n if (polled.status === \"error\" || polled.status === \"failed\") {\n console.error(`\\n Deploy failed: ${polled.error || \"Unknown error\"}\\n`);\n process.exit(1);\n }\n console.log(`\\n ✓ Deployed to a private draft.\\n`);\n printClaimBlock(ctx);\n return;\n }\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 const existing = options.replace || linkedProject?.anon\n ? null\n : await websiteToReplace(orgId, linkedProject?.website_id);\n if (existing) {\n console.log(\n `\\n Note: this would replace the organization's existing website (${existing.slug}).` +\n `\\n A real deploy refuses unless you pass --replace.`,\n );\n }\n console.log();\n return;\n }\n\n // A folder still linked to a temporary workspace deploys into that\n // workspace's own site; the heal below re-checks against the real org.\n if (!linkedProject?.anon) await refuseWebsiteReplace(orgId, linkedProject?.website_id, options);\n console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);\n let result = await uploadWebsiteDeploy(archive, baseName, orgId, { dir: resolvedDir, force: options.force });\n // Stale anonymous link (deployed logged-out, then logged in without\n // claiming): the linked org isn't accessible to this account. Heal once —\n // drop the link, resolve the real org, redeploy. See lib/anon.ts.\n if (!result.ok && result.error === \"org_not_accessible\" && linkedProject?.anon) {\n orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);\n // The heal redeploys into the account's real org, which may already have a site.\n await refuseWebsiteReplace(orgId, undefined, options);\n result = await uploadWebsiteDeploy(archive, baseName, orgId, { dir: resolvedDir, force: options.force });\n }\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\ninterface AgentFile {\n path: string;\n content: string;\n}\n\n/** Recursively collect files under `root`, yielding each with a forward-slash\n * path relative to `root`. Silent no-op if `root` doesn't exist. */\nfunction walkFiles(root: string, cb: (rel: string, abs: string) => void): void {\n if (!fs.existsSync(root)) return;\n const walk = (cur: string, prefix: string) => {\n for (const name of fs.readdirSync(cur)) {\n const abs = path.join(cur, name);\n const rel = prefix ? `${prefix}/${name}` : name;\n if (fs.statSync(abs).isDirectory()) walk(abs, rel);\n else cb(rel, abs);\n }\n };\n walk(root, \"\");\n}\n\n/** Assemble an agent member's deployable payload: AGENT.md → AGENTS.md (the\n * file OpenClaw loads as instructions), every file under skills/, and the\n * top-level flows/*.json. Paths use forward slashes to match the hook's\n * allowlist. .gitkeep placeholders are skipped. */\nfunction assembleAgentFiles(dir: string): AgentFile[] {\n const out: AgentFile[] = [];\n\n const agentMd = path.join(dir, \"AGENT.md\");\n if (fs.existsSync(agentMd)) {\n out.push({ path: \"AGENTS.md\", content: fs.readFileSync(agentMd, \"utf8\") });\n }\n\n walkFiles(path.join(dir, \"skills\"), (rel, abs) => {\n if (path.basename(abs) === \".gitkeep\") return;\n out.push({ path: `skills/${rel}`, content: fs.readFileSync(abs, \"utf8\") });\n });\n\n const flowsDir = path.join(dir, \"flows\");\n if (fs.existsSync(flowsDir)) {\n for (const name of fs.readdirSync(flowsDir)) {\n if (!name.endsWith(\".json\")) continue;\n out.push({ path: `flows/${name}`, content: fs.readFileSync(path.join(flowsDir, name), \"utf8\") });\n }\n }\n\n return out;\n}\n\n/**\n * Deploy a workspace agent member: push AGENTS.md + skills/ + flows/ to a\n * named agent. The link (agent id + agent name) is saved to\n * .clawnify/project.json on first deploy, then reused.\n * The push is additive on the VPS — it never deletes agent-authored files.\n *\n * Nothing has to be passed for the usual single-agent org: resolveServerId\n * picks it, exactly as `agents pull/push` do. Only an org with several agents\n * is ever asked which one, and only then.\n */\nasync function deployAgent(dir: string | undefined, options: DeployOptions): Promise<void> {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const linked = readProject(resolvedDir);\n\n const serverId = await resolveServerId(options.server || linked?.server_id);\n const agentName = options.agent || linked?.agent_name || \"main\";\n\n const files = assembleAgentFiles(resolvedDir);\n if (files.length === 0) {\n console.error(\n `Nothing to deploy — no AGENT.md, skills/, or flows/ found in ${resolvedDir}.`,\n );\n process.exit(EXIT_USAGE);\n }\n\n // Org: explicit --org wins, else the saved link's org, else the workspace's.\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 orgId = match.id;\n } else {\n orgId = linked?.org_id || (await workspaceOrgId(resolvedDir));\n }\n\n if (options.dryRun) {\n console.log(`\\n Dry run — would deploy to agent \"${agentName}\" (${serverId})`);\n for (const f of files) {\n console.log(` ${f.path} (${Buffer.byteLength(f.content, \"utf8\")} bytes)`);\n }\n console.log();\n return;\n }\n\n console.log(`Deploying → agent \"${agentName}\" (${serverId})...`);\n const res = await api.post(\n `/servers/${serverId}/deploy-agent`,\n { agent: agentName, files },\n { orgId },\n );\n const data = (await res.json().catch(() => ({}))) as {\n error?: string;\n written?: string[];\n rejected?: string[];\n };\n if (!res.ok) {\n console.error(`Deploy failed: ${data.error || res.statusText}`);\n process.exit(1);\n }\n\n saveProject(resolvedDir, {\n kind: \"agent\",\n org_id: orgId,\n server_id: serverId,\n agent_name: agentName,\n });\n\n const written = data.written ?? [];\n const rejected = (data.rejected ?? []).filter(Boolean);\n console.log(`\\n ✓ Deployed ${written.length} file(s) to agent \"${agentName}\".`);\n if (rejected.length) {\n console.log(` Skipped (outside the agent payload allowlist): ${rejected.join(\", \")}`);\n }\n console.log();\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 if (kind === \"agent\") {\n return deployAgent(dir, options);\n }\n } catch (err) {\n console.error(`${(err as Error).message}`);\n process.exit(EXIT_USAGE);\n }\n }\n // An unmarked Astro site is a WEBSITE, not an app. Sites bootstrapped by\n // the platform shipped without a clawnify.json, so falling through here\n // deployed them down the app path: the sandbox added an app's\n // `worker-entry.ts`, the build died on `Could not resolve \"hono\"`, and the\n // org was left with a junk app named after the folder. Refuse with the\n // real instruction instead of guessing (the workspace-root guard above is\n // the same idea). Newly bootstrapped sites carry a manifest and never\n // reach this branch.\n if (\n !manifest &&\n (fs.existsSync(path.join(resolvedDir, \"astro.config.mjs\")) ||\n fs.existsSync(path.join(resolvedDir, \"astro.config.ts\"))) &&\n fs.existsSync(path.join(resolvedDir, \"src\", \"tree\"))\n ) {\n console.error(\n \"This looks like a Clawnify website, but it has no clawnify.json so it\\n\" +\n \"cannot be told apart from an app — deploying it as one creates a broken app.\\n\\n\" +\n \" Add a clawnify.json here:\\n\" +\n ' { \"version\": 1, \"name\": \"website\", \"website\": { \"framework\": \"astro\" } }\\n\\n' +\n \" Or push to the synced workspace repo, which rebuilds the site for you.\",\n );\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 // Initialized so TS accepts the anon-heal control flow (the redeploy\n // branch can defer assignment to the create block via needsCreate);\n // every surviving runtime path assigns before use.\n let appId = \"\";\n let slug = \"\";\n let appToken = \"\";\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 // Resolve exactly as the local-directory path below does: an explicit\n // --org wins, then the folder's link, then the workspace it sits in.\n // Passing (null, undefined) skipped the last two, so a --from deploy run\n // inside a pinned client workspace ignored the pin and fell through to\n // whichever org ensureOrg picked first. That case is now the common one:\n // every synced workspace repo carries a workspace.org pin.\n //\n // Resolved BEFORE the dry-run return so `--dry-run` can report the target\n // org. A dry run that won't tell you which tenant it would deploy into is\n // no use for the one mistake that actually costs something.\n const fromDir = process.cwd();\n const orgId = await resolveOrgId(options, readProject(fromDir), fromDir);\n\n if (options.dryRun) {\n console.log(\n `\\n Dry run — would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : \"\"}${options.name ? `, name: ${options.name}` : \"\"})` +\n `\\n Target org: ${orgId ?? \"(unresolved — would use your default org)\"}\\n`,\n );\n return;\n }\n console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : \"\"}...`);\n let result = await repoDeploy({ repo, subdir, name: options.name, orgId });\n\n // Same conflict machinery as the local-directory path below: a repeat\n // deploy of a repo the org already has updates that app rather than minting\n // a duplicate at a fresh random slug.\n if (!result.ok && \"conflict\" in result) {\n const decision = await resolveConflictDecision(options, result.conflict);\n\n if (decision === \"update\") {\n const existingSlug = result.conflict.existing_app_slug ?? result.conflict.slug;\n console.log(`Updating ${result.conflict.existing_app_name} (${existingSlug})...`);\n const redeployed = await repoRedeploy(\n result.conflict.existing_app_id,\n { repo, subdir, discardDraft: options.discardDraft },\n orgId,\n );\n if (!redeployed.ok) {\n console.error(`Deploy failed: ${redeployed.error}`);\n process.exit(1);\n }\n result = { ok: true, data: redeployed.data };\n } else if (decision === \"create\") {\n // The suggested slug is free in this org; `createNew` waives the\n // \"already deployed from this repo\" guard we just tripped.\n result = await repoDeploy({\n repo,\n subdir,\n name: result.conflict.suggested_slug,\n createNew: true,\n orgId,\n });\n } else {\n process.exit(EXIT_CONFLICT_NEEDS_DECISION);\n }\n }\n\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\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.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 assertDatabaseDdlPresent(resolvedDir, manifest);\n const { archive, files } = createArchive(resolvedDir);\n\n // Not signed in → anonymous surface (unclaimed org). Handles its own\n // poll + output and returns; the schema sync below needs the authed CLI\n // route, so it is skipped for anonymous deploys. See lib/anon.ts.\n if (isLoggedOut() && !options.org) {\n if (options.dryRun) {\n summarizeArchive(archive, files, framework, baseName);\n console.log(` Would deploy anonymously into a temporary workspace\\n`);\n return;\n }\n const { ctx, created } = await getOrCreateAnonContext(resolvedDir, baseName, manifest?.deploy?.agents);\n const isUpdate = Boolean(linkedProject?.app_id && linkedProject?.anon);\n console.log(\n created\n ? `No account detected — deploying ${baseName} to a temporary workspace...`\n : isUpdate\n ? `Updating ${baseName} (temporary workspace)...`\n : `Deploying ${baseName} (temporary workspace)...`,\n );\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n formData.append(\"name\", baseName);\n formData.append(\"framework\", framework);\n const anonPath = isUpdate\n ? `/v1/anon/apps/${linkedProject!.app_id}/redeploy`\n : \"/v1/anon/apps/deploy\";\n const res = await anonPostForm(anonPath, formData, ctx);\n if (res.status === 401) explainAnonUnauthorized(resolvedDir);\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 const data = (await res.json()) as DeploySuccess;\n saveProject(resolvedDir, {\n ...(readProject(resolvedDir) ?? {}),\n org_id: ctx.org_id,\n app_id: data.app_id,\n slug: data.slug,\n app_token: data.app_token,\n anon: ctx,\n });\n const polled = await pollUntilReady(data.app_id, { anonToken: ctx.deploy_token });\n if (polled.status === \"error\") {\n console.error(`\\n Deploy failed: ${polled.error || \"Unknown error\"}\\n`);\n process.exit(1);\n }\n // The ?token= is the app perimeter's link auth — only people with this\n // exact link can view the app until the workspace is claimed.\n console.log(`\\n ✓ Deployed (private link):`);\n console.log(` https://${data.slug}.apps.clawnify.com?token=${data.app_token}\\n`);\n printClaimBlock(ctx);\n return;\n }\n\n let 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 let needsCreate = !linkedProject?.app_id;\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 dir: resolvedDir,\n force: options.force,\n discardDraft: options.discardDraft,\n });\n if (result.ok) {\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 if (result.error === \"org_not_accessible\" && linkedProject.anon) {\n // Stale anonymous link (deployed logged-out, then logged in without\n // claiming). Redeploy can't cross orgs — the server scopes the app id\n // by org — so heal the link and fall through to the CREATE path in\n // the account's real org. See lib/anon.ts.\n orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);\n needsCreate = true;\n } else {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n }\n }\n if (needsCreate) {\n console.log(`Deploying ${baseName}...`);\n let result = await uploadDeploy(archive, baseName, framework, orgId);\n\n // Same stale-anonymous-link heal for folders whose anon deploy never\n // wrote an app_id (create-path 403).\n if (\n !result.ok &&\n !(\"conflict\" in result) &&\n result.error === \"org_not_accessible\" &&\n linkedProject?.anon\n ) {\n orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);\n result = await uploadDeploy(archive, baseName, framework, orgId);\n }\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 dir: resolvedDir,\n force: options.force,\n discardDraft: options.discardDraft,\n });\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 // The org matters: without it the status call resolves to the caller's\n // DEFAULT org, never finds an app deployed with --org, and spins until it\n // reports a timeout for a deploy that already succeeded.\n const result = await pollUntilReady(appId, { orgId: resolvedOrgId });\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 if (result.status === \"draft\") {\n // The app had unpublished changes from the chat: this deploy joined them\n // as a draft rather than publishing them on the way out.\n console.log(\n `\\n ✓ Deployed as a draft. ${slug} has unpublished changes from the chat, so this deploy joined them\\n` +\n ` instead of going live. Review and publish both in the dashboard:\\n` +\n ` https://app.clawnify.com/apps/${slug}\\n` +\n ` To replace those changes instead, deploy again with --discard-draft.\\n`,\n );\n } else {\n console.log(`\\n ✓ Deployed! ${url}\\n`);\n console.log(` Open: clawnify open ${slug}\\n`);\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 // Materializes .clawnify/drizzle.config.ts when the app has a schema.ts\n // (root config wins for older scaffolds); null = no drizzle schema.\n const drizzleConfig = ensureDrizzleConfig(resolvedDir);\n if (!drizzleConfig) return;\n\n await new Promise<void>((resolve) => {\n const proc = spawn(\"npx\", [\"drizzle-kit\", \"generate\", `--config=${drizzleConfig}`], {\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 // A spawn failure (drizzle-kit not installed, npx unavailable) used to be\n // swallowed entirely — the deploy then shipped an app with no DDL at all.\n proc.on(\"error\", (err) => {\n console.warn(` warning: could not run drizzle-kit generate (${String(err).slice(0, 160)}).`);\n resolve();\n });\n });\n}\n\n/**\n * An app that declares a database must ship DDL, or every query 500s at\n * runtime with \"no such table\" and nothing upstream reports a problem — the\n * build succeeds, the worker deploys, `status` goes live.\n *\n * Two accepted sources, matching the deploy pipeline: generated Drizzle\n * migrations (remapped to `drizzle/*.sql` on upload) or a hand-written\n * `schema.sql`. Missing both is a deploy that is already broken, so fail here\n * rather than let it reach production looking healthy.\n */\nfunction assertDatabaseDdlPresent(\n resolvedDir: string,\n manifest: ReturnType<typeof readManifest>,\n): void {\n if (!manifest?.app?.database) return;\n\n const hasSchemaSql =\n fs.existsSync(path.join(resolvedDir, \"schema.sql\")) ||\n fs.existsSync(path.join(resolvedDir, \"src/server/schema.sql\"));\n if (hasSchemaSql) return;\n\n const drizzleDir = path.join(resolvedDir, \".clawnify\", \"drizzle\");\n const hasDrizzleSql =\n fs.existsSync(drizzleDir) &&\n fs.readdirSync(drizzleDir).some((f) => f.endsWith(\".sql\"));\n if (hasDrizzleSql) return;\n\n console.error(\n `Deploy aborted: this app sets \"database\": true in clawnify.json, but no schema\\n` +\n `would be applied — so every query would fail at runtime with \"no such table\".\\n\\n` +\n ` Fix:\\n` +\n ` • npx clawnify@latest db generate (emits .clawnify/drizzle/*.sql from src/server/schema.ts)\\n` +\n ` If that just failed, see the warning above — drizzle-kit ships as a\\n` +\n ` devDependency, so run your package manager's install first.\\n` +\n ` • set \"database\": false (if this app genuinely has no database)\\n\\n` +\n ` schema.ts is the source of truth; a hand-written schema.sql at the app root\\n` +\n ` is also accepted, but only for apps not using Drizzle.`,\n );\n process.exit(1);\n}\n","import { loadAuth } from \"./auth.js\";\nimport { api, resolveOrgContext } from \"./api.js\";\nimport {\n readProject,\n saveProject,\n type ProjectConfig,\n type AnonContext,\n type PendingAgentSpec,\n} from \"./config.js\";\n\n// Anonymous deploys: no login → deploy into a real but UNCLAIMED org the\n// platform creates on the fly. The context (org id + ephemeral deploy token +\n// claim URL) lives in .clawnify/project.json — already gitignored by every\n// scaffold, and per-folder like every other project link. The human claims\n// the workspace at the claim URL; the deploy token dies at claim or after the\n// 72h window. See docs/internal/agent-experience.md.\n\nexport function isLoggedOut(): boolean {\n return !process.env.CLAWNIFY_TOKEN && !loadAuth();\n}\n\nfunction anonExpired(ctx: AnonContext): boolean {\n return new Date(ctx.claim_expires_at).getTime() <= Date.now();\n}\n\n/** Merge-save the anon context into the folder's project.json. */\nfunction saveAnon(dir: string, ctx: AnonContext, extra: Partial<ProjectConfig> = {}): void {\n const existing = readProject(dir) ?? {};\n saveProject(dir, { ...existing, ...extra, org_id: ctx.org_id, anon: ctx });\n}\n\n/** Drop a dead (expired/claimed) anon context so the next run starts fresh.\n * org_id and app_token must go too: they belong to the anonymous org, and a\n * surviving org_id re-targets every later deploy at an org the user isn't a\n * member of (403 org_not_accessible, forever). */\nexport function clearAnon(dir: string): void {\n const existing = readProject(dir);\n if (!existing?.anon) return;\n const {\n anon: _anon,\n app_id: _a,\n website_id: _w,\n slug: _s,\n org_id: _o,\n app_token: _t,\n ...rest\n } = existing;\n saveProject(dir, rest);\n}\n\n/**\n * Reuse the folder's anon context, or create a fresh unclaimed org.\n * Exits the process with a clear message when the API refuses (rate limit).\n */\nexport async function getOrCreateAnonContext(\n dir: string,\n name: string,\n agents?: PendingAgentSpec[],\n): Promise<{ ctx: AnonContext; created: boolean }> {\n const existing = readProject(dir)?.anon;\n if (existing && !anonExpired(existing)) {\n return { ctx: existing, created: false };\n }\n if (existing) clearAnon(dir);\n\n // `agents` = clawnify.json deploy.agents: the hires this workspace is meant\n // to make, shown on the claim page and consumed after claim.\n const res = await api.request(\"POST\", \"/claims/orgs\", {\n body: agents?.length ? { name, agents } : { name },\n });\n if (!res.ok) {\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(\n `Could not start an anonymous deploy: ${err.error || res.statusText}\\n` +\n ` You can always deploy signed in: clawnify login`,\n );\n process.exit(1);\n }\n const data = (await res.json()) as {\n org_id: string;\n deploy_token: string;\n claim_url: string;\n claim_expires_at: string;\n };\n const ctx: AnonContext = {\n org_id: data.org_id,\n deploy_token: data.deploy_token,\n claim_url: data.claim_url,\n claim_expires_at: data.claim_expires_at,\n };\n saveAnon(dir, ctx);\n return { ctx, created: true };\n}\n\nexport async function anonPostForm(path: string, formData: FormData, ctx: AnonContext) {\n return api.request(\"POST\", path, { formData, token: ctx.deploy_token });\n}\n\n/** 401 on the anon surface means the workspace was claimed or expired. */\nexport function explainAnonUnauthorized(dir: string): never {\n clearAnon(dir);\n console.error(\n \"This temporary workspace is no longer writable (claimed or expired).\\n\" +\n \" Run `clawnify deploy` again to start a fresh one, or sign in: clawnify login\",\n );\n process.exit(1);\n}\n\n/**\n * A signed-in deploy hit 403 org_not_accessible and the folder carries an\n * anonymous link: the anon org was claimed by someone else, expired and swept,\n * or simply never claimed before this account logged in. Heal by dropping the\n * stale link and resolving the org the retry should target (env pin →\n * workspace → account default, via resolveOrgContext so CLAWNIFY_ORG_ID is\n * honored). The claim URL is printed one last time first — clearing the link\n * destroys the only local copy, and the workspace may still be claimable.\n */\nexport async function healStaleAnonLink(\n dir: string,\n ctx: AnonContext,\n): Promise<string | undefined> {\n console.log(\"\\nThis folder was linked to a temporary workspace this account can't access.\");\n if (new Date(ctx.claim_expires_at).getTime() > Date.now()) {\n console.log(\"If nobody claimed it yet, it is still claimable:\");\n printClaimBlock(ctx);\n }\n clearAnon(dir);\n const orgId = await resolveOrgContext({ dir });\n console.log(\"Deploying into your own workspace instead...\\n\");\n return orgId;\n}\n\nexport function printClaimBlock(ctx: AnonContext): void {\n const hoursLeft = Math.max(\n 1,\n Math.round((new Date(ctx.claim_expires_at).getTime() - Date.now()) / 3600000),\n );\n console.log(\n ` Keep it: ${ctx.claim_url}\\n` +\n ` Sign in with Google there to make this workspace yours.\\n` +\n ` Unclaimed workspaces are deleted after ~${hoursLeft}h.\\n`,\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 fs from \"node:fs\";\nimport path from \"node:path\";\n\n// The drizzle config is a MANAGED artifact, not a user file — same rule as\n// .clawnify/wrangler.toml. It is materialized into .clawnify/ from convention\n// (schema at src/server/schema.ts; output pinned to .clawnify/drizzle, the\n// one path `clawnify dev` applies, deploy asserts on, and the upload archive\n// remaps into drizzle/). The user owns clawnify.json and src/ — nothing\n// toolchain-shaped at the app root.\n//\n// Back-compat: a root drizzle.config.ts (older scaffolds) wins when present,\n// so existing apps keep whatever they configured.\n\nconst MANAGED_CONFIG = `import { defineConfig } from \"drizzle-kit\";\n\n// Generated by the Clawnify CLI — do not edit. Derived from clawnify.json\n// (\"database\": true) and src/server/schema.ts; regenerated on every\n// dev / deploy / db generate run.\nexport default defineConfig({\n schema: \"./src/server/schema.ts\",\n out: \"./.clawnify/drizzle\",\n dialect: \"sqlite\",\n});\n`;\n\n/**\n * Returns the drizzle config path to pass to `drizzle-kit generate --config`,\n * materializing the managed one when needed — or null when the app has no\n * drizzle schema (no src/server/schema.ts), in which case callers fall back\n * to the legacy schema.sql path.\n */\nexport function ensureDrizzleConfig(resolvedDir: string): string | null {\n const schemaTs = path.join(resolvedDir, \"src/server/schema.ts\");\n if (!fs.existsSync(schemaTs)) return null;\n\n const rootConfig = path.join(resolvedDir, \"drizzle.config.ts\");\n if (fs.existsSync(rootConfig)) return rootConfig;\n\n const clawnifyDir = path.join(resolvedDir, \".clawnify\");\n fs.mkdirSync(clawnifyDir, { recursive: true });\n const managed = path.join(clawnifyDir, \"drizzle.config.ts\");\n fs.writeFileSync(managed, MANAGED_CONFIG);\n return managed;\n}\n","import { api } from \"./api.js\";\nimport { readProject } from \"./config.js\";\n\ninterface ServerRow {\n id: string;\n name: string | null;\n status: string;\n}\n\n/**\n * Resolve which agent to target: --agent-id wins, then a linked project\n * (.clawnify/project.json), then the org's single agent. Exits with a clear\n * message when the org has zero or several agents and none was specified.\n * Shared by the `sessions`, `agents` and `flows` commands.\n *\n * The id here is the underlying server UUID — every downstream route is still\n * keyed on it — but nothing user-facing says so. An org normally has exactly\n * one agent, so this resolves silently and the concept never surfaces.\n */\nexport async function resolveServerId(explicit: string | undefined): Promise<string> {\n if (explicit) return explicit;\n const linked = readProject()?.server_id;\n if (linked) return linked;\n\n const res = await api.get(\"/servers\");\n if (!res.ok) {\n console.error(\"Failed to list agents. Run `clawnify login` and try again.\");\n process.exit(1);\n }\n const { servers } = (await res.json()) as { servers: ServerRow[] };\n if (!servers || servers.length === 0) {\n console.error(\n \"No agents in this org yet. Hire one at https://app.clawnify.com.\",\n );\n process.exit(1);\n }\n if (servers.length === 1) return servers[0].id;\n\n console.error(\n \"This org has several agents — pick one with --agent-id <id> (see `clawnify agents list`):\\n\",\n );\n for (const s of servers) {\n console.error(` ${s.id} ${s.name ?? \"(unnamed)\"} [${s.status}]`);\n }\n process.exit(1);\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 /** Failure detail from the last errored build — set even when the stored\n * build log predates it, so always show it alongside the log. */\n error?: 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.error) {\n console.log(`\\n--- Last Error ---\\n`);\n console.log(data.error);\n }\n if (data.logs) {\n console.log(\"\\n--- Build Logs ---\\n\");\n console.log(data.logs);\n }\n}\n","/**\n * `clawnify sessions` — the FDE's observe verb.\n *\n * clawnify sessions [list] list stored sessions across ALL agents on\n * the org's server (main + specialists)\n * clawnify sessions history <key> read one session's transcript by key\n *\n * Backed by the org-scoped GET /servers/:id/sessions[/history] API (read-only,\n * ownership-checked). See docs/internal/fde-strategy.md.\n */\n\nimport { api } from \"../lib/api.js\";\nimport { resolveServerId } from \"../lib/servers.js\";\n\ninterface SessionRow {\n agentId: string;\n key: string;\n sessionId: string | null;\n updatedAt: string | null;\n model: string | null;\n}\n\ninterface ListOptions {\n server?: string;\n agent?: string;\n active?: string;\n limit?: string;\n json?: boolean;\n}\n\ninterface HistoryOptions {\n server?: string;\n agent?: string;\n limit?: string;\n json?: boolean;\n}\n\nexport async function sessionsListCommand(opts: ListOptions): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n const params = new URLSearchParams();\n if (opts.agent) params.set(\"agentId\", opts.agent);\n if (opts.active) params.set(\"activeMinutes\", opts.active);\n if (opts.limit) params.set(\"limit\", opts.limit);\n const qs = params.toString();\n\n const res = await api.get(`/servers/${serverId}/sessions${qs ? `?${qs}` : \"\"}`);\n if (!res.ok) {\n console.error(`Failed to list sessions (${res.status}).`);\n process.exit(1);\n }\n const data = (await res.json()) as {\n sessions: SessionRow[];\n totalCount?: number;\n hasMore?: boolean;\n };\n const sessions = data.sessions ?? [];\n\n if (opts.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n if (sessions.length === 0) {\n console.log(\"No sessions found.\");\n return;\n }\n\n const agentW = Math.max(5, ...sessions.map((s) => (s.agentId ?? \"\").length));\n const keyW = Math.max(3, ...sessions.map((s) => (s.key ?? \"\").length));\n console.log(\n `${\"Agent\".padEnd(agentW)} ${\"Key\".padEnd(keyW)} ${\"Updated\".padEnd(19)} Model`,\n );\n console.log(\n `${\"─\".repeat(agentW)} ${\"─\".repeat(keyW)} ${\"─\".repeat(19)} ${\"─\".repeat(20)}`,\n );\n for (const s of sessions) {\n const updated = (s.updatedAt ?? \"\").replace(\"T\", \" \").slice(0, 19);\n console.log(\n `${(s.agentId ?? \"\").padEnd(agentW)} ${(s.key ?? \"\").padEnd(keyW)} ${updated.padEnd(19)} ${s.model ?? \"\"}`,\n );\n }\n if (data.hasMore) {\n console.log(\n `\\n… more available — raise --limit (showing ${sessions.length}${data.totalCount ? ` of ${data.totalCount}` : \"\"}).`,\n );\n }\n}\n\nexport async function sessionsHistoryCommand(\n key: string,\n opts: HistoryOptions,\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n const params = new URLSearchParams();\n params.set(\"key\", key);\n if (opts.agent) params.set(\"agentId\", opts.agent);\n if (opts.limit) params.set(\"limit\", opts.limit);\n\n const res = await api.get(\n `/servers/${serverId}/sessions/history?${params.toString()}`,\n );\n if (!res.ok) {\n if (res.status === 404) {\n console.error(\n `No session found for key \"${key}\". List sessions with \\`clawnify sessions\\`.`,\n );\n } else {\n console.error(`Failed to read session (${res.status}).`);\n }\n process.exit(1);\n }\n const data = (await res.json()) as {\n agentId: string;\n key: string;\n sessionId: string | null;\n entries: unknown[];\n entryCount: number;\n totalLines: number;\n hasMore?: boolean;\n };\n\n if (opts.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n console.log(\n `agent: ${data.agentId} key: ${data.key} session: ${data.sessionId ?? \"?\"}`,\n );\n console.log(\n `${data.entryCount} entr${data.entryCount === 1 ? \"y\" : \"ies\"}${data.hasMore ? ` (of ${data.totalLines}; raise --limit for more)` : \"\"}\\n`,\n );\n // Raw JSONL transcript entries — one per line, so a coding agent can parse\n // them and a human can `| jq`.\n for (const entry of data.entries) {\n console.log(JSON.stringify(entry));\n }\n}\n","/**\n * `clawnify agents` — the FDE's agent-management verbs.\n *\n * clawnify agents [list] the org's agents, each with its sub-agents\n * clawnify agents pull [dir] fetch an agent's AGENTS.md + skills/ (+ flows/\n * for main only — flows belong to the main agent)\n * clawnify agents push [dir] push the edited files back (additive; the\n * agent picks them up next session, no restart)\n *\n * `list` renders the hierarchy as a tree — an agent and, nested under it, its\n * sub-agents. That shape is load-bearing: a flat list gave no way to tell an\n * existing agent from a missing one, which is how a coding agent read a\n * provisioned agent as absent and created a redundant sub-agent.\n *\n * Backed by GET /agents, GET /servers/:id/agent-config, and\n * POST /servers/:id/deploy-agent. See docs/internal/fde-strategy.md.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { api } from \"../lib/api.js\";\nimport { resolveServerId } from \"../lib/servers.js\";\nimport { readProject, saveProject } from \"../lib/config.js\";\n\ninterface SubAgentRow {\n id: string;\n name: string;\n status?: unknown;\n session_count?: number;\n}\n\ninterface OrgAgentRow {\n agent_id: string;\n name: string | null;\n status: string;\n region: string | null;\n sub_agents?: SubAgentRow[];\n sub_agents_unavailable?: boolean;\n}\n\ninterface AgentFile {\n path: string;\n content: string;\n}\n\ninterface CommonOpts {\n server?: string;\n agent?: string;\n}\n\nexport async function agentsListCommand(): Promise<void> {\n const res = await api.get(\"/agents\");\n if (!res.ok) {\n console.error(`Failed to list agents (${res.status}).`);\n process.exit(1);\n }\n const { agents } = (await res.json()) as { agents: OrgAgentRow[] };\n if (!agents || agents.length === 0) {\n console.log(\"No agents in this org yet. Hire one at https://app.clawnify.com.\");\n return;\n }\n\n // Tree, not a table: an agent's sub-agents are indented under it, so the\n // parent/child relationship is unmissable and no row can be misread as a\n // peer of the agent that owns it.\n for (const a of agents) {\n const label = a.name?.trim() || \"(unnamed)\";\n const meta = [a.status, a.region].filter(Boolean).join(\", \");\n console.log(`\\n${label}${meta ? ` (${meta})` : \"\"}`);\n console.log(` id: ${a.agent_id}`);\n\n if (a.sub_agents_unavailable) {\n console.log(\" sub-agents: unavailable (agent unreachable right now)\");\n continue;\n }\n const subs = a.sub_agents ?? [];\n if (subs.length === 0) {\n console.log(\" sub-agents: none\");\n continue;\n }\n console.log(\" sub-agents:\");\n for (const s of subs) {\n const sessions = s.session_count ?? 0;\n console.log(\n ` └─ ${s.id}${s.name && s.name !== s.id ? ` (${s.name})` : \"\"} ${sessions} session${sessions === 1 ? \"\" : \"s\"}`,\n );\n }\n }\n console.log();\n}\n\nexport async function agentsPullCommand(dir: string | undefined, opts: CommonOpts): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const agent = opts.agent || \"main\";\n\n const res = await api.get(`/servers/${serverId}/agent-config?agent=${encodeURIComponent(agent)}`);\n if (!res.ok) {\n if (res.status === 404) console.error(`No agent or sub-agent named \"${agent}\" in this org.`);\n else console.error(`Failed to read agent config (${res.status}).`);\n process.exit(1);\n }\n const { files } = (await res.json()) as { files: AgentFile[] };\n\n const target = dir ? path.resolve(dir) : process.cwd();\n fs.mkdirSync(target, { recursive: true });\n let written = 0;\n for (const f of files ?? []) {\n // The API only returns AGENTS.md / skills/** / flows/*.json, but guard the\n // returned path against traversal before writing to disk.\n const norm = path.posix.normalize(f.path);\n if (norm.startsWith(\"/\") || norm.split(\"/\").includes(\"..\")) continue;\n const abs = path.join(target, norm);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, f.content);\n written++;\n }\n\n // Remember server + agent so `clawnify agents push` targets the same place.\n const existing = readProject(target) ?? {};\n saveProject(target, { ...existing, kind: \"agent\", server_id: serverId, agent_name: agent });\n\n console.log(`Pulled ${written} file(s) for agent \"${agent}\" → ${target}`);\n console.log(`Edit AGENTS.md / skills / flows, then push: clawnify agents push${dir ? ` ${dir}` : \"\"}`);\n}\n\nexport async function agentsPushCommand(dir: string | undefined, opts: CommonOpts): Promise<void> {\n const target = dir ? path.resolve(dir) : process.cwd();\n const linked = readProject(target);\n const serverId = await resolveServerId(opts.server || linked?.server_id);\n const agent = opts.agent || linked?.agent_name || \"main\";\n\n const files: AgentFile[] = [];\n const add = (rel: string) => {\n try {\n files.push({ path: rel, content: fs.readFileSync(path.join(target, rel), \"utf8\") });\n } catch {\n /* file absent — skip */\n }\n };\n add(\"AGENTS.md\");\n const walk = (relDir: string) => {\n let names: string[];\n try {\n names = fs.readdirSync(path.join(target, relDir));\n } catch {\n return;\n }\n for (const name of names) {\n const rel = `${relDir}/${name}`;\n let isDir = false;\n try {\n isDir = fs.statSync(path.join(target, rel)).isDirectory();\n } catch {\n continue;\n }\n if (isDir) walk(rel);\n else add(rel);\n }\n };\n walk(\"skills\");\n let flowNames: string[] = [];\n try {\n flowNames = fs.readdirSync(path.join(target, \"flows\"));\n } catch {\n /* no flows dir */\n }\n for (const name of flowNames) if (name.endsWith(\".json\")) add(`flows/${name}`);\n\n if (files.length === 0) {\n console.error(`No agent files (AGENTS.md / skills / flows) found in ${target}. Run \\`clawnify agents pull\\` first.`);\n process.exit(1);\n }\n\n const res = await api.post(`/servers/${serverId}/deploy-agent`, { agent, files });\n if (!res.ok) {\n console.error(`Failed to push (${res.status}).`);\n process.exit(1);\n }\n console.log(\n `Pushed ${files.length} file(s) to agent \"${agent}\". Additive — the agent picks them up on its next session (no restart).`,\n );\n}\n\nexport async function agentsSkillsCommand(\n agent: string | undefined,\n opts: { server?: string },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const who = agent || \"main\";\n\n const res = await api.get(`/servers/${serverId}/agent-skills?agent=${encodeURIComponent(who)}`);\n if (!res.ok) {\n if (res.status === 404) console.error(`No agent or sub-agent named \"${who}\" in this org.`);\n else console.error(`Failed to read skills (${res.status}).`);\n process.exit(1);\n }\n const data = (await res.json()) as { agent: string; skills: unknown };\n\n // The EFFECTIVE inventory (workspace + shared managed-root + bundled, with\n // eligibility) as OpenClaw's loader reports it — richer than what's in the\n // agent's own workspace. Printed as JSON (the shape is OpenClaw's): a coding\n // agent parses it, a human can `| jq`.\n console.log(JSON.stringify(data.skills, null, 2));\n}\n\nexport async function agentsGrantSkillCommand(\n skill: string,\n opts: { server?: string; to?: string; all?: boolean },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n if (!opts.all && !opts.to) {\n console.error(\n \"Specify who gets the skill: --to <agent> (one sub-agent) or --all (every agent).\",\n );\n process.exit(1);\n }\n const scope = opts.all ? \"tree\" : \"agent\";\n const payload: Record<string, unknown> = { skill, action: \"grant\", scope };\n if (scope === \"agent\") payload.slug = opts.to;\n\n const res = await api.post(`/servers/${serverId}/agent-skills`, payload);\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n if (!res.ok) {\n // Grant symlinks an EXISTING main-workspace skill; a 404 means it isn't\n // authored yet, so point the FDE at the author step instead of a bare error.\n if (res.status === 404 && /source skill not found/i.test(data.error ?? \"\")) {\n console.error(\n `Skill \"${skill}\" isn't in the main agent's workspace, so there's nothing to grant yet.\\n` +\n `Author it first: clawnify agents pull ./main --agent main → add skills/${skill}/SKILL.md → clawnify agents push ./main`,\n );\n } else {\n console.error(`Failed to grant skill (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n }\n process.exit(1);\n }\n\n const who = opts.all ? \"every agent (shared managed root; includes future agents)\" : `agent \"${opts.to}\"`;\n console.log(`Granted skill \"${skill}\" to ${who}. Picked up on the agent's next session (no restart). Reversible.`);\n}\n\nexport async function agentsCreateCommand(\n slug: string,\n opts: { server?: string; name?: string; description?: string; yes?: boolean },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n // Creating an agent runs several openclaw calls and a synchronous gateway\n // restart (~20-40s) that briefly interrupts every agent on the box. Gate it\n // behind --yes so an autonomous FDE has to consciously confirm the disruption.\n if (!opts.yes) {\n console.error(\n `This creates agent \"${slug}\" and RESTARTS the gateway (~20-40s), briefly interrupting this agent and its sub-agents.\\n` +\n `Re-run with --yes once the user has confirmed: clawnify agents create ${slug} --yes`,\n );\n process.exit(1);\n }\n\n const payload: Record<string, unknown> = { slug };\n if (opts.name) payload.name = opts.name;\n if (opts.description) payload.description = opts.description;\n\n const res = await api.post(`/servers/${serverId}/agents`, payload);\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n if (!res.ok) {\n console.error(`Failed to create agent (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log(\n `Created agent \"${slug}\". The gateway was restarted and it onboards shortly. ` +\n `Author it with: clawnify agents pull ./${slug} --agent ${slug}`,\n );\n}\n","/**\n * `clawnify servers` — list the org's agent servers. An org can have several\n * (e.g. an agency managing multiple client boxes). This is the top of the\n * discovery tree the FDE walks: servers → `agents` → `sessions`. Backed by\n * GET /servers (org-scoped).\n */\n\nimport { api } from \"../lib/api.js\";\n\ninterface ServerRow {\n id: string;\n name: string | null;\n status: string;\n region?: string | null;\n}\n\nexport async function serversListCommand(): Promise<void> {\n const res = await api.get(\"/servers\");\n if (!res.ok) {\n console.error(`Failed to list servers (${res.status}).`);\n process.exit(1);\n }\n const { servers } = (await res.json()) as { servers: ServerRow[] };\n if (!servers || servers.length === 0) {\n console.log(\"No servers in this org yet. Provision one at https://app.clawnify.com.\");\n return;\n }\n\n const idW = Math.max(2, ...servers.map((s) => s.id.length));\n const nameW = Math.max(4, ...servers.map((s) => (s.name ?? \"\").length));\n console.log(`${\"ID\".padEnd(idW)} ${\"Name\".padEnd(nameW)} ${\"Status\".padEnd(10)} Region`);\n console.log(`${\"─\".repeat(idW)} ${\"─\".repeat(nameW)} ${\"─\".repeat(10)} ${\"─\".repeat(10)}`);\n for (const s of servers) {\n console.log(\n `${s.id.padEnd(idW)} ${(s.name ?? \"\").padEnd(nameW)} ${s.status.padEnd(10)} ${s.region ?? \"\"}`,\n );\n }\n}\n","/**\n * `clawnify env` — the org's custom environment variables, injected into every\n * agent's gateway. Reading is `clawnify connections list` (the customEnv\n * section); this sets/unsets. Org-scoped; setting or removing one restarts the\n * gateway to apply, so agents briefly reconnect.\n *\n * NOT for secrets: don't pass a real API key / secret here from an agent — it\n * exposes the value in the command line and the agent's context. Secrets belong\n * in the dashboard (Settings → Environment Variables / API Keys). Use this only\n * for non-secret config (a flag, a default, a public URL).\n */\n\nimport { api } from \"../lib/api.js\";\n\nexport async function envSetCommand(key: string, value: string): Promise<void> {\n const res = await api.post(\"/settings/custom-keys\", { key_name: key, key_value: value });\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n if (!res.ok) {\n console.error(`Failed to set ${key} (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log(`Set ${key} org-wide. The gateway restarts to apply — agents briefly reconnect.`);\n}\n\nexport async function envUnsetCommand(key: string): Promise<void> {\n const res = await api.del(`/settings/custom-keys/${encodeURIComponent(key)}`);\n if (!res.ok) {\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Failed to unset ${key} (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log(`Removed ${key} org-wide. The gateway restarts to apply.`);\n}\n","/**\n * `clawnify api <path>` — a raw authenticated request to the Clawnify API.\n * The escape hatch (à la `gh api` / `stripe get`): the porcelain covers the\n * common paths; this reaches anything without a dedicated command, so the CLI\n * never has to be complete to be useful. Same auth + org scoping as every other\n * command — it can only do what you can do.\n *\n * clawnify api /servers\n * clawnify api /servers/<id>/agents\n * clawnify api /servers/<id>/deploy-agent -X POST -d '{\"agent\":\"main\",\"files\":[...]}'\n */\n\nimport { api, resolveOrgContext } from \"../lib/api.js\";\n\nexport async function apiCommand(\n path: string,\n opts: { method?: string; data?: string; org?: string },\n): Promise<void> {\n const method = (opts.method || (opts.data !== undefined ? \"POST\" : \"GET\")).toUpperCase();\n\n let body: unknown;\n if (opts.data !== undefined) {\n try {\n body = JSON.parse(opts.data);\n } catch {\n console.error(\"-d/--data must be valid JSON.\");\n process.exit(1);\n }\n }\n\n const p = path.startsWith(\"/\") ? path : `/${path}`;\n // --org goes through the shared resolver, never straight onto the wire: the\n // flag's own help says \"slug-or-id\", and only the resolver turns a slug into\n // the UUID the header needs. It also refuses when the flag contradicts the\n // folder this is being run from. Passing the raw string here instead is how\n // `--org <slug>` used to read and write another org entirely.\n const orgId = await resolveOrgContext({ orgFlag: opts.org });\n const res = await api.call(method, p, { body, orgId });\n\n const text = await res.text();\n let out = text;\n try {\n out = JSON.stringify(JSON.parse(text), null, 2);\n } catch {\n /* not JSON — pass through verbatim */\n }\n\n if (!res.ok) {\n console.error(`HTTP ${res.status}`);\n if (out) console.error(out);\n process.exit(1);\n }\n if (out) console.log(out);\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, getValidToken } from \"../lib/auth.js\";\nimport { api, resolveOrgContext } from \"../lib/api.js\";\n\nexport async function whoamiCommand(): Promise<void> {\n const envToken = process.env.CLAWNIFY_TOKEN;\n const auth = loadAuth();\n\n if (!auth && !envToken) {\n console.log(\"Not logged in\");\n return;\n }\n\n const email = getEmailFromToken(envToken ?? auth!.access_token) ?? \"unknown\";\n console.log(`Email: ${email}`);\n // Resolved for THIS directory — whoami must report the org the next\n // command in this folder would actually use.\n const orgId = await resolveOrgContext();\n if (orgId) {\n console.log(`Org: ${orgId}`);\n }\n\n // A local JWT decode is NOT a liveness check — the refresh-token family can be\n // revoked while the cached access token still decodes fine, so `whoami` would\n // print a healthy identity while every real call 401s. Verify against the\n // server (this also self-heals a locally-expired token via getValidToken).\n const token = await getValidToken();\n if (!token) {\n console.log(\"Status: session expired — run `clawnify login`\");\n process.exitCode = 1;\n return;\n }\n\n try {\n const res = await api.request(\"GET\", \"/v1/orgs\", { token });\n if (res.ok) {\n console.log(\"Status: active\");\n } else if (res.status === 401) {\n console.log(\"Status: session expired — run `clawnify login`\");\n process.exitCode = 1;\n } else {\n console.log(`Status: could not verify (HTTP ${res.status})`);\n process.exitCode = 1;\n }\n } catch {\n // Network unreachable — the identity above is still valid locally; we just\n // couldn't confirm liveness. Don't crash or claim the session is dead.\n console.log(\"Status: could not reach the server (offline?)\");\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\" | \"agent\";\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\" || opts?.type === \"agent\") {\n return opts.type;\n }\n if (opts?.type) {\n console.error(`Unknown --type '${opts.type}' (expected 'app', 'website', or 'agent').`);\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(\" 3) agent — an OpenClaw agent (instructions, skills, flows)\");\n console.log();\n const choice = (await ask(\"Type [1]: \")) || \"1\";\n if (choice === \"2\") return \"website\";\n if (choice === \"3\") return \"agent\";\n return \"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 if (type === \"agent\") {\n return initAgent(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 // v5 — wrangler >=4.114 declares a peer of ^5.x, and npm (unlike pnpm)\n // hard-fails the install on the conflict if this is pinned to ^4.\n \"@cloudflare/workers-types\": \"^5.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 // Floor must be a PUBLISHED version at scaffold time — an unpublished\n // pin fails the whole install (and with it drizzle-kit, vite, …).\n // Caret picks up newer releases automatically.\n clawnify: \"^0.16.1\",\n \"drizzle-kit\": \"^0.31.0\",\n tailwindcss: \"^4.0.0\",\n // `vite build` only transpiles — it never typechecks — so without this the\n // scaffold ships with no way to catch a type error before deploy.\n typescript: \"^5.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 // Referenced by the generated schema.ts comment and the starter UI, and\n // run implicitly by `clawnify deploy`. It must exist as a script or\n // following the app's own instructions fails with \"Missing script\".\n // Delegates to the CLI, which materializes the managed drizzle config\n // in .clawnify/ before invoking drizzle-kit (lib/drizzle.ts).\n \"db:generate\": \"clawnify db generate\",\n typecheck: \"tsc --noEmit\",\n deploy: \"clawnify deploy\",\n },\n dependencies: {\n \"@clawnify/app\": \"^0.4.3\",\n \"@clawnify/db\": \"^0.4.3\",\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\", \"workerd\"] },\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 it — read the org\n * with \\`orgId(c)\\` from \\`@clawnify/app\\` (never parse headers yourself).\n * See https://github.com/clawnify/skills/tree/main/skills/build-a-clawnify-app\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 // No drizzle.config.ts at the root: like .clawnify/wrangler.toml, the\n // drizzle config is a managed artifact the CLI materializes into\n // .clawnify/ from clawnify.json + src/server/schema.ts (lib/drizzle.ts).\n // The user owns clawnify.json and src/ — nothing toolchain-shaped at the\n // app root. Edit schema.ts; dev/deploy handle the rest.\n\n // src/server/index.ts\n if (storage) {\n write(targetDir, \"src/server/index.ts\", `import { createApp, type AppEnv } from \"@clawnify/app\";\nimport { initUploads } from \"./uploads\";\nimport api from \"./routes\";\n\ntype Env = AppEnv & { Bindings: { UPLOADS: R2Bucket } };\n\n// createApp returns an OpenAPIHono with API discovery already mounted —\n// GET /api/openapi.json + GET /llms.txt, generated from your live routes.\n// That descriptor is how agents discover this app; never hand-write it.\n// db:false — routes read the database per request via getDB(c.env).\nconst app = createApp<Env>({ title: \"${name}\", version: \"1.0.0\", db: false });\n\napp.use(\"*\", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route(\"/\", api);\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 { createApp } from \"@clawnify/app\";\nimport api from \"./routes\";\n\n// createApp returns an OpenAPIHono with API discovery already mounted —\n// GET /api/openapi.json + GET /llms.txt, generated from your live routes.\n// That descriptor is how agents discover this app; never hand-write it.\n// db:false — routes read the database per request via getDB(c.env).\nconst app = createApp({ title: \"${name}\", version: \"1.0.0\", db: false });\n\napp.route(\"/\", api);\n\nexport default app;\n`);\n }\n\n // src/client/index.css — ships the DESIGN.md tokens so apps don't hand-roll\n // them. DESIGN.md claims both modes \"come free from the tokens and template\";\n // they only do if the template actually contains them.\n write(targetDir, \"src/client/index.css\", `@import \"tailwindcss\";\n\n/* Design tokens. Rebrand by editing values here — no component file should\n contain a raw hex, font name, or fixed pixel value. */\n@theme {\n --color-background: #ffffff;\n --color-surface: #ffffff;\n --color-surface-sunken: #f1f5f9;\n --color-foreground: #1a202c;\n --color-muted: #475569;\n --color-faint: #94a3b8;\n --color-border: #e2e8f0;\n --color-ring: #2563eb;\n --color-primary: #dd5164;\n --color-primary-hover: #c53a4e;\n --color-on-primary: #ffffff;\n --color-success: #047857;\n --color-success-tint: #ecfdf5;\n --color-warning: #b45309;\n --color-warning-tint: #fffbeb;\n --color-danger: #b91c1c;\n --color-danger-tint: #fef2f2;\n --font-sans: Inter, ui-sans-serif, system-ui, sans-serif;\n}\n\n/* Dark MUST override the custom properties in a plain rule. Tailwind v4 hoists\n and merges every @theme block and drops the surrounding media condition, so a\n nested \\`@media { @theme { … } }\\` silently makes dark the *unconditional*\n default and light never renders. Light stays the default; dark is opt-in by\n system preference. */\n@media (prefers-color-scheme: dark) {\n :root {\n --color-background: #0d1117;\n --color-surface: #161b22;\n --color-surface-sunken: #1c2128;\n --color-foreground: #e6edf3;\n --color-muted: #9ba7b3;\n --color-faint: #6e7681;\n --color-border: #30363d;\n --color-ring: #4493f8;\n --color-success: #3fb950;\n --color-success-tint: #12261e;\n --color-warning: #d29922;\n --color-warning-tint: #2a2210;\n --color-danger: #f85149;\n --color-danger-tint: #2d1518;\n }\n}\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\nasync function initAgent(dir?: string, opts?: InitOptions): Promise<void> {\n const yes = !!opts?.yes;\n const dirArgName = dir ? path.basename(path.resolve(dir)) : undefined;\n const name =\n opts?.name ||\n (yes ? (dirArgName ?? \"my-agent\") : (await ask(\"Agent name: \")) || \"my-agent\");\n const slug = slugify(name);\n // Inside a workspace (and with no explicit dir), agents live under agents/.\n // 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, \"agents\", slug) : path.resolve(slug);\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 // clawnify.json — the `agent` block discriminates the kind (mirrors\n // app/website/workspace); `harness` selects the runtime adapter.\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 agent: { harness: \"openclaw\" },\n }, null, 2));\n\n // AGENT.md — the agent's instructions (its \"system prompt\" as prose).\n write(targetDir, \"AGENT.md\", `# ${name}\n\nYou are ${name}, an OpenClaw agent.\n\nDescribe the agent's role, tone, and boundaries here. This file is the\nagent's primary instructions — edit it to shape behavior.\n\n## Skills\n\nReusable procedures live under \\`skills/<name>/\\`: a \\`SKILL.md\\` the agent\nreads when triggered, plus a \\`skill.json\\` describing when it runs.\n\n## Flows\n\nAutomations live under \\`flows/<name>.json\\` — ClawFlow definitions that run\non triggers (webhooks, schedules) without a full agent turn.\n`);\n\n // Payload dirs the OpenClaw adapter deploys (see ADR § Layer 1). Kept in\n // git even when empty so the layout is discoverable.\n write(targetDir, \"skills/.gitkeep\", \"\");\n write(targetDir, \"flows/.gitkeep\", \"\");\n\n // .gitignore — the ADR's hard secret-exclusion guard: credentials, env, and\n // runtime state (memories, sessions, logs) are never shipped with the agent.\n // Each installer brings their own keys.\n write(targetDir, \".gitignore\", `node_modules\n.clawnify\n.env*\n!.env.example\n.dev.vars\n# Runtime state — never shipped with the agent (ADR § secret-exclusion)\nmemories/\nsessions/\nlogs/\n`);\n\n const rel = path.relative(process.cwd(), targetDir) || \".\";\n console.log();\n console.log(` Created agent ${name} in ${rel}/`);\n console.log();\n console.log(\" Layout:\");\n console.log(\" AGENT.md — the agent's instructions\");\n console.log(\" skills/ — reusable procedures (SKILL.md + skill.json)\");\n console.log(\" flows/ — ClawFlow automations (<name>.json)\");\n console.log();\n console.log(\" Author here and commit. Deploying this (config push to the\");\n console.log(\" running agent via CAP) lands in a follow-up.\");\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, PageQuery, pageParams, pagedResponse, type AppEnv } from \"@clawnify/app\";\nimport { getDB, desc, like } from \"@clawnify/db\";\nimport * as schema from \"./schema\";\n\nconst api = new OpenAPIHono<AppEnv>();\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 // Every list endpoint pages: an agent reads this API through one tool,\n // and an unbounded list would land in its context whole.\n request: { query: PageQuery },\n responses: { 200: pagedResponse(\"items\", ItemSchema) },\n }),\n async (c) => {\n const { page, limit, offset, search } = pageParams(c.req.valid(\"query\"));\n const db = getDB(c.env, { schema });\n const where = search ? like(schema.items.name, \"%\" + search + \"%\") : undefined;\n const total = await db.$count(schema.items, where);\n const items = await db\n .select()\n .from(schema.items)\n .where(where)\n .orderBy(desc(schema.items.createdAt))\n .limit(limit)\n .offset(offset);\n return c.json({ items, total, page, limit }, 200);\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/skills/tree/main/skills/build-a-clawnify-app\" target=\"_blank\" rel=\"noreferrer\" className=\"underline underline-offset-2\">\n the build-a-clawnify-app skill\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, PageQuery, pageParams, pagedResponse, type AppEnv } from \"@clawnify/app\";\nimport { getDB, eq, desc, like } from \"@clawnify/db\";\nimport * as schema from \"./schema\";\n\nconst api = new OpenAPIHono<AppEnv>();\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 // Every list endpoint pages: an agent reads this API through one tool,\n // and an unbounded list would land in its context whole.\n request: { query: PageQuery },\n responses: { 200: pagedResponse(\"items\", ItemSchema) },\n }),\n async (c) => {\n const { page, limit, offset, search } = pageParams(c.req.valid(\"query\"));\n const db = getDB(c.env, { schema });\n const where = search ? like(schema.items.title, \"%\" + search + \"%\") : undefined;\n const total = await db.$count(schema.items, where);\n const items = await db\n .select()\n .from(schema.items)\n .where(where)\n .orderBy(desc(schema.items.createdAt))\n .limit(limit)\n .offset(offset);\n return c.json({ items, total, page, limit }, 200);\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 400: { description: \"Nothing to update\", 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()) as { items: Item[] }).items);\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.20.3\";\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 + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts as the single schema source of truth (DDL generated via pnpm db:generate), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and platform-injected identity via user()/orgId()/caller(). 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 exactly what `clawnify init` scaffolds and what the platform\\nexpects.\\n\\n## TL;DR\\n\\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\\n identity) + Tailwind v4. Nothing else.\\n- **Schema lives in `schema.ts` alone** — the Drizzle DSL your queries\\n compile against. The DDL is generated from it (`pnpm db:generate` →\\n `.clawnify/drizzle/*.sql`); never hand-write a `schema.sql` in a\\n scaffolded app.\\n- **Queries through `getDB`** — `import { getDB, eq } from\\n \\\"@clawnify/db\\\"`. JSON columns auto-serialize.\\n- **API routes are `OpenAPIHono` + `createRoute`** — Zod-validated\\n request/response.\\n- **`createApp()`** (from `@clawnify/app`) builds the entry — it returns an\\n `OpenAPIHono` with API discovery already mounted (`/api/openapi.json` +\\n `/llms.txt`, generated from your live routes). That descriptor *is* the\\n tool surface agents discover. Never hand-write those routes.\\n- **One import.** `@clawnify/app` re-exports `createRoute`, `z` and\\n `OpenAPIHono`, and adds `user` / `orgId` / `caller`. Import from it, not\\n from `@clawnify/routes` directly.\\n- **`clawnify.json`** declares framework, env, and public routes.\\n There is no `api.tools[]` — the agent discovers and calls your\\n endpoints via `/llms.txt` (and the OpenAPI spec).\\n- **Identity is injected by the platform** — read it with `user(c)` /\\n `orgId(c)` / `caller(c)` from `@clawnify/app`. Your app never\\n authenticates anyone.\\n\\n## Stack rationale\\n\\nOne template, one set of decisions. Don't deviate unless the user has\\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\\n`blank` template (one GET route + a page) or a `crud` template (a\\ntable with list/create/update/delete + a form). Both share the exact\\nsame stack below.\\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 ← @vitejs/plugin-react + @tailwindcss/vite; proxies /api → :8787\\n index.html\\n .gitignore\\n .clawnify/ ← Managed by the CLI (gitignored) — never edit\\n wrangler.toml ← Generated wrangler config\\n drizzle.config.ts ← Generated drizzle config (from clawnify.json + schema.ts)\\n drizzle/ ← Generated migration SQL (applied by dev + deploy)\\n applied-migrations.json ← Local-apply tracker\\n src/\\n server/\\n index.ts ← OpenAPIHono entry — mounts routes, serves /api/openapi.json\\n routes.ts ← OpenAPIHono + createRoute definitions — the API surface\\n schema.ts ← Drizzle table definitions — the single source of truth\\n worker-env.d.ts ← Cloudflare Workers types reference\\n uploads.ts ← R2 helpers (only when storage is enabled)\\n client/\\n main.tsx ← React mount point\\n app.tsx ← Root component (plain fetch against /api/*)\\n index.css ← @import \\\"tailwindcss\\\"\\n```\\n\\n## Schema — `schema.ts` is the single source of truth\\n\\n`schema.ts` (Drizzle DSL) defines the tables. Do **not** hand-write a\\n`schema.sql` in a scaffolded app, and there is no toolchain config to\\nmaintain: the drizzle config is a managed artifact the CLI materializes\\ninto `.clawnify/` (from `clawnify.json` + the schema path), and the DDL\\nis generated from `schema.ts` into `.clawnify/drizzle/*.sql` — which is\\nwhat `clawnify dev` applies locally and the deploy applies to your D1.\\n\\nThe scaffold's starter table (blank template):\\n\\n```ts\\n// src/server/schema.ts\\nimport { sqliteTable, text, integer } from \\\"@clawnify/db\\\";\\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\\nReal apps are multi-tenant. Every user-facing table carries an\\n`org_id`, every query filters by it. JSON columns and indexes use the\\nDrizzle DSL re-exported from `@clawnify/db`:\\n\\n```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## Generating the DDL — automatic, or `clawnify db generate`\\n\\n`clawnify dev` and `clawnify deploy` (local-directory deploys) generate\\nthe migration SQL themselves — editing `schema.ts` and running dev or\\ndeploy is the whole workflow. To refresh the SQL explicitly without\\neither, run `npx clawnify@latest db generate` (the scaffold's\\n`pnpm db:generate` is an alias for it). Always invoke the CLI as\\n`npx clawnify@latest` — never a global or pinned install. Deploy refuses a database-enabled app with no DDL,\\nso a broken generate fails loudly, not silently.\\n\\nOne artifact to leave alone: after a successful signed-in deploy the CLI\\nsyncs a read-only `schema.sql` snapshot of the DEPLOYED schema into the\\napp root. It is generated output for reference/diffing — never edit it,\\nand never treat it as the source of truth (`schema.ts` is).\\n\\nRules:\\n- Deploys are **additive**: new tables and columns are added\\n automatically. Destructive changes (dropping or retyping a column) are\\n not applied automatically — do those deliberately, and never drop a\\n table with user data unless explicitly asked.\\n- Never edit the generated `.clawnify/drizzle/*.sql` by hand — change\\n `schema.ts` and regenerate.\\n- A hand-written `schema.sql` at the app root is accepted **only** for\\n apps that don't use Drizzle at all (e.g. some template repos). A\\n scaffolded app never needs one.\\n\\n## `src/server/index.ts` — the entry\\n\\n```ts\\nimport { createApp } from \\\"@clawnify/app\\\";\\nimport api from \\\"./routes\\\";\\n\\n// db:false — this app reads the database per request via getDB(c.env),\\n// which needs no init middleware.\\nconst app = createApp({ title: \\\"My app\\\", version: \\\"1.0.0\\\", db: false });\\n\\napp.route(\\\"/\\\", api);\\n\\nexport default app;\\n```\\n\\nThe entry is thin: `createApp()` then mount your routes. `createApp`\\nreturns an `OpenAPIHono` with **API discovery already mounted** — it\\nserves both `/api/openapi.json` (generated from your `createRoute`\\ndefinitions, with schemas) **and** `/llms.txt` (the same, agent-readable).\\nAny `/api/*` route written as a plain `app.get` with no `createRoute` is\\nstill listed from the live route table, so the endpoint inventory is\\nalways complete. **Never hand-write a `/openapi.json` or `/llms.txt`\\nhandler** — and don't call `mountDiscovery` yourself; `createApp` did it.\\n\\nWhen storage (file uploads) is enabled, the entry also wires the R2\\nbucket in a middleware before mounting routes:\\n\\n```ts\\nimport { createApp, type AppEnv } from \\\"@clawnify/app\\\";\\nimport { initUploads } from \\\"./uploads\\\";\\nimport api from \\\"./routes\\\";\\n\\ntype Env = AppEnv & { Bindings: { UPLOADS: R2Bucket } };\\n\\nconst app = createApp<Env>({ title: \\\"My app\\\", version: \\\"1.0.0\\\", db: false });\\n\\napp.use(\\\"*\\\", async (c, next) => {\\n initUploads(c.env.UPLOADS);\\n await next();\\n});\\n\\napp.route(\\\"/\\\", api);\\n\\nexport default app;\\n```\\n\\n## `src/server/routes.ts` — routes with `createRoute`\\n\\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\\ndefinition paired with a handler via `api.openapi(route, handler)`.\\nRequest bodies and params are Zod-validated (`c.req.valid(\\\"json\\\")`,\\n`c.req.valid(\\\"param\\\")`); response shapes are declared with\\n`.openapi(\\\"Name\\\")` Zod schemas so they land in the generated spec.\\n\\nBlank template — one read route:\\n\\n```ts\\nimport { OpenAPIHono, createRoute, z, PageQuery, pageParams, pagedResponse, type AppEnv } from \\\"@clawnify/app\\\";\\nimport { getDB, desc, like } from \\\"@clawnify/db\\\";\\nimport * as schema from \\\"./schema\\\";\\n\\nconst api = new OpenAPIHono<AppEnv>();\\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 // Every list endpoint pages: an agent reads this API through one tool,\\n // and an unbounded list would land in its context whole.\\n request: { query: PageQuery },\\n responses: { 200: pagedResponse(\\\"items\\\", ItemSchema) },\\n }),\\n async (c) => {\\n const { page, limit, offset, search } = pageParams(c.req.valid(\\\"query\\\"));\\n const db = getDB(c.env, { schema });\\n const where = search ? like(schema.items.name, \\\"%\\\" + search + \\\"%\\\") : undefined;\\n const total = await db.$count(schema.items, where);\\n const items = await db\\n .select()\\n .from(schema.items)\\n .where(where)\\n .orderBy(desc(schema.items.createdAt))\\n .limit(limit)\\n .offset(offset);\\n return c.json({ items, total, page, limit }, 200);\\n },\\n);\\n\\nexport default api;\\n```\\n\\nCRUD template — the full list/create/update/delete surface:\\n\\n```ts\\nimport { OpenAPIHono, createRoute, z, PageQuery, pageParams, pagedResponse, type AppEnv } from \\\"@clawnify/app\\\";\\nimport { getDB, eq, desc, like } from \\\"@clawnify/db\\\";\\nimport * as schema from \\\"./schema\\\";\\n\\nconst api = new OpenAPIHono<AppEnv>();\\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 // Every list endpoint pages: an agent reads this API through one tool,\\n // and an unbounded list would land in its context whole.\\n request: { query: PageQuery },\\n responses: { 200: pagedResponse(\\\"items\\\", ItemSchema) },\\n }),\\n async (c) => {\\n const { page, limit, offset, search } = pageParams(c.req.valid(\\\"query\\\"));\\n const db = getDB(c.env, { schema });\\n const where = search ? like(schema.items.title, \\\"%\\\" + search + \\\"%\\\") : undefined;\\n const total = await db.$count(schema.items, where);\\n const items = await db\\n .select()\\n .from(schema.items)\\n .where(where)\\n .orderBy(desc(schema.items.createdAt))\\n .limit(limit)\\n .offset(offset);\\n return c.json({ items, total, page, limit }, 200);\\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 400: { description: \\\"Nothing to update\\\", 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\\nPatterns to follow:\\n- **Give every route a clear `summary`/`description`.** The generated\\n OpenAPI spec is what the agent reads to decide which endpoint to\\n call — a vague summary makes your endpoint invisible in practice.\\n- **Validate input with Zod** via `request.body` / `request.params`\\n and read it with `c.req.valid(\\\"json\\\")` / `c.req.valid(\\\"param\\\")`.\\n Never parse `c.req.raw` by hand.\\n- **Declare response shapes** with `.openapi(\\\"Name\\\")` schemas — they\\n become the documented return type in the spec.\\n- **Filter by the org** on every user-facing query (see \\\"who is\\n calling\\\" below). No exceptions.\\n\\n## `src/server` — who is calling\\n\\nThe platform authenticates every caller at its perimeter and injects a\\nverified identity onto the request (it strips any client-supplied\\nversion first, so it can't be spoofed). Your app never authenticates\\nanyone: no `Authorization`, no cookies, no JWT, no login screen.\\n\\nRead it with the helpers from `@clawnify/app` — don't parse headers\\nyourself:\\n\\n```ts\\nimport { user, orgId, caller } from \\\"@clawnify/app\\\";\\n\\napp.get(\\\"/api/notes\\\", async (c) => {\\n const org = orgId(c);\\n if (!org) return c.json({ error: \\\"unauthorized\\\" }, 401);\\n\\n const db = getDB(c.env, { schema });\\n return c.json(\\n await db.select().from(schema.notes).where(eq(schema.notes.orgId, org)),\\n );\\n});\\n```\\n\\n| Helper | Returns |\\n|--------|---------|\\n| `orgId(c)` | Organization UUID — the tenant key. Filter every user-facing query by it. |\\n| `user(c)` | `{ id, email, name, avatarUrl, firstName, lastName }` — or **`null`** when the caller isn't a person. |\\n| `caller(c)` | `user`, `api`, `agent`, `agent-browser`, `public`, `bypass`, `system`, or `app`. |\\n\\nTwo rules that catch people out:\\n\\n- **`user(c)` is null for five of the eight caller kinds**\\n (`agent-browser`, `public`, `bypass`, `system`, `app`). Always handle\\n the null case — don't assume a person is present just because a\\n request arrived. For per-user rows, store `user(c).id` in a `user_id`\\n column and filter on it, exactly as you filter on `org_id`.\\n- **`firstName` / `lastName` are a heuristic** split of a single stored\\n full name (first word / the rest). Fine for a greeting; never persist\\n them or treat them as someone's legal name — store `name`.\\n\\nDon't build app-level users, roles, or permissions. Authorization\\nalready happened at the perimeter.\\n\\n## `src/client` — React + plain fetch\\n\\nThe client mounts React and talks to the API with plain `fetch`\\nagainst the `/api/*` routes. No data-layer library is scaffolded.\\n\\n```tsx\\n// src/client/main.tsx\\nimport { 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```tsx\\n// src/client/app.tsx (CRUD template shape)\\nimport { 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()) as { items: Item[] }).items);\\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 // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\\n\\n return (\\n <div className=\\\"max-w-xl mx-auto mt-10 px-4\\\">\\n {/* form + list */}\\n </div>\\n );\\n}\\n```\\n\\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\\n`vite.config.ts`), so the same relative fetch paths work in dev and\\nin production. The API is the one contract: the UI calls it over\\n`fetch`, and the agent calls it over the OpenAPI spec.\\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. The\\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\\n`@import \\\"tailwindcss\\\";` in `index.css`) and nothing else — no\\ncomponent library. 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.** Blue is reserved for links and\\n focus rings; never a second accent.\\n- **Status colors are muted pairs** — never pure-saturated fills.\\n- **Style with Tailwind utilities.** Don't install another component\\n library or write a bespoke CSS system unless the user asks.\\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 \\\"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\\n`clawnify init` writes the minimal form:\\n`{ app: { framework: \\\"react+hono\\\", database: true, storage } }`. Add\\nthe rest as needed.\\n\\nIf the app talks to third-party services the user has connected\\n(ads platforms, CRMs, messaging), declare them:\\n\\n```json\\n{ \\\"app\\\": { \\\"credentials\\\": [\\\"metaads\\\", \\\"googleads\\\"] } }\\n```\\n\\nGet the ids and names from `clawnify connections list` — see the\\nnaming rule below.\\n\\n`env` supports `required` (deploy warns if missing), `optional`\\n(injected when available), and `oneOf` (at least one per group).\\n\\nRules:\\n- **There is no `api.tools[]`.** The manifest's `api` object only\\n accepts `public_routes` and `automation_bypass`. Your API surface\\n is discovered from the generated OpenAPI spec, not a hand-authored\\n tools list (see the next section).\\n- **Public routes are the exception**, not the default. Every route\\n is behind the Clawnify perimeter (auth-required) unless you\\n explicitly add a matching path to `api.public_routes`. Use only for\\n webhooks, RSS, 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.ts` defines the\\n tables; run `pnpm db:generate` after changing it.\\n\\n## How the agent reaches your API (no `api.tools[]`)\\n\\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\\nThat mechanism is gone. Today the flow is:\\n\\n1. Your `createRoute` definitions auto-generate a live OpenAPI 3.0 spec\\n plus a lean `/llms.txt` index, both served for you — never hand-write\\n or route them yourself. **These are the agent's discovery channel:**\\n it calls `call_app_api` with `GET /llms.txt` (index of every\\n endpoint) or `GET /api/openapi.json` (full request/response schemas).\\n Because both are generated from the live route table, they cannot\\n drift from the code.\\n2. The agent then drives your endpoints with `call_app_api` (a `method`\\n + `path` on the live app). No per-app MCP registration and no\\n manifest tools array. Use source reading to *modify* code, not to\\n discover endpoints.\\n\\nSo you make an endpoint \\\"agent-callable\\\" by defining it with\\n`createRoute()` + `app.openapi()` and giving it a clear\\n`summary`/`description` with Zod-typed request/response. The clearer\\nthose are, the more reliably the agent uses it.\\n\\n### `agent.md` — lead with the procedure, not the endpoint list\\n\\n`agent.md` is extracted into `agent_instructions` on every build. Since\\ndiscovery is already covered by the generated surfaces above, **`agent.md`\\nis not an API reference** — re-listing every payload there just creates a\\nsecond source of truth that goes stale the first time a route changes.\\nIt is the one place for what generation can't produce: **judgment**.\\n\\nWrite it in this order:\\n\\n1. **Division of labour, first and short.** What the agent should do\\n itself vs. what it must delegate to the app — and say the wrong move\\n out loud (*\\\"never look up contact details yourself; post the records\\n and let the app resolve them\\\"*). This one block prevents more misuse\\n than the rest of the file combined.\\n2. **The procedure** — numbered steps for the app's main job, written so\\n the agent can follow them on a request it has never seen.\\n3. **Pages**, flagging the screenshot-friendly ones.\\n4. **API anchors, not API docs** — method, path, and *when to reach for\\n it*, plus the one or two request shapes the agent writes most often.\\n For anything else, let it read `/llms.txt`.\\n5. **How to read failures**, and any **cost discipline** — which calls\\n spend the user's money and which are free.\\n\\n**Don't ship a per-app skill.** A skill's frontmatter stays resident in\\nagent context, so one skill per app grows the agent's context floor as\\nthe app count grows; `agent_instructions` and `/llms.txt` are pulled on\\ndemand instead. Skills are for **cross-app** procedures — if one earns\\nreuse across more than one app, promote that single procedure\\n(parameterized) to the shared skills library rather than copying it into\\nevery app.\\n\\n## Connections & secrets — `@clawnify/connections`\\n\\n**The naming rule — never invent an identifier.** Before declaring\\n`credentials` or env names, run `clawnify connections list`: it shows\\nthe org's canonical integration ids (`googleads`, never `google_ads`),\\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\\n`OPENROUTER_KEY`), and custom env vars already defined — each with\\nconnected/set state. Reuse those exact identifiers; a misspelled one\\ndoesn't fail the build, it silently resolves to nothing at runtime. If\\nyou need a custom secret that isn't listed, pick a clear name and tell\\nthe user to set it in the dashboard.\\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- **Need exact paths/arguments for a raw-REST provider?** Some carry\\n a `spec_url` (the provider's published OpenAPI spec) —\\n `clawnify connections list --json` shows it. Download and query it —\\n `curl -s <spec_url> -o spec.json && jq '.paths | keys' spec.json` —\\n never read a whole spec into context (they run to 10+ MB).\\n- **Never fall back to raw `fetch`** against a provider API, and\\n never invent endpoints or guess tokens.\\n\\n**The one exception — a service we don't support at all.** If a\\nprovider isn't in the connections registry (nothing to `connect()`\\nto, and `clawnify connections list` doesn't show it), the sanctioned\\npath *is* a raw call with a user-supplied key: declare the key(s) it\\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\\nthe user to set them in the dashboard, read them with\\n`secret(\\\"THAT_KEY\\\", env)`, and `fetch` the provider's documented\\nendpoints directly. This is the escape hatch for the long tail of\\nintegrations we don't model yet — it does **not** apply to a service\\nwe *do* support (use `connect()` / `run()` for those, always). Keep\\nthe endpoint and token server-side, never in the client bundle.\\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## Scheduling & deferred work — the managed queue\\n\\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\\n`ASSETS` + `UPLOADS`). To run work later — a scheduled publish, a reminder, a\\nretry, a \\\"do this in 10 minutes\\\" — use the **Clawnify managed queue service**\\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\\nendpoint on *your own app* back at the scheduled time.\\n\\nUse the published `@clawnify/queue` package — `enqueueJob`, `cancelJob`,\\n`verifyDelivery` — same shape as `@clawnify/db` / `@clawnify/connections`.\\nAuth is the build-injected `env.CLAWNIFY_TOKEN`; with no token (local dev)\\nit degrades to a no-op.\\n\\n**Enqueue** a deferred call to your own endpoint:\\n\\n```ts\\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\\nconst res = await fetch(\\\"https://services.clawnify.com/queue/enqueue\\\", {\\n method: \\\"POST\\\",\\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, \\\"Content-Type\\\": \\\"application/json\\\" },\\n body: JSON.stringify({\\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\\n payload: { post_id: id }, // echoed back to you on fire\\n run_at: new Date(whenMs).toISOString(),\\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\\n }),\\n});\\nconst { job_id } = await res.json(); // store it to cancel/reschedule\\n```\\n\\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\\nreschedule = cancel + a fresh enqueue.\\n\\n**The callback endpoint is a public, signature-verified route.** The queue calls\\n`target_url` from outside the perimeter, so the endpoint must be declared in\\n`clawnify.json` `public_routes` **and** verify the delivery signature itself —\\nthe signature *is* its auth (never trust an unsigned call):\\n\\n```jsonc\\n// clawnify.json\\n\\\"api\\\": { \\\"public_routes\\\": [ { \\\"path\\\": \\\"/api/internal/publish\\\", \\\"methods\\\": [\\\"POST\\\"] } ] }\\n```\\n\\nDeliveries are signed with the platform's **ECDSA P-256 (ES256)** key,\\nStripe-style over `${timestamp}.${rawBody}`, verified against\\n`https://services.clawnify.com/.well-known/jwks.json` (public key — nothing\\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\\ntolerance (~5 min) before doing anything:\\n\\n```ts\\napp.post(\\\"/api/internal/publish\\\", async (c) => {\\n const raw = await c.req.text();\\n const ok = await verifyDelivery(raw, {\\n signature: c.req.header(\\\"x-clawnify-signature\\\"),\\n timestamp: c.req.header(\\\"x-clawnify-timestamp\\\"),\\n keyId: c.req.header(\\\"x-clawnify-key-id\\\"),\\n });\\n if (!ok) return c.json({ error: \\\"bad signature\\\" }, 401);\\n const { post_id } = JSON.parse(raw);\\n // …do the deferred work (short: it's one normal Worker invocation)…\\n return c.json({ ok: true });\\n});\\n```\\n\\nEach fire is a normal Worker request — size the work to one invocation (publish a\\npost, send a digest). For long compute *now* (not deferred), hold the request\\nopen and return when done; don't fire-and-forget past the response.\\n\\n## Migrations\\n\\nThe workflow is:\\n\\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\\n2. Run `pnpm db:generate` — emits the migration SQL under\\n `.clawnify/drizzle/`.\\n3. Run `npx clawnify@latest dev` locally, then `npx clawnify@latest deploy`.\\n\\nOn deploy your schema changes are applied to the app's database — new\\ntables and columns are added automatically.\\n\\nDestructive changes (drop column, rename) are not applied automatically;\\ndo them deliberately, and only when the user explicitly asks. Renames\\nare risky on production data — prefer \\\"add new column, backfill, switch\\nqueries, drop old column\\\" over a single-step rename.\\n\\n## What the agent must NOT do\\n\\n- Author a `/openapi.json` or `/llms.txt` handler by hand. `createApp()`\\n mounts both, generated from your `createRoute` definitions.\\n- Hand-write a `schema.sql`, edit anything under `.clawnify/`, or add a\\n root `drizzle.config.ts`. Schema changes happen in `schema.ts`; the\\n CLI generates and applies the SQL.\\n- Invent an `api.tools[]` array in the manifest. It isn't a valid\\n field — the OpenAPI spec is the tool surface.\\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\\n via Drizzle. The raw SQL API has `json()` as a helper.\\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\\n leak is the worst-class bug we can ship.\\n- Return a whole table from a list endpoint, or a bare array. Every list\\n pages: `PageQuery`, `pageParams` and `pagedResponse` from `@clawnify/app`.\\n- Read auth from `Authorization` / cookies / `Bearer` tokens, or\\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\\n `caller(c)` from `@clawnify/app`.\\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.1` pulls it in transitively; only add it if you\\n 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`, `desc`, `sql`, `sqliteTable`, `text`,\\n `integer`, `index`, etc. are all re-exported there). Drop to\\n `drizzle-orm` directly only for things not re-exported.\\n- Give every route a clear `summary`/`description` and Zod-typed\\n request/response so the agent can discover and call it via the\\n OpenAPI spec.\\n- Page every list endpoint with the helpers `@clawnify/app` exports:\\n `request: { query: PageQuery.extend({ /* filters */ }) }`,\\n `const { page, limit, offset, search } = pageParams(c.req.valid(\\\"query\\\"))`\\n (25 per page by default, capped at 100, bad input falls back), and\\n `responses: { 200: pagedResponse(\\\"items\\\", ItemSchema) }` for\\n `{ items, total, page, limit }`. Count with `db.$count(table, where)`.\\n- Type a helper that takes the database client as `DB<typeof schema>`\\n (from `@clawnify/db`), and a separate routes file's env as `AppEnv`\\n (from `@clawnify/app`). Never name the backend (`D1Database`,\\n `DrizzleD1Database`) or cast `getDB`'s result: the same app code is\\n served by more than one database backend.\\n- Test locally with `npx clawnify@latest dev` before deploying; deploys go live at\\n `https://<slug>.apps.clawnify.com` (the dashboard's preview pane shows\\n the draft tier).\\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: \"build-a-clawnify-website\",\n description: \"Build and ship a Clawnify website — Astro on Cloudflare Workers, the built-in form system (never hand-roll a form), images and assets, and the draft-then-publish deploy flow. Use when creating or editing a Clawnify website, or when a site needs a contact/waitlist/signup form.\",\n content: \"# Build a Clawnify website\\n\\nA Clawnify website is an **Astro** project deployed to Cloudflare Workers. One\\nsite per organization. You write pages; the platform owns hosting, forms and\\nthe publish flow.\\n\\n```bash\\nnpx clawnify@latest init --type website --name \\\"My Site\\\" website\\ncd website && pnpm install && pnpm dev # http://localhost:4321\\n```\\n\\nAlways invoke the CLI as `npx clawnify@latest <command>` — never a\\nglobal or pinned install; stale CLIs miss deploy guards and fixes.\\n\\n```\\nwebsite/\\n src/pages/ # one .astro file per route (index.astro → /)\\n src/layouts/ # shared shell: nav, footer, <head>\\n src/blocks/ # platform blocks you've adopted (see Forms below)\\n public/ # images, favicons — served as-is from /\\n```\\n\\n## Forms: use the built-in system. Do not build your own.\\n\\n**This is the single most common mistake.** A site needs a contact or waitlist\\nform, and the obvious move is to write a `<form>` and POST it somewhere — your\\nown endpoint, a third-party form service, or the platform's submit URL with the\\nwebsite id pasted in. All three are wrong, and the last one looks right enough\\nto survive review.\\n\\nClawnify has a form system. It captures submissions, stores them, can email you,\\nand can hand each one to an agent or a flow. You get all of it by using the\\n**Forms block** rather than writing a form yourself.\\n\\n### How it works\\n\\n- The submit target is **computed at render time** from `WEBSITE_ID` — a\\n variable the platform bakes into your site's Worker — plus the form's id:\\n\\n ```astro\\n const env = (Astro.locals as { runtime?: { env?: Record<string, string> } })?.runtime?.env;\\n const websiteId = env?.WEBSITE_ID ?? \\\"\\\";\\n const action = websiteId ? `https://provision.clawnify.com/forms/submit/${websiteId}/${formId}` : \\\"\\\";\\n ```\\n\\n **Never hardcode the website id.** It is baked per Worker so a site can only\\n ever submit to itself — hardcoding throws that away, and the literal goes\\n stale the moment the site is recreated. An empty `action` in local `astro dev`\\n is expected: there are no Worker vars locally, so the form simply no-ops.\\n\\n- The submit script POSTs JSON with `Content-Type: text/plain;charset=UTF-8`.\\n That is not a typo — `text/plain` is CORS-safelisted, so the request needs no\\n preflight, which matters because the platform can't know your site's origin in\\n advance. The route parses the text body as JSON.\\n\\n- **Keep the Turnstile widget.** The ingest rejects a submission with no token,\\n so a form without the widget fails every time with \\\"Verification required\\\".\\n The sitekey shipped in the block is public and pairs with the platform's\\n secret; the widget will not validate on `localhost`, only on a real hostname.\\n\\n### Getting the block\\n\\nSites are seeded with the platform's block library at creation. If yours has\\n`src/blocks/Forms/Contact.astro`, import it and go. If it doesn't — an older\\nsite, or one scaffolded bare by the CLI — copy it in from the website template\\nand adapt it.\\n\\n**The design is yours; the plumbing is not.** Restyle the markup, labels and\\nclasses freely. Preserve, exactly:\\n\\n- the computed `action` (never a prop, never a literal),\\n- the Turnstile widget,\\n- the `data-clawnify-managed-form` attribute,\\n- `export const schema`,\\n- destructuring only known props — never splat leftover props onto `<form>`,\\n or an injected `action` becomes a way to point your form at someone else.\\n\\nThere is no submit script to copy. The runtime lives in the framework catch-all\\n(`src/pages/[...path].astro`) and binds every `data-clawnify-managed-form` on\\nthe page. If the block you inherited still has its own inline `<script>` and a\\n`data-clawnify-form` attribute, it is the older shape: it still works, and you\\ncan migrate it by deleting the script and renaming the attribute. Do not carry\\nboth attributes on one form, and do not add `data-clawnify-form` to a managed\\nform: older blocks bind that selector unconditionally, so the form would submit\\ntwice.\\n\\n### After a successful submit\\n\\nTwo options, and the default is unchanged.\\n\\n- **Inline message** (default). The `successText` prop, rendered into the\\n status line.\\n- **Redirect.** Set the `successUrl` prop, or `data-success-url` on any form\\n you hand-built. A site-relative path (`/thanks`) or an absolute `https://`\\n URL (a booking page is fine). Anything else is ignored and the message is\\n shown instead, which is what keeps `javascript:` out of the navigation.\\n\\nA redirect to a thank-you page is also the only way to count a form conversion\\nin the analytics tool, which has no custom events: the dashboard Submissions\\npanel counts submissions, but a pageview is what gives you a rate.\\n\\nNeed a side effect on success, like setting a cookie? Listen for the\\n`clawnify:form-success` event on the form. It is cancelable, so\\n`preventDefault()` suppresses the redirect if you would rather navigate\\nyourself.\\n\\n### Fields\\n\\nThe stock block collects **name, email and message**. Two ways to go beyond\\nthat, and the right one depends on whether your form is registered:\\n\\n- **Registered forms** (a tree node named `Forms/Contact`) are schema-locked:\\n the ingest 422s any field it doesn't expect. Give extra inputs **no `name`\\n attribute** and have the submit script fold them into `message`.\\n- **Unregistered forms** — hand-built pages like this one — are not locked, so\\n extra fields post as themselves and are stored verbatim in the payload. Better\\n data, but if the site later moves onto the tree renderer, registration will\\n start rejecting them. Leave a comment saying so.\\n\\n### PDF attachments\\n\\nThe Contact block can collect one PDF per submission (job applications, RFQs).\\nOff by default — enable it with the block's `attachment` prop (and optionally\\n`attachmentLabel`), then **publish**: the file field is registered at publish\\ntime, and the ingest rejects files on forms that haven't registered one. Rules\\nthe platform enforces server-side (don't fight them client-side): PDF only,\\nverified by content not by extension, max 10 MB. The submission's payload\\ncarries the filename and a download link that only the site's own organization\\ncan open — the file is never on a public URL. When a file is attached the\\nsubmit script posts `multipart/form-data` instead of JSON; both are\\npreflight-free, and the block already handles the switch.\\n\\n### Where submissions go\\n\\nEvery submission is stored and visible in the dashboard. From there it can\\nnotify an email address, or fan out to an agent or a flow — which is how a\\nsignup becomes a CRM record or a WhatsApp message without you writing a backend.\\nSet the notification address in the dashboard, not in the site.\\n\\n## Images and assets\\n\\nPut them in `public/` and reference them with an absolute path (`/img/hero.jpg`).\\nThey're served as static files. Pull in real assets at real resolution rather\\nthan linking someone else's CDN from your markup.\\n\\n## Deploying: draft first, then publish\\n\\n```bash\\nnpx clawnify@latest deploy # → the DRAFT site, visible only to your org\\n```\\n\\nDeploying **never** changes the live site. Going live is a separate, explicit\\nstep: review the draft, then **Publish to live** in the dashboard. Tell the user\\nthis — a deploy that \\\"worked\\\" but didn't appear on the live site is almost\\nalways someone expecting deploy to publish.\\n\\n## Pinning the org\\n\\nEvery command resolves which organization it targets, folder-first. In a linked\\nfolder you get it for free; otherwise pass `--org`. If you work across several\\norganizations, pass `--org` explicitly on anything that writes — the global\\nactive org is shared machine-wide and another session can change it under you.\\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, route patterns), use the\\n`build-a-clawnify-app` skill — this one covers the tooling around it.\\n\\n## TL;DR\\n\\n```bash\\nnpx clawnify@latest login # browser sign-in, paste-code fallback\\nnpx clawnify@latest init my-app # scaffold an app or website\\ncd my-app && npx clawnify@latest dev\\nnpx clawnify@latest deploy # → https://<slug>.apps.clawnify.com\\n```\\n\\n- **Always invoke as `npx clawnify@latest <command>`.** Never install\\n globally or pin a version — the CLI ships guards and self-heals\\n continuously, and a stale copy misses them. Reference blocks below\\n show bare `clawnify <cmd>` for brevity; run them with the full\\n `npx clawnify@latest` form. (Scaffolded apps' package scripts —\\n `pnpm dev`, `pnpm deploy` — already delegate correctly.)\\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**Headless / CI / agents — skip `login` entirely.** Set `CLAWNIFY_TOKEN` (a\\nlogin token: the `access_token` in `~/.clawnify/auth.json` on a machine that\\nran `clawnify login`) and it wins over any stored session, reading/writing no\\nfiles; `CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. This is how a\\ncoding agent runs the CLI without a browser.\\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\\nIf the app has unpublished changes from the chat, the deploy won't publish\\nthem: it lands as a draft on top of them (publish both in the dashboard), or\\nit is refused if it would overwrite them. `--discard-draft` replaces them;\\nonly use it when the user says those changes can go.\\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 db generate # refresh .clawnify/drizzle/*.sql from schema.ts\\nclawnify pull schema --from <app-id-or-slug> # snapshot the DEPLOYED schema to schema.sql (generated; read-only reference)\\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## Manage agents\\n\\nDrive an org's AI agents from the terminal — observe them and fix them. See the\\n`fix-a-clawnify-agent` skill for the workflow; this is the command list. All\\norg-scoped and **repo-independent** (reads live agent state, never a GitHub\\nrepo).\\n\\n**The model — two levels, and only two.** An org has one or more **agents** (the\\nAI employees, e.g. \\\"Ash\\\"). Each agent can have **sub-agents**: narrower helpers\\nit delegates to. `clawnify agents list` prints both, sub-agents indented under\\nthe agent that owns them:\\n\\n```\\nAsh (ready, eu)\\n id: 7c2f…\\n sub-agents:\\n └─ research (Research) 4 sessions\\n```\\n\\nAn org normally has exactly one agent, so nothing needs to be selected. When it\\nhas several, pass `--agent-id <id>` (the `id:` line above).\\n\\n```bash\\nclawnify agents list # the org's agents, each with its sub-agents\\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\\nclawnify sessions history <key> --json # one session's transcript — where it veered\\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only — flows belong to the main agent)\\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\\nclawnify agents create <slug> --yes # new SUB-AGENT (RESTARTS the gateway)\\nclawnify env set <KEY> <VALUE> # org custom env — NON-SECRET only (restarts gateway)\\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\\nclawnify flows list # the main agent's flows + latest published version\\nclawnify flows read <name> # print a flow's draft\\nclawnify flows create <name> --file f.json # new draft (validated on save)\\nclawnify flows edit <name> # edit the draft ($EDITOR, or --file to replace)\\nclawnify flows publish <name> # cut the next numbered live version\\n```\\n\\n**Flows:** runs and triggers use the latest **published** version, so editing a\\ndraft doesn't change what's live — until a flow's first publish, though, the\\ndraft *is* what runs. `create`/`edit`/`publish` validate automatically and\\nreport per-node errors; fix and re-save. Prefer these verbs over pushing raw\\n`flows/*.json` edits (which skip validation and versioning).\\n\\n**Boundary:** everything above is autonomous *except* the human-auth actions —\\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\\nexplain the dashboard steps; never fake them. `agents create` / `env set`\\nrestart the gateway, so confirm before running them on a busy agent.\\n\\n**`agents create` makes a NEW sub-agent — it is never the way to \\\"find\\\" an\\nexisting one.** If you were looking for an agent and `agents list` didn't show\\nit, the answer is that the org doesn't have it, or you're in the wrong org\\n(`clawnify org list`). Creating one restarts the gateway and leaves a duplicate\\nbehind.\\n\\n## Connections & env names\\n\\n```bash\\nclawnify connections list # the org's naming catalog (● connected / ○ not)\\nclawnify connections connect <id> # how to connect one — dashboard OAuth; the CLI/agent can't do it for you\\n```\\n\\nLists the active org's integrations (canonical ids + connected state),\\nprovider API keys (fixed names + set state), and custom env vars. Read\\nit before declaring `credentials` or env names in `clawnify.json` and\\nreuse the exact identifiers it shows — a misspelled id or key name\\ndoesn't fail the build, it silently resolves to nothing at runtime.\\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## The raw escape hatch\\n\\n```bash\\nclawnify api /agents # any GET\\nclawnify api /apps -X POST -d '{…}' # any method + JSON body\\n```\\n\\n`clawnify api <path>` makes an authenticated request to any Clawnify API path —\\nsame auth and org scoping as every other command (it can only do what you can).\\nUse it for anything the porcelain doesn't wrap; the curated commands stay small\\nbecause this is always there.\\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 name: \"fix-a-clawnify-agent\",\n description: \"Diagnose and fix a Clawnify AI agent that veers off its instructions, ignores specific rules, forgets things, repeats the same mistake, or burns a lot of API credits. Use when someone says their agent (e.g. \\\"Ash\\\") won't follow instructions, keeps going off-path, or is expensive — read the agent's own sessions, find the real cause, and fix the instructions / sessions / flow instead of patching blind.\",\n content: \"# Fix a misbehaving Clawnify agent\\n\\nYou are the planner and thinker. The Clawnify agent — the customer's\\nWhatsApp / Telegram / Slack / email \\\"AI employee\\\" — is the executor. When it\\nmisbehaves your job is to **read what it actually did, find the real cause, and\\nchange the durable inputs.** Not to patch instructions blind, and not to burn\\nthe agent's own (expensive) model tokens on trial-and-error.\\n\\n**Know what you're looking at.** An org has one or more **agents** (the\\nemployees). Each may have **sub-agents** — narrower helpers it delegates to.\\n`clawnify agents list` shows both, sub-agents indented under their agent. That\\nis the whole hierarchy; there is no other tier to go looking for.\\n\\nThe person you're helping is often **not** an AI specialist. So: diagnose\\nfirst, then **explain the cause in plain language and correct the\\nmisconception** before you change anything.\\n\\n## The one rule: don't debug blind\\n\\n\\\"Veers off / ignores instructions\\\" has **three different causes with three\\ndifferent fixes.** You can only tell which one by reading the agent's actual\\nsession. Patching instructions without looking is exactly why it \\\"isn't\\nheading in the right direction\\\" — and every blind test run costs model tokens.\\n\\n| Cause | What you'll see in the session | Fix |\\n|---|---|---|\\n| **1. Session bloat** | Was fine early, degrades over a long-running chat; forgets/repeats; high `contextTokens`; compaction/truncation in the transcript; the rule is simply *absent* from recent context | Scope a **fresh session per task**; reset/retire the bloated one |\\n| **2. Instruction patchwork** | The rule *was* in context but a **contradicting or older** rule won, or it's buried in a wall of text | **Restructure** `AGENTS.md` (don't add another patch) |\\n| **3. Wrong structure** | A repeatable multi-step task the agent improvises differently each time | Move it to a **flow** (deterministic rails) |\\n\\nBloat and patchwork also explain most **surprise API costs**: a bloated\\nsession re-sends a huge context on *every* turn, and the patch-and-rerun loop\\nitself burns tokens. Measure it — don't guess (Step 1).\\n\\n## Step 1 — Observe (read what actually happened)\\n\\n```bash\\nclawnify agents list # the org's agents + their sub-agents — START HERE\\nclawnify sessions # every agent's sessions, newest first\\nclawnify sessions --agent ash --json # ash only, with token counters (contextTokens = bloat signal)\\nclawnify sessions history <key> --json # the transcript of one run — where it actually veered\\nclawnify agents skills ash # what ash can ACTUALLY run (workspace + shared skills)\\n```\\n\\nLook for, in order:\\n- **Which failure mode** (table above): was the instruction *present and\\n ignored* (→ patchwork/structure) or *compacted away / absent* (→ bloat)?\\n- **`contextTokens`** on the session — large and growing = bloat.\\n- **A missing skill** — if the instruction says \\\"use skill X\\\" but `agents\\n skills` doesn't list it, the agent literally can't. The fix is to grant it\\n (`clawnify agents grant-skill X --to ash`, or `--all` for every agent) if it's\\n already authored in main, else author it first (`agents pull main` → add\\n `skills/X/SKILL.md` → `agents push`) — not to reword the instruction. (Note:\\n what's in the agent's *workspace* is only part of it — `agents skills` shows\\n the effective set incl. shared managed-root skills.)\\n- **Where the tokens go** — one giant session, or repeated retries after a\\n veer? That's your cost answer, from data, not a hypothesis.\\n\\n> If `clawnify sessions` isn't available yet in this org, fall back: ask the\\n> person to describe (or paste) one failing run, and read the current\\n> `AGENTS.md` from the org's synced repo. You still diagnose before you fix.\\n\\n## Step 2 — Explain, then fix\\n\\nTell the person, plainly, which of the three it is and why. Then:\\n\\n**Bloat →** don't reuse one ever-growing chat for the same task. Start a fresh\\nsession per task/topic (or `/reset` the runaway one). This fixes the veer\\n*and* the cost.\\n\\n**Patchwork →** rewrite `AGENTS.md`, don't append to it. Structure it: **role\\n→ a short list of hard rules up front → the steps → one example of right vs\\nwrong.** Delete contradictions. A tight, prioritized instruction set is\\nfollowed far better than a long patched one.\\n\\n**Structure →** author a **flow** for the repeatable task: deterministic steps,\\neach with a narrow instruction, and the heavy/deterministic parts (fetch data,\\nfill a template, render the deck) run *without* the model — less veer, less cost.\\n\\nWhere instructions live and how edits land:\\n- Edit **`AGENTS.md`** (and `skills/`). Push via the org's **GitHub\\n sync repo** (auto-deploys to the agent) or `npx clawnify@latest deploy`. See the\\n `use-the-clawnify-cli` skill for the commands.\\n- Edit **flows** with `clawnify flows edit <name>` then `clawnify flows\\n publish <name>` — validated on save; once a flow has a published version,\\n runs and triggers keep using it until you publish again (before the first\\n publish, the draft is what runs). Raw `flows/*.json` edits via the repo also\\n land, but skip validation and versioning.\\n- **No gateway restart needed** — the agent picks up new `AGENTS.md` / skills /\\n flows on its **next session**.\\n- **Never edit any `CLAWNIFY-*.md`** file (`CLAWNIFY-SOUL/AGENTS/TOOLS.md`) —\\n those are platform-owned and Clawnify overwrites them on every sync. Your\\n edits there vanish.\\n\\n## How Clawnify agents actually work (what people get wrong)\\n\\nPreempt these — they cause \\\"I set it up but the agent ignores it\\\":\\n\\n- **Adding a document to Knowledge does NOT mean the agent reads it.**\\n (1) A doc must be **published by a human** — an agent \\\"proposing\\\" it only\\n creates a draft. (2) Once published, the agent only *automatically* sees its\\n **title + one-line description** (a capped, ~30-item index); the **actual\\n content is fetched only when the agent chooses to search** it\\n (`company_knowledge_search`). So if the agent ignores a doc, check: is it\\n published? not hidden? still in the index? does its `AGENTS.md` tell it to\\n search? — **re-uploading won't help.** Depth: the `organize-company-knowledge` skill.\\n- **Memory** is written by the agent via a tool (`memory_write`) and surfaced\\n as an index + per-turn recall — it is **not** a file/folder you drop notes\\n into.\\n- **The dashboard \\\"recurring skill\\\" cards are manual-click only** — the\\n cron/every/at schedule shown is **not wired to a scheduler.** For real\\n scheduled or event-driven work use a **cron job or a flow/webhook**, not a\\n recurring-skill card.\\n- **Native channels** (WhatsApp/Telegram/Slack) receive messages \\\"for free\\\"\\n via the allowlist — there is **no trigger/webhook to set up** for incoming\\n messages. (Only Clawnify *integrations* have dashboard triggers.)\\n\\n## Answering \\\"would a different agent / a flow help?\\\"\\n\\n- **Same agent for the same task → confusion?** The agent identity isn't the\\n problem; a reused, ever-growing **session** is (bloat, above). A second agent\\n doesn't fix the mechanism and doubles what you manage. Fresh sessions do.\\n- **Would a flow be better?** Yes *if* the task is repeatable and structured —\\n it constrains the agent and moves deterministic work off-model (less veer,\\n less cost). No if the underlying step instructions are vague — a flow\\n structures, it doesn't clarify.\\n\\n## Guardrails\\n\\n- **Diagnose before you change anything.** One transcript read beats five blind\\n patches.\\n- **Never** edit `CLAWNIFY-*.md` (overwritten) — edit `AGENTS.md`.\\n- **Confirm with the human before anything irreversible or outward-facing:**\\n sending messages on the agent's live channels, deleting an agent or app,\\n billing/plan changes, rotating credentials. Self-service is not unattended\\n autonomy.\\n- **Connecting an integration is a hard stop, not a confirm.** If a fix needs a\\n Clawnify integration that `clawnify connections list` shows as not connected\\n (○), you *cannot* connect it — that needs the user's OAuth sign-in in a\\n browser. Run `clawnify connections connect <id>` and relay the steps to the\\n user; never attempt it yourself or ask for their password.\\n- **Never put a secret through `clawnify env set`** — it exposes the value in\\n the command and your context. Secrets and API keys go in the dashboard\\n (Settings → Environment Variables / API Keys); guide the user there. Use\\n `env set` only for non-secret config. And remember `agents create` / `env set`\\n **restart the gateway** — confirm with the user before you run them on a live,\\n busy agent.\\n- **Never run `agents create` to \\\"find\\\" an agent.** It creates a *new sub-agent*\\n and restarts the gateway. If the agent you expected isn't in `clawnify agents\\n list`, you are in the wrong org (`clawnify org list`) or it genuinely doesn't\\n exist — ask. Creating one leaves a duplicate the customer then has to live\\n with, and interrupts the real agent while it does.\\n- Prefer the **smallest durable fix** (a session habit, a tightened `AGENTS.md`,\\n one flow) over more instructions.\\n\",\n }\n];\n\nexport type RulesKind = \"app\" | \"website\" | \"agent\";\n\nexport const RULES_BY_KIND: Record<RulesKind, string> = {\n \"app\": \"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 org — read it with `orgId(c)` from `@clawnify/app`. This is how\\n multi-tenancy works — there are no exceptions.\\n\\n## Identity comes from request headers, never the client\\n\\nThe platform injects identity the client cannot forge. Read it with\\n`user(c)` / `orgId(c)` / `caller(c)` from `@clawnify/app` — never parse\\n`X-Clawnify-*` headers by hand, and never trust a client-supplied user or\\norg 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 \"website\": \"You are working inside a **Clawnify website** — an Astro site that deploys to\\nCloudflare through the Clawnify platform. Follow these rules.\\n\\n## Stack (fixed — do not swap)\\n\\n- **Framework:** Astro 5, `output: \\\"server\\\"` with the `@astrojs/cloudflare`\\n adapter. Pages render on a Worker, so `Astro.request` and runtime env are\\n available; there is no static export step to fight.\\n- **Styling:** Tailwind v4 via `@tailwindcss/vite`, entry `src/styles/global.css`.\\n\\nOne website = one `clawnify.json` manifest at the repo root, with\\n`website: { framework: \\\"astro\\\" }`. Don't introduce another framework, another\\nCSS system, or another hosting target.\\n\\n## This is a normal Astro project — author it as one\\n\\n- Pages are files: `src/pages/index.astro` is `/`, `src/pages/about.astro` is\\n `/about`. Dynamic routes use `[slug].astro` the usual way.\\n- Shared chrome belongs in `src/layouts/`; reusable markup in\\n `src/components/`.\\n- A route that fetches per request needs `export const prerender = false`.\\n Without it Astro prerenders at build time and your data is frozen at deploy.\\n\\nThere is no page-tree JSON, no block registry, and no theme token file in this\\nproject. Those belong to Clawnify's dashboard-managed website product, which is\\na different thing with a different authoring model — don't go looking for them\\nhere, and don't invent them.\\n\\n## Fetching data on the server\\n\\nFetch in the frontmatter (it runs on the Worker), not in a client script, unless\\nthe data is genuinely user-interactive. Anything you can resolve server-side\\nrenders in the first byte and costs the visitor nothing.\\n\\nGive any response you cache-control a real TTL: `public, max-age=<n>`. Clawnify\\nedge-caches declared-public GETs, but only when the response says how long it is\\ngood for.\\n\\n## Commands\\n\\n- `clawnify dev` — local dev server, same adapter as production.\\n- `clawnify deploy` — publishes the site and prints its live URL.\\n- Don't invoke raw `astro` or `wrangler` — the CLI wraps them, and it is what\\n binds the deploy to your org and site.\\n\\n## Going deeper\\n\\nAstro's own docs are the reference for routing, layouts, and content\\ncollections — this is a standard Astro project and nothing about it is\\nClawnify-specific except the manifest and the deploy step. For CLI mechanics\\n(workspaces, orgs, linking, custom domains) read the **use-the-clawnify-cli**\\nskill installed alongside these rules.\\n\",\n \"agent\": \"You are working inside a **Clawnify agent** project — the configuration for an\\nAI employee that runs on the Clawnify platform. Follow these rules.\\n\\n## What this project is\\n\\nOne agent = one `clawnify.json` manifest at the repo root, with\\n`agent: { harness: \\\"openclaw\\\" }`. The manifest picks the runtime; everything\\nelse here is prose and JSON that shapes behaviour. There is no application\\nstack to choose — no framework, no database, no build.\\n\\n## The pieces\\n\\n- **`AGENT.md`** — the agent's primary instructions, its role, tone and\\n boundaries, written as prose. This is the file that actually changes how the\\n agent behaves; most requests to \\\"change what the agent does\\\" are edits here.\\n- **`skills/<name>/`** — reusable procedures. A `SKILL.md` the agent reads when\\n triggered, plus a `skill.json` describing when it runs. Reach for a skill when\\n a task recurs with the same shape; don't encode one-offs.\\n- **`flows/<name>.json`** — ClawFlow definitions for automations that run on a\\n schedule or a trigger rather than in conversation.\\n\\n## Write instructions, not code\\n\\nThe most common mistake here is reaching for a script when the answer is a\\nclearer sentence in `AGENT.md` or a skill. Prefer changing the instructions.\\nAdd a flow only when something must run without a human in the loop.\\n\\n## Commands\\n\\n- `clawnify deploy` — pushes this configuration to the agent.\\n- The push is additive on the agent's machine: it never deletes files the agent\\n authored for itself.\\n\\n## Going deeper\\n\\nFor diagnosing an agent that is misbehaving — instructions not taking effect,\\na channel not responding, a skill not firing — read the **fix-a-clawnify-agent**\\nskill installed alongside these rules.\\n\"\n};\n\n/** No manifest to read from — a bare directory, or ai-files run before init.\n * App is the overwhelmingly common kind, and this is what shipped before. */\nexport const RULES_CONTENT = RULES_BY_KIND.app;\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_BY_KIND, type RulesKind } 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 -->\";\n// The `kind:` suffix is optional here on purpose: blocks written before kinds\n// existed have none, and this has to keep parsing their version so they report\n// as an upgrade rather than a fresh install.\nconst VERSION_RE = /<!--\\s*clawnify:rules\\s+v([\\d.]+)(?:\\s+kind:\\w+)?\\s*-->/;\n\n/** The kind marker is written into the block so a project that changes kind, or\n * one whose rules were installed before kinds existed, is detected as stale and\n * rewritten rather than left asserting the wrong stack forever. */\nconst KIND_RE = /<!--\\s*clawnify:rules\\s+v[\\d.]+\\s+kind:(\\w+)\\s*-->/;\n\nfunction block(kind: RulesKind): string {\n return `${START}\n<!-- clawnify:rules v${CLI_VERSION} kind:${kind} -->\n${RULES_BY_KIND[kind].trimEnd()}\n${END}\n`;\n}\n\nexport type RulesStatus =\n | { status: \"installed\"; file: string }\n | { status: \"updated\"; file: string; previousVersion: string; previousKind: string | null; kind: RulesKind }\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, kind: RulesKind): RulesStatus {\n const filePath = join(cwd, file);\n const section = block(kind);\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 const kindMatch = match[0].match(KIND_RE);\n const previousKind = kindMatch ? kindMatch[1] : null;\n // Version AND kind. Matching on version alone would leave a block that is\n // current but wrong — an app block sitting in a website project, skipped\n // on every rerun because the number agreed. A pre-kinds block has no\n // marker at all, so it reads as null and gets rewritten.\n if (previousVersion === CLI_VERSION && previousKind === kind) {\n return { status: \"skipped\", file: filePath, reason: `already at v${CLI_VERSION} (${kind})` };\n }\n writeFileSync(filePath, existing.replace(sectionRe, section));\n return previousVersion\n ? { status: \"updated\", file: filePath, previousVersion, previousKind, kind }\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 { manifestKind, readManifest } from \"../lib/config.js\";\nimport type { RulesKind } from \"../lib/skills/content.gen.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 */\n/**\n * Project kind for the rules block. Falls back to \"app\" when there is no\n * manifest to read — a bare directory, or `ai-files install` run before\n * `init` — which is both the common case and what shipped before kinds existed.\n * `manifestKind` throws on a malformed manifest; a bad manifest should not stop\n * someone wiring up their agent, so that degrades to the same fallback.\n */\nfunction resolveRulesKind(cwd: string): RulesKind {\n try {\n const manifest = readManifest(cwd);\n return manifest ? manifestKind(manifest) : \"app\";\n } catch {\n return \"app\";\n }\n}\n\nexport function installAiFiles(\n cwd: string,\n agents: DetectedAgent[],\n opts: { mcp: boolean },\n): InstallResult {\n // Which rules block to write. `deploy`, `dev` and `mcp` all resolve the\n // project kind from the manifest already; this command was the one that did\n // not, so every project got the app block — including websites and agents,\n // where it names a stack and files that do not exist. Rules are always in\n // context, so that was a standing instruction to build the wrong thing.\n const kind = resolveRulesKind(cwd);\n\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, kind);\n if (r.status === \"skipped\") {\n console.log(` · rules → ${r.file} (${r.reason})`);\n } else if (r.status === \"updated\") {\n // Say what actually changed. When only the kind moved, \"v0.13.0 → v0.13.0\"\n // reads as a no-op while the whole block was in fact swapped out.\n const change =\n r.previousKind === r.kind\n ? `v${r.previousVersion} → v${CLI_VERSION}`\n : `${r.previousKind ?? \"unkinded\"} → ${r.kind}`;\n console.log(` ↑ rules → ${r.file} (${change})`);\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\";\nimport { ensureDrizzleConfig } from \"../lib/drizzle.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 drizzleConfigPath = ensureDrizzleConfig(resolvedDir);\n if (drizzleConfigPath) {\n await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath, drizzleConfigPath);\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 drizzleConfigPath: string,\n): Promise<void> {\n try {\n await runQuiet(resolvedDir, \"npx\", [\"drizzle-kit\", \"generate\", `--config=${drizzleConfigPath}`]);\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 { spawn } from \"node:child_process\";\nimport { ensureDrizzleConfig } from \"../lib/drizzle.js\";\n\n/**\n * `clawnify db generate` — explicit DDL generation from src/server/schema.ts.\n *\n * `clawnify dev` and `clawnify deploy` run this transparently; the explicit\n * command exists for agents/users who want the migration SQL refreshed\n * without starting either (e.g. to inspect it, or after the deploy guard\n * pointed here). Unlike the deploy-time regeneration (best-effort, warns),\n * an explicit invocation fails loudly.\n */\nexport async function dbGenerateCommand(dir?: string): Promise<void> {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const configPath = ensureDrizzleConfig(resolvedDir);\n if (!configPath) {\n console.error(\n \"No src/server/schema.ts here — nothing to generate.\\n\" +\n \" Drizzle apps define tables in src/server/schema.ts; apps without a\\n\" +\n \" database don't need this command.\",\n );\n process.exit(1);\n }\n\n const code = await new Promise<number>((resolve) => {\n const proc = spawn(\"npx\", [\"drizzle-kit\", \"generate\", `--config=${configPath}`], {\n cwd: resolvedDir,\n stdio: \"inherit\",\n env: { ...process.env },\n });\n proc.on(\"exit\", (c) => resolve(c ?? 1));\n proc.on(\"error\", (err) => {\n console.error(`Could not run drizzle-kit: ${String(err).slice(0, 160)}`);\n resolve(1);\n });\n });\n if (code !== 0) process.exit(code);\n console.log(\" ✓ Migrations in .clawnify/drizzle/ (applied on the next dev/deploy)\");\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 org_slug: matched.org.slug,\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\";\n\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 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`);\n console.log(`${\"─\".repeat(nameWidth)} ${\"─\".repeat(slugWidth)} ───────`);\n for (const o of orgs) {\n console.log(\n `${o.name.padEnd(nameWidth)} ${o.slug.padEnd(slugWidth)} ${o.role}`\n );\n }\n}\n\n/**\n * Deprecated. Org is resolved per folder, never per machine.\n *\n * This used to write org_id into ~/.clawnify/auth.json — one mutable pointer\n * shared by every shell, worktree and agent on the box, so one session could\n * silently redirect another session's commands at a different tenant. It now\n * writes nothing.\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 console.error(\n `\\`clawnify org use\\` is deprecated and no longer sets anything.\\n` +\n `Org is resolved per folder, so a global default cannot redirect another\\n` +\n `session mid-task. Bind ${match.name} to this folder instead:\\n\\n` +\n ` clawnify link <app> --org ${match.slug}\\n` +\n ` writes .clawnify/project.json — persists for this folder\\n\\n` +\n ` \"workspace\": { \"org\": \"${match.slug}\" } in clawnify.json\\n` +\n ` for a workspace repo — persists for every folder inside it\\n\\n` +\n ` --org ${match.slug}\\n` +\n ` one command\\n\\n` +\n ` export CLAWNIFY_ORG_ID=${match.slug}\\n` +\n ` one shell\\n`,\n );\n process.exit(1);\n}\n","import { api } from \"../lib/api.js\";\n\n// The §3.5 naming catalog — the \"wrangler secret list\" of Clawnify. One read\n// returns the union of static canon and this org's live state so callers reuse\n// canonical identifiers instead of inventing them.\ninterface Catalog {\n integrations: Array<{\n id: string;\n label: string;\n connected: boolean;\n kind: string;\n accessor: string;\n description?: string;\n hasTriggers?: boolean;\n }>;\n providerKeys: Array<{ name: string; provider: string; set: boolean; accessor: string }>;\n customEnv: Array<{ name: string; set: boolean; hint?: string }>;\n}\n\nexport async function connectionsListCommand(opts?: { json?: boolean }): Promise<void> {\n const res = await api.get(\"/v1/connections/catalog\");\n if (!res.ok) {\n console.error(\"Failed to fetch the connections catalog.\");\n process.exit(1);\n }\n\n const catalog = (await res.json()) as Catalog;\n\n // Agent-consumable form: the full catalog payload, including fields the\n // table omits (docs, spec_url — the provider's published OpenAPI spec).\n if (opts?.json) {\n console.log(JSON.stringify(catalog, null, 2));\n return;\n }\n\n const idWidth = Math.max(2, ...catalog.integrations.map((i) => i.id.length));\n const labelWidth = Math.max(5, ...catalog.integrations.map((i) => i.label.length));\n\n console.log(\"Integrations (use the exact id — never invent a slug)\\n\");\n console.log(\n ` ${\"Id\".padEnd(idWidth)} ${\"Label\".padEnd(labelWidth)} ${\"State\".padEnd(9)} Accessor`\n );\n console.log(\n ` ${\"─\".repeat(idWidth)} ${\"─\".repeat(labelWidth)} ${\"─\".repeat(9)} ${\"─\".repeat(30)}`\n );\n for (const i of catalog.integrations) {\n const state = i.connected ? \"● active\" : \"○ —\";\n console.log(\n ` ${i.id.padEnd(idWidth)} ${i.label.padEnd(labelWidth)} ${state.padEnd(9)} ${i.accessor}`\n );\n }\n\n const keyWidth = Math.max(4, ...catalog.providerKeys.map((k) => k.name.length));\n console.log(\"\\nProvider keys (fixed names, set in Settings → API Keys)\\n\");\n for (const k of catalog.providerKeys) {\n console.log(` ${k.name.padEnd(keyWidth)} ${k.set ? \"● set\" : \"○ unset\"}`);\n }\n\n console.log(\"\\nCustom env (this org's user-defined vars)\\n\");\n if (catalog.customEnv.length === 0) {\n console.log(\" (none set)\");\n } else {\n const envWidth = Math.max(4, ...catalog.customEnv.map((e) => e.name.length));\n for (const e of catalog.customEnv) {\n console.log(` ${e.name.padEnd(envWidth)} ● set${e.hint ? ` (${e.hint})` : \"\"}`);\n }\n }\n}\n\nconst INTEGRATIONS_URL = \"https://app.clawnify.com/settings/integrations\";\n\n/**\n * `clawnify connections connect <id>` — explain how to connect an integration.\n * Connecting is an OAuth flow that needs the user's authorization in a browser;\n * neither the CLI nor an agent can do it. This validates the id against the\n * catalog and prints the canonical steps (so the FDE relays correct guidance\n * instead of improvising a dashboard path) — it never attempts the connect.\n */\nexport async function connectionsConnectCommand(\n id: string,\n opts?: { json?: boolean },\n): Promise<void> {\n const res = await api.get(\"/v1/connections/catalog\");\n if (!res.ok) {\n console.error(\"Failed to fetch the connections catalog.\");\n process.exit(1);\n }\n const catalog = (await res.json()) as Catalog;\n const match = catalog.integrations.find((i) => i.id === id);\n\n if (!match) {\n console.error(\n `No integration with id \"${id}\". Run \\`clawnify connections list\\` for valid ids.\\n` +\n `(Provider API keys are set in Settings → API Keys; custom env in Settings → Environment Variables.)`,\n );\n process.exit(1);\n }\n if (match.connected) {\n console.log(`\"${match.label}\" (${id}) is already connected (● active). Nothing to do.`);\n return;\n }\n\n const steps = [\n `Open ${INTEGRATIONS_URL}`,\n `Find \"${match.label}\" and click Connect`,\n `Complete the sign-in / authorization in the browser`,\n `Re-run your command once it shows connected`,\n ];\n if (opts?.json) {\n console.log(\n JSON.stringify(\n { id, label: match.label, connected: false, connect_url: INTEGRATIONS_URL, steps },\n null,\n 2,\n ),\n );\n return;\n }\n console.log(`\"${match.label}\" (${id}) is not connected.\\n`);\n console.log(\n \"Connecting it needs your authorization in a browser — the CLI and the agent can't do it for you. To connect it:\\n\",\n );\n steps.forEach((s, n) => console.log(` ${n + 1}. ${s}`));\n console.log(`\\n ${INTEGRATIONS_URL}`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { api, listMyOrgs, resolveOrgContext, type Org } from \"../lib/api.js\";\nimport { getValidToken, 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 // Folder-first (link → workspace.org → env), never a machine-global default.\n const resolved = await resolveOrgContext();\n const match = resolved ? orgs.find((o) => o.id === resolved) : undefined;\n if (match) return match;\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- \\`agents/<name>/\\` — one folder per OpenClaw agent (AGENT.md, skills/, flows/).\n- \\`website/\\` — the org's single public website (Astro).\n\n## Add an app / an agent / the website\n\n\\`\\`\\`bash\nclawnify init # app → apps/<name>/ (inherits the org)\nclawnify init --type agent # agent → agents/<name>/\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/, agents/, and website/ in git even before anything is added.\n write(targetDir, \"apps/.gitkeep\", \"\");\n write(targetDir, \"agents/.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\n// ---------------------------------------------------------------------------\n// `clawnify workspace` (bare) — orientation for humans AND coding agents.\n// Prints who you are, which GitHub repo backs the org, the subdir↔target\n// map, and the operating contract for editing locally. This is the CLI's\n// front door: a one-line prompt (\"run `npx clawnify@latest workspace` and\n// follow it\") must be enough for an agent to bootstrap.\n// ---------------------------------------------------------------------------\n\ninterface WorkspaceStatusOptions {\n json?: boolean;\n}\n\ninterface RepoLink {\n repo: string;\n branch: string;\n subdir: string;\n auto_deploy: boolean;\n installation_id: number;\n target:\n | { type: \"app\"; slug: string; name: string }\n | { type: \"website\"; slug: string }\n | { type: \"agent\"; name: string };\n}\n\n/** The operating contract, phrased for a coding agent. Version-shipped with\n * the CLI, so `npx clawnify@latest` always prints the current rules. */\nconst WORKSPACE_GUIDE = `How editing works:\n - The org has ONE workspace repo on GitHub. The website lives under\n website/ (Astro), apps under apps/<slug>/, agent configs under\n agents/<name>/. Each folder two-way syncs with Clawnify.\n - Pushing to the synced branch auto-rebuilds ONLY the folders that\n changed. Clawnify also pushes its own edits back into the repo, so\n pull before you start.\n - Website: cd website && pnpm install && pnpm dev (Node 22+; preview on\n localhost:4321). Do NOT use \\`clawnify dev\\` for the website — it is\n for apps only. Reuse the existing components/blocks under src/.\n - Apps: cd apps/<slug> && clawnify dev.\n - Website deploys (via push or \\`clawnify deploy\\` from website/) land on\n the DRAFT site (<slug>.draft-site.clawnify.com), visible only to the\n org. Going live is a separate \"Publish\" step in the dashboard —\n remind the user.\n - NEVER commit .env files or .clawnify/ folders — they hold secrets.\n Never commit or echo tokens found in them.\n - Run \\`clawnify ai-files install\\` in the repo once: it installs\n Clawnify rules, skills, and MCP access for coding agents.\n - Per-app deep docs: \\`clawnify docs <app-slug>\\`.`;\n\nexport async function workspaceStatusCommand(\n opts?: WorkspaceStatusOptions,\n): Promise<void> {\n const token = await getValidToken();\n if (!token) {\n if (opts?.json) {\n console.log(JSON.stringify({ logged_in: false, next: \"clawnify login\" }));\n process.exit(1);\n }\n console.log(`Not logged in.\n\n \\`clawnify login\\` opens a browser for OAuth — a coding agent cannot\n complete it headlessly. Ask the user to run:\n\n npx clawnify@latest login\n\n then re-run \\`clawnify workspace\\`.\n\n${WORKSPACE_GUIDE}`);\n process.exit(1);\n }\n\n // Folder-first, via the shared resolver. This command describes *this*\n // workspace, so reading a machine-global org here reported a different\n // tenant's repo, apps and agents for a folder explicitly pinned to another\n // org — and it labelled the output with that global org's slug, so the\n // wrong answer looked authoritative.\n const orgId = await resolveOrgContext();\n const res = await api.get(\"/v1/github/links\", orgId ? { orgId } : undefined);\n if (!res.ok) {\n console.error(`Failed to load workspace state (${res.status}).`);\n process.exit(1);\n }\n const data = (await res.json()) as {\n org_id: string;\n installations: { installation_id: number; github_account: string }[];\n links: RepoLink[];\n };\n\n if (opts?.json) {\n console.log(JSON.stringify({ logged_in: true, ...data, guide: WORKSPACE_GUIDE }));\n return;\n }\n\n // Label from what the API actually answered for, never from local auth state:\n // a label sourced separately from the data is how a wrong org reads as right.\n console.log(`Org: ${data.org_id}`);\n\n if (data.links.length === 0) {\n console.log(`\n No GitHub repo is linked yet. Local editing works through the org's\n synced workspace repo. Enable the sync from here:\n\n clawnify workspace connect\n\n That creates the workspace repo (installing the Clawnify GitHub App\n first if needed — a browser step for the user) and pushes the current\n website source. Then re-run \\`clawnify workspace\\` for the clone URL.\n\n${WORKSPACE_GUIDE}`);\n return;\n }\n\n // Group links by repo (normally exactly one workspace repo per org/account).\n const byRepo = new Map<string, RepoLink[]>();\n for (const l of data.links) {\n const list = byRepo.get(`${l.repo}#${l.branch}`) ?? [];\n list.push(l);\n byRepo.set(`${l.repo}#${l.branch}`, list);\n }\n\n for (const [key, list] of byRepo) {\n const [repo, branch] = key.split(\"#\");\n console.log(`\\nRepo: ${repo} (branch ${branch})`);\n console.log(` Clone: git clone https://github.com/${repo}.git`);\n for (const l of list) {\n const label =\n l.target.type === \"app\"\n ? `app: ${l.target.name} (${l.target.slug})`\n : l.target.type === \"website\"\n ? `website: ${l.target.slug}`\n : `agent: ${l.target.name}`;\n console.log(` ${(l.subdir || \"(root)\").padEnd(28)} ${label}`);\n }\n }\n\n console.log(`\\n${WORKSPACE_GUIDE}`);\n}\n\n// ---------------------------------------------------------------------------\n// `clawnify workspace connect` — enable GitHub sync from the CLI.\n// The dashboard's connect flow, orchestrated over existing API endpoints so\n// external coding agents (Claude Code, Codex) — which can't drive the\n// dashboard UI — can set up the workspace repo themselves. The one step the\n// CLI cannot do is the GitHub App INSTALL (GitHub has no headless install):\n// for that it prints the URL, hands it to the user, and polls until the\n// installation appears, then completes the connect itself.\n// ---------------------------------------------------------------------------\n\ninterface WorkspaceConnectOptions {\n /** Pick the GitHub account (installation id or login) when the org has several. */\n account?: string;\n}\n\nconst INSTALL_URL = \"https://github.com/apps/clawnify/installations/new\";\nconst INSTALL_POLL_MS = 5_000;\nconst INSTALL_TIMEOUT_MS = 5 * 60_000;\n\ninterface Installation {\n id: number;\n account: string;\n account_type: string;\n}\n\nasync function listInstallations(orgId?: string): Promise<Installation[]> {\n const res = await api.get(\"/settings/github/installations\", orgId ? { orgId } : undefined);\n if (!res.ok) return [];\n const data = (await res.json()) as { installations?: Installation[] };\n return data.installations ?? [];\n}\n\nexport async function workspaceConnectCommand(\n opts?: WorkspaceConnectOptions,\n): Promise<void> {\n const token = await getValidToken();\n if (!token) {\n console.log(`Not logged in.\n\n \\`clawnify login\\` opens a browser for OAuth — a coding agent cannot\n complete it headlessly. Ask the user to run:\n\n npx clawnify@latest login\n\n then re-run \\`clawnify workspace connect\\`.`);\n process.exit(1);\n }\n\n const orgId = await resolveOrgContext();\n const orgOpt = orgId ? { orgId } : undefined;\n\n // 1. The org needs the GitHub App installed on some account. If it isn't,\n // the install is a browser step — print the URL and poll until the\n // callback registers the installation for this org.\n let installs = await listInstallations(orgId);\n if (installs.length === 0) {\n console.log(`No GitHub account is connected to this workspace yet.\n\n Ask the user to install the Clawnify GitHub App (browser step):\n\n ${INSTALL_URL}\n\n They should pick the GitHub account/org where the workspace repo will\n live. Waiting for the installation to appear (up to 5 minutes)...`);\n\n const deadline = Date.now() + INSTALL_TIMEOUT_MS;\n while (Date.now() < deadline && installs.length === 0) {\n await new Promise((r) => setTimeout(r, INSTALL_POLL_MS));\n installs = await listInstallations(orgId);\n }\n if (installs.length === 0) {\n console.error(`\n Timed out waiting. Once the user has completed the install, re-run:\n\n clawnify workspace connect`);\n process.exit(1);\n }\n console.log(` ✓ GitHub account connected: ${installs[0]!.account}`);\n }\n\n // 2. Pick the installation. One → use it; several → require --account.\n let install = installs[0]!;\n if (installs.length > 1) {\n const match = opts?.account\n ? installs.find(\n (i) => String(i.id) === opts.account || i.account.toLowerCase() === opts.account!.toLowerCase(),\n )\n : undefined;\n if (!match) {\n console.error(\n `Multiple GitHub accounts are connected — pick one with --account:\\n` +\n installs.map((i) => ` --account ${i.account} (${i.account_type}, id ${i.id})`).join(\"\\n\"),\n );\n process.exit(1);\n }\n install = match;\n }\n\n // 3. Resolve the org's website (the workspace-repo anchor; apps join the\n // monorepo afterwards via the dashboard or their own flows).\n const siteRes = await api.get(\"/v1/websites\", orgOpt);\n const site = siteRes.ok\n ? (((await siteRes.json()) as { website?: { id?: string; slug?: string } }).website ?? {})\n : {};\n if (!site.id) {\n console.error(`This workspace has no website yet — there is nothing to sync.\n\n Create the website first (dashboard → Website), then re-run\n \\`clawnify workspace connect\\`.`);\n process.exit(1);\n }\n\n // 4. Create-or-join the workspace repo and link the website under website/.\n console.log(`Connecting ${site.slug ?? \"website\"} via @${install.account}...`);\n const res = await api.post(\n \"/settings/github/connect\",\n { website_id: site.id, installation_id: install.id },\n orgOpt,\n );\n const data = (await res.json().catch(() => ({}))) as {\n repo?: string; branch?: string; subdir?: string; url?: string;\n error?: string; needsReauth?: boolean;\n };\n if (!res.ok || !data.repo) {\n if (data.needsReauth) {\n console.error(`GitHub authorization expired. Ask the user to reconnect (browser step):\n\n https://app.clawnify.com/github/reauth?state=website\n\n then re-run \\`clawnify workspace connect\\`.`);\n } else {\n console.error(`Connect failed: ${data.error ?? `HTTP ${res.status}`}`);\n }\n process.exit(1);\n }\n\n console.log(`\n ✓ Workspace repo connected: ${data.repo} (branch ${data.branch ?? \"main\"})\n\n Clone: git clone https://github.com/${data.repo}.git\n The website lives under ${data.subdir ?? \"website\"}/ — pushes to\n ${data.branch ?? \"main\"} auto-deploy to the draft site.\n\n Run \\`clawnify workspace\\` any time for the full map + editing contract.`);\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 } from \"./auth.js\";\nimport { resolveOrgContext } from \"./api.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 headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: \"Bearer \" + token,\n };\n const orgId = await resolveOrgContext();\n if (orgId) {\n headers[\"X-Clawnify-Org-Id\"] = orgId;\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 } from \"../lib/auth.js\";\nimport { resolveOrgContext } from \"../lib/api.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 orgId = await resolveOrgContext();\n if (!orgId) {\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/${orgId}/${slug}.md?caller=${caller}` : `/docs/${orgId}/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\";\nimport { resolveOrgContext } from \"../lib/api.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 // Resolved from the directory the bridge was started in, not from a\n // machine-global default another session can repoint.\n const bridgeOrgId = await resolveOrgContext();\n if (bridgeOrgId) {\n baseHeaders[\"X-Clawnify-Org-Id\"] = bridgeOrgId;\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","/**\n * `clawnify flows` — manage the main agent's ClawFlow definitions on the org's server.\n *\n * clawnify flows list list drafts (+ latest published version)\n * clawnify flows read <name> print a flow's draft definition\n * clawnify flows create <name> --file f create a draft from a local JSON file\n * clawnify flows edit <name> [--file f] replace the draft (opens $EDITOR without --file)\n * clawnify flows publish <name> snapshot the draft as the next numbered version\n *\n * Flows belong to the server's MAIN agent: one ClawFlow instance runs per\n * gateway, bound to main's workspace/flows — a specialist agent's flows/ dir\n * is never executed (same rule as `deploy-agent-config`).\n *\n * Drafts are validated on-box against the LIVE engine registry (so custom\n * steps like `do: clawnify_app` validate correctly) and publishing snapshots\n * via the engine's own publishDraft — never a second parser or mirrored\n * version layout. Backed by POST /servers/:id/flows[/publish] → the box hook.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { api } from \"../lib/api.js\";\nimport { resolveServerId } from \"../lib/servers.js\";\n\ninterface CommonOpts {\n server?: string;\n}\n\ninterface FlowSummary {\n file: string;\n flow: string;\n description: string | null;\n nodes: unknown[];\n published: number | null;\n updated_at: string;\n}\n\ninterface ValidationIssue {\n node?: string;\n field?: string;\n message: string;\n}\n\n/** The flow file name the box expects (plain name → <name>.json). */\nfunction flowFileName(name: string): string {\n return name.endsWith(\".json\") ? name : `${name}.json`;\n}\n\n/** Read + parse a local flow definition, exiting with a clear error. */\nfunction parseFlowFile(file: string): Record<string, unknown> {\n const abs = path.resolve(file);\n let raw: string;\n try {\n raw = fs.readFileSync(abs, \"utf8\");\n } catch {\n console.error(`Cannot read ${abs}.`);\n process.exit(1);\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error();\n return parsed as Record<string, unknown>;\n } catch {\n console.error(`${abs} is not a valid flow definition (expected a JSON object).`);\n process.exit(1);\n }\n}\n\n/** Print the engine's validation errors from a 422 payload, then exit. */\nfunction failValidation(payload: { error?: string; errors?: ValidationIssue[] }, note?: string): never {\n console.error(payload.error ?? \"Flow validation failed:\");\n for (const e of payload.errors ?? []) {\n const where = [e.node && `node \"${e.node}\"`, e.field].filter(Boolean).join(\", \");\n console.error(` - ${where ? `${where}: ` : \"\"}${e.message}`);\n }\n if (note) console.error(note);\n process.exit(1);\n}\n\n/**\n * Find a flow's summary on the box, or null when there's no draft by that name.\n * Uses the list (not get-flow) because it also carries `published`, which\n * decides whether a draft edit is safe or is itself the live definition.\n */\nasync function findDraft(serverId: string, name: string): Promise<FlowSummary | null> {\n const res = await api.get(`/servers/${serverId}/flows`);\n if (!res.ok) return null;\n const { flows } = (await res.json()) as { flows: FlowSummary[] };\n return (flows ?? []).find((f) => f.file === flowFileName(name)) ?? null;\n}\n\n/** POST the draft; on validation errors print them and exit. */\nasync function saveDraft(\n serverId: string,\n name: string,\n flow: Record<string, unknown>,\n validationNote?: string,\n): Promise<void> {\n // The box keys drafts by bare name — a `.json` here would be stripped to\n // \"myflowjson\" by the hook's sanitizer and quietly create a second flow.\n const res = await api.post(`/servers/${serverId}/flows`, {\n name: name.replace(/\\.json$/, \"\"),\n flow,\n });\n const payload = (await res.json().catch(() => ({}))) as {\n error?: string;\n errors?: ValidationIssue[];\n code?: string;\n };\n if (res.status === 422 && payload.errors) failValidation(payload, validationNote);\n if (!res.ok) {\n console.error(`Failed to save draft (${res.status})${payload.error ? `: ${payload.error}` : \"\"}.`);\n process.exit(1);\n }\n}\n\nexport async function flowsListCommand(opts: CommonOpts & { json?: boolean }): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const res = await api.get(`/servers/${serverId}/flows`);\n if (!res.ok) {\n console.error(`Failed to list flows (${res.status}).`);\n process.exit(1);\n }\n const { flows } = (await res.json()) as { flows: FlowSummary[] };\n if (opts.json) {\n console.log(JSON.stringify(flows, null, 2));\n return;\n }\n if (!flows || flows.length === 0) {\n console.log(\"This agent has no flows yet. Create one with: clawnify flows create <name> --file flow.json\");\n return;\n }\n\n const nameW = Math.max(4, ...flows.map((f) => f.flow.length));\n console.log(`${\"Name\".padEnd(nameW)} ${\"Nodes\".padEnd(5)} ${\"Published\".padEnd(9)} Updated`);\n console.log(`${\"─\".repeat(nameW)} ${\"─\".repeat(5)} ${\"─\".repeat(9)} ${\"─\".repeat(10)}`);\n for (const f of flows) {\n const published = f.published != null ? `v${f.published}` : \"—\";\n const updated = (f.updated_at ?? \"\").slice(0, 16).replace(\"T\", \" \");\n console.log(`${f.flow.padEnd(nameW)} ${String(f.nodes?.length ?? 0).padEnd(5)} ${published.padEnd(9)} ${updated}`);\n }\n}\n\nexport async function flowsReadCommand(name: string, opts: CommonOpts): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const res = await api.get(`/servers/${serverId}/flows?name=${encodeURIComponent(flowFileName(name))}`);\n if (!res.ok) {\n if (res.status === 404) console.error(`No draft flow named \"${name}\" on this agent.`);\n else console.error(`Failed to read flow (${res.status}).`);\n process.exit(1);\n }\n const { flow } = (await res.json()) as { flow: unknown };\n console.log(JSON.stringify(flow, null, 2));\n}\n\nexport async function flowsCreateCommand(\n name: string,\n opts: CommonOpts & { file?: string },\n): Promise<void> {\n if (!opts.file) {\n console.error(`Provide the flow definition: clawnify flows create ${name} --file flow.json`);\n process.exit(1);\n }\n const serverId = await resolveServerId(opts.server);\n const flow = parseFlowFile(opts.file);\n\n if (await findDraft(serverId, name)) {\n console.error(`A draft named \"${name}\" already exists. Update it with: clawnify flows edit ${name} --file ${opts.file}`);\n process.exit(1);\n }\n\n await saveDraft(serverId, name, flow);\n const nodes = Array.isArray(flow.nodes) ? flow.nodes.length : 0;\n console.log(`Created draft flow \"${name}\" (${nodes} node${nodes === 1 ? \"\" : \"s\"}). Until it has a published version, runs and triggers execute this draft — cut v1 with: clawnify flows publish ${name}`);\n}\n\nexport async function flowsEditCommand(\n name: string,\n opts: CommonOpts & { file?: string },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n const existing = await findDraft(serverId, name);\n if (!existing) {\n console.error(`No draft flow named \"${name}\" on this agent. Create it with: clawnify flows create ${name} --file flow.json`);\n process.exit(1);\n }\n\n let flow: Record<string, unknown>;\n let tmpDir: string | null = null;\n let tmpFile: string | null = null;\n if (opts.file) {\n flow = parseFlowFile(opts.file);\n } else {\n // Round-trip through $EDITOR: seed a temp file with the current draft,\n // reopen it, and save back whatever the user left behind.\n const res = await api.get(`/servers/${serverId}/flows?name=${encodeURIComponent(flowFileName(name))}`);\n const { flow: current } = (await res.json()) as { flow: Record<string, unknown> };\n\n tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), \"clawnify-flow-\"));\n tmpFile = path.join(tmpDir, flowFileName(name));\n fs.writeFileSync(tmpFile, JSON.stringify(current, null, 2) + \"\\n\");\n\n const editor = process.env.VISUAL || process.env.EDITOR || \"vi\";\n const result = spawnSync(`${editor} \"${tmpFile}\"`, { shell: true, stdio: \"inherit\" });\n if (result.status !== 0) {\n console.error(`Editor exited without saving — draft unchanged (kept at ${tmpFile}).`);\n process.exit(1);\n }\n\n const edited = fs.readFileSync(tmpFile, \"utf8\");\n if (edited === JSON.stringify(current, null, 2) + \"\\n\") {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n console.log(\"No changes.\");\n return;\n }\n try {\n flow = JSON.parse(edited) as Record<string, unknown>;\n } catch {\n console.error(`Edited file is not valid JSON — draft unchanged (kept at ${tmpFile}; re-save with: clawnify flows edit ${name} --file \"${tmpFile}\")`);\n process.exit(1);\n }\n }\n\n await saveDraft(\n serverId,\n name,\n flow,\n tmpFile ? `Draft unchanged — your edits are kept at ${tmpFile}; fix and re-save with: clawnify flows edit ${name} --file \"${tmpFile}\"` : undefined,\n );\n\n if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });\n console.log(\n existing.published != null\n ? `Saved draft \"${name}\". Runs and triggers keep using v${existing.published} — publish to make this live: clawnify flows publish ${name}`\n : `Saved draft \"${name}\". This flow has no published version, so runs and triggers execute the draft as-is — cut v1 with: clawnify flows publish ${name}`,\n );\n}\n\nexport async function flowsPublishCommand(name: string, opts: CommonOpts): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const res = await api.post(`/servers/${serverId}/flows/publish`, { name });\n const payload = (await res.json().catch(() => ({}))) as {\n error?: string;\n errors?: ValidationIssue[];\n version?: number;\n };\n if (res.status === 404) {\n console.error(`No draft flow named \"${name}\" on this agent — nothing to publish.`);\n process.exit(1);\n }\n if (res.status === 422 && payload.errors) failValidation(payload);\n if (!res.ok) {\n console.error(`Failed to publish (${res.status})${payload.error ? `: ${payload.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log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,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":["redirectUri","fs","path","readline","path","fs","path","readline","path","polled","fs","result","fs","path","path","fs","path","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","spawn","path","spawn","path","UUID_RE","path","path","path","fs","path","slugify","match","write","path","fs","fs","fs","path","readline","MCP_URL","readline","resolveAgents","fs","path","path","fs"]}
|