clawnify 0.5.0 → 0.6.1

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.
@@ -5,6 +5,7 @@ import {
5
5
  OAUTH_TOKEN_URL,
6
6
  api,
7
7
  createArchive,
8
+ findWorkspaceRoot,
8
9
  generatePkce,
9
10
  getEmailFromToken,
10
11
  getValidToken,
@@ -14,9 +15,10 @@ import {
14
15
  pollUntilReady,
15
16
  readManifest,
16
17
  readProject,
18
+ readWorkspaceConfig,
17
19
  saveAuth,
18
20
  saveProject
19
- } from "./chunk-3HQ3VZOS.js";
21
+ } from "./chunk-HOCFYU72.js";
20
22
 
21
23
  // src/cli.ts
22
24
  import { Command } from "commander";
@@ -107,7 +109,11 @@ async function loginCommand() {
107
109
  });
108
110
  server.listen(port, () => {
109
111
  console.log("Opening browser to authorize...");
110
- open(authUrl.toString());
112
+ console.log("\nBrowser didn't open? Use the url below to sign in:\n");
113
+ console.log(` ${authUrl.toString()}
114
+ `);
115
+ open(authUrl.toString()).catch(() => {
116
+ });
111
117
  console.log("Waiting for authorization...");
112
118
  });
113
119
  });
@@ -328,7 +334,7 @@ function assertNodeVersion() {
328
334
  process.exit(1);
329
335
  }
330
336
  }
331
- async function resolveOrgId(options, linkedProject) {
337
+ async function resolveOrgId(options, linkedProject, resolvedDir) {
332
338
  if (options.org) {
333
339
  const orgs = await listMyOrgs();
334
340
  const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
@@ -351,8 +357,26 @@ async function resolveOrgId(options, linkedProject) {
351
357
  if (linkedProject?.app_id && linkedProject.org_id) {
352
358
  return linkedProject.org_id;
353
359
  }
360
+ if (resolvedDir) {
361
+ const wsOrg = await workspaceOrgId(resolvedDir);
362
+ if (wsOrg) return wsOrg;
363
+ }
354
364
  return void 0;
355
365
  }
366
+ async function workspaceOrgId(resolvedDir) {
367
+ const ws = findWorkspaceRoot(resolvedDir);
368
+ if (!ws?.org) return void 0;
369
+ const orgs = await listMyOrgs();
370
+ const match = orgs.find((o) => o.id === ws.org || o.slug === ws.org);
371
+ if (!match) {
372
+ console.error(
373
+ `This workspace is bound to org "${ws.org}", but you're not a member of it (or it no longer exists).
374
+ Available: ${orgs.map((o) => o.slug).join(", ")}`
375
+ );
376
+ process.exit(EXIT_USAGE);
377
+ }
378
+ return match.id;
379
+ }
356
380
  async function resolveConflictDecision(options, conflict) {
357
381
  if (options.updateExisting) return "update";
358
382
  if (options.createNew) return "create";
@@ -443,6 +467,8 @@ async function deployWebsite(dir, options) {
443
467
  orgId = match.id;
444
468
  } else if (linkedProject?.website_id && linkedProject.org_id) {
445
469
  orgId = linkedProject.org_id;
470
+ } else {
471
+ orgId = await workspaceOrgId(resolvedDir);
446
472
  }
447
473
  if (options.dryRun) {
448
474
  const sizeKB = (archive.length / 1024).toFixed(1);
@@ -480,15 +506,30 @@ async function deployWebsite(dir, options) {
480
506
  `);
481
507
  process.exit(1);
482
508
  }
483
- console.log(`
484
- \u2713 Deployed! ${result.data.url}
509
+ if (polled.status === "live") {
510
+ console.log(`
511
+ \u2713 Published! ${result.data.url}
485
512
  `);
513
+ } else {
514
+ console.log(
515
+ `
516
+ \u2713 Deployed to draft.
517
+ Review it in the dashboard, then "Publish to live" when ready.
518
+ `
519
+ );
520
+ }
486
521
  }
487
522
  async function deployCommand(dir, options = {}) {
488
523
  assertNodeVersion();
489
524
  if (!options.from) {
490
525
  const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
491
526
  const manifest = readManifest(resolvedDir);
527
+ if (!manifest && readWorkspaceConfig(resolvedDir)) {
528
+ console.error(
529
+ "This is a Clawnify workspace root, not an app.\n Deploy a specific app: clawnify deploy apps/<name>\n Or cd into one: cd apps/<name> && clawnify deploy"
530
+ );
531
+ process.exit(EXIT_USAGE);
532
+ }
492
533
  if (manifest) {
493
534
  try {
494
535
  const kind = manifestKind(manifest);
@@ -508,15 +549,18 @@ async function deployCommand(dir, options = {}) {
508
549
  let syncTargetDir;
509
550
  if (options.from) {
510
551
  const repo = options.from.replace(/^github:/, "");
552
+ const subdir = options.path?.trim().replace(/^\/+|\/+$/g, "") || void 0;
511
553
  if (options.dryRun) {
512
- console.log(`
513
- Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main)
514
- `);
554
+ console.log(
555
+ `
556
+ Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : ""})
557
+ `
558
+ );
515
559
  return;
516
560
  }
517
- console.log(`Deploying from ${repo}...`);
561
+ console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : ""}...`);
518
562
  const orgId = options.org ? await resolveOrgId(options, null) : void 0;
519
- const res = await api.post("/v1/apps/deploy", { repo, branch: "main" }, { orgId });
563
+ const res = await api.post("/v1/apps/deploy", { repo, branch: "main", subdir }, { orgId });
520
564
  if (!res.ok) {
521
565
  const err = await res.json().catch(() => ({}));
522
566
  console.error(`Deploy failed: ${err.error || res.statusText}`);
@@ -536,7 +580,7 @@ async function deployCommand(dir, options = {}) {
536
580
  const linkedProject = readProject(resolvedDir);
537
581
  await regenerateDrizzleMigrations(resolvedDir);
538
582
  const { archive, files } = createArchive(resolvedDir);
539
- const orgId = await resolveOrgId(options, linkedProject);
583
+ const orgId = await resolveOrgId(options, linkedProject, resolvedDir);
540
584
  if (options.dryRun) {
541
585
  summarizeArchive(archive, files, framework, baseName);
542
586
  if (linkedProject?.app_id) {
@@ -792,122 +836,561 @@ async function whoamiCommand() {
792
836
  import fs3 from "fs";
793
837
  import path3 from "path";
794
838
  import readline4 from "readline";
795
- function ask2(question) {
796
- const rl = readline4.createInterface({
797
- input: process.stdin,
798
- output: process.stdout
799
- });
800
- return new Promise((resolve) => {
801
- rl.question(question, (answer) => {
802
- rl.close();
803
- resolve(answer.trim());
804
- });
805
- });
839
+
840
+ // src/lib/skills/detect.ts
841
+ import { statSync } from "fs";
842
+ import { join } from "path";
843
+ var DETECTORS = [
844
+ { agent: "claude", markers: [".claude", ".claude.json", "CLAUDE.md"], target: ".claude/skills" },
845
+ { agent: "cursor", markers: [".cursor", ".cursorrules"], target: ".cursor/rules" },
846
+ { agent: "openclaw", markers: [".openclaw", "openclaw.json"], target: ".openclaw/skills" },
847
+ { agent: "codex", markers: [".codex", "AGENTS.md"], target: ".codex/skills" },
848
+ { agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
849
+ ];
850
+ function exists(cwd, name) {
851
+ const path8 = join(cwd, name);
852
+ try {
853
+ statSync(path8);
854
+ return true;
855
+ } catch {
856
+ return false;
857
+ }
806
858
  }
807
- function slugify(name) {
808
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
859
+ function detectAgents(cwd) {
860
+ const found = [];
861
+ for (const d of DETECTORS) {
862
+ const hit = d.markers.find((m) => exists(cwd, m));
863
+ if (hit) {
864
+ found.push({ agent: d.agent, target: d.target, marker: hit });
865
+ }
866
+ }
867
+ return found;
809
868
  }
810
- async function askProjectType(opts) {
811
- if (opts?.type === "app" || opts?.type === "website") return opts.type;
812
- if (opts?.type) {
813
- console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);
814
- process.exit(1);
869
+ function agentByName(name) {
870
+ const d = DETECTORS.find((x) => x.agent === name);
871
+ if (!d) throw new Error(`Unknown agent: ${name}`);
872
+ return { agent: d.agent, target: d.target, marker: "(forced)" };
873
+ }
874
+ var ALL_AGENTS = DETECTORS.map((d) => d.agent);
875
+
876
+ // src/lib/skills/content.gen.ts
877
+ var CLI_VERSION = "0.6.1";
878
+ var BUNDLED_SKILLS = [
879
+ {
880
+ name: "build-a-clawnify-app",
881
+ description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + tRPC + @clawnify/db (Drizzle) stack, schema.ts as the single source of truth, MCP-tagged tRPC procedures, and X-Clawnify-* identity headers. Use when building or modifying an app that deploys to the Clawnify platform.",
882
+ content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare the patterns the platform expects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + tRPC + `@clawnify/db` (Drizzle)\n + Tailwind + shadcn/ui. Nothing else.\n- **Schema lives in `schema.ts`** (Drizzle DSL) \u2014 single source of\n truth. Never write SQL DDL by hand.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **`clawnify.json`** declares framework, env, and public routes.\n Build emits `api.tools[]` from tRPC procedure meta.\n- **No `/mcp` endpoint.** The org\'s MCP gateway projects tools\n from the manifest.\n- **Identity flows via `X-Clawnify-*` headers** injected by the\n platform. Read them, don\'t fake them.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked.\n\n## File layout\n\n```\nmy-app/\n clawnify.json \u2190 Manifest (validated against /schema/v1/clawnify.json)\n package.json\n tsconfig.json\n vite.config.ts\n tailwind.config.ts\n components.json \u2190 shadcn/ui config\n index.html\n drizzle.config.ts \u2190 Points at src/server/schema.ts \u2192 outputs to .clawnify/drizzle\n .clawnify/ \u2190 CLI cache (gitignored)\n drizzle/ \u2190 drizzle-kit generate output \u2014 never hand-edit\n 0000_<name>.sql\n meta/\n applied-migrations.json \u2190 Local-D1 applied tracker\n wrangler.toml \u2190 Generated per-dev wrangler config\n src/\n server/\n index.ts \u2190 Hono entry \u2014 mounts the tRPC router\n schema.ts \u2190 Drizzle table definitions \u2014 THE schema\n router.ts \u2190 tRPC router with MCP-tagged procedures\n auth.ts \u2190 Read X-Clawnify-* identity headers\n env.d.ts \u2190 Worker bindings types\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component\n lib/\n trpc.ts \u2190 Typed tRPC client\n components/ \u2190 shadcn/ui + your components\n styles.css\n```\n\n## `schema.ts` \u2014 the only place tables exist\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \u2014 Drizzle\n serializes on write and parses on read.\n- Multi-tenancy: every user-facing table has `org_id`. Every query\n filters by it. No exceptions.\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\n\n## `drizzle.config.ts`\n\n```ts\nimport { defineConfig } from "drizzle-kit";\n\nexport default defineConfig({\n schema: "./src/server/schema.ts",\n out: "./.clawnify/drizzle",\n dialect: "sqlite",\n});\n```\n\nYou never run `drizzle-kit` manually. The CLI runs it for you:\n\n- **`clawnify dev`** \u2014 runs `drizzle-kit generate`, applies any new\n migrations to local D1 via `wrangler d1 execute --local`, tracks\n applied state in `.clawnify/applied-migrations.json` (idempotent\n on rerun).\n- **`clawnify deploy`** \u2014 same generate step, then auto-includes\n `.clawnify/drizzle/*.sql` in the upload tar (remapped to\n `drizzle/<name>` for the deploy pipeline, which applies them\n transactionally to D1 + Facet and records in `__clawnify_migrations`).\n\nThe output dir (`.clawnify/drizzle/`) is gitignored. Migrations\nare derived artifacts, not source \u2014 never commit them, never edit\nthem. The single source of truth is `schema.ts`.\n\n## `src/server/index.ts` \u2014 Hono entry\n\n```ts\nimport { Hono } from "hono";\nimport { trpcServer } from "@hono/trpc-server";\nimport { appRouter } from "./router";\nimport { createContext } from "./auth";\n\nconst app = new Hono<{ Bindings: Env }>();\n\napp.use("/trpc/*", trpcServer({\n router: appRouter,\n createContext: (opts, c) => createContext(opts, c.env, c.req.raw),\n}));\n\n// SPA fallback \u2014 Vite-built static assets served by the platform\napp.notFound((c) => c.env.ASSETS.fetch(c.req.raw));\n\nexport default app;\n```\n\nThat\'s it. The Worker entry is thin. No MCP mounting, no inline\nroute handlers \u2014 tRPC owns the API surface.\n\n## `src/server/auth.ts` \u2014 identity from headers\n\n```ts\nimport type { Context } from "hono";\n\nexport interface User {\n id: string;\n orgId: string;\n email: string;\n caller: "user" | "agent" | "agent-browser" | "system";\n}\n\nexport function readUser(req: Request): User | null {\n const id = req.headers.get("X-Clawnify-User-Id");\n const orgId = req.headers.get("X-Clawnify-Org-Id");\n const email = req.headers.get("X-Clawnify-User-Email") ?? "";\n const caller = (req.headers.get("X-Clawnify-Caller") ?? "user") as User["caller"];\n if (!id || !orgId) return null;\n return { id, orgId, email, caller };\n}\n\nexport function createContext(_opts: unknown, env: Env, req: Request) {\n const user = readUser(req);\n return { env, user };\n}\n```\n\nTrust these headers \u2014 the platform strips client-supplied versions\nand reinjects authenticated ones at the perimeter. Never read\n`Authorization` or session cookies directly.\n\n## `src/server/router.ts` \u2014 tRPC procedures with MCP meta\n\n```ts\nimport { initTRPC } from "@trpc/server";\nimport { z } from "zod";\nimport { getDB, eq, desc, and } from "@clawnify/db";\nimport * as schema from "./schema";\nimport type { User } from "./auth";\n\nconst t = initTRPC.context<{ env: Env; user: User | null }>().create();\n\nconst authed = t.procedure.use(({ ctx, next }) => {\n if (!ctx.user) throw new Error("UNAUTHORIZED");\n return next({ ctx: { ...ctx, user: ctx.user } });\n});\n\nexport const appRouter = t.router({\n list_notes: authed\n .meta({ mcp: { name: "list_notes", description: "List the user\'s notes." } })\n .input(z.object({ limit: z.number().int().min(1).max(100).default(50) }))\n .output(z.array(z.object({\n id: z.number(),\n title: z.string(),\n body: z.string(),\n tags: z.array(z.string()),\n createdAt: z.string(),\n })))\n .query(async ({ ctx, input }) => {\n const db = getDB(ctx.env, { schema });\n return db\n .select()\n .from(schema.notes)\n .where(eq(schema.notes.orgId, ctx.user.orgId))\n .orderBy(desc(schema.notes.createdAt))\n .limit(input.limit);\n }),\n\n create_note: authed\n .meta({ mcp: { name: "create_note", description: "Create a new note." } })\n .input(z.object({\n title: z.string().min(1),\n body: z.string().default(""),\n tags: z.array(z.string()).default([]),\n }))\n .mutation(async ({ ctx, input }) => {\n const db = getDB(ctx.env, { schema });\n const [row] = await db\n .insert(schema.notes)\n .values({ ...input, orgId: ctx.user.orgId })\n .returning();\n return row;\n }),\n});\n\nexport type AppRouter = typeof appRouter;\n```\n\nPatterns to follow:\n- **Every state-mutating procedure** that an agent might want to\n call gets `.meta({ mcp: { name, description } })`. The build\n picks these up into `clawnify.json api.tools[]`. The Clawnify\n MCP gateway projects them as MCP tools.\n- **Auth via middleware** (`authed`). Never check headers inside\n a procedure body.\n- **Filter by `ctx.user.orgId`** on every query. No exceptions.\n- **Schema-validated input + output** with Zod. The output schema\n is what the agent sees as the tool\'s return shape.\n- **Procedure names are intent verbs** (`archive_old_notes`,\n `publish_post`), not REST resource shapes (`get_notes`,\n `update_note`). Tools describe what the agent wants to do.\n\n## `src/client` \u2014 React + tRPC + shadcn\n\n```tsx\n// src/client/lib/trpc.ts\nimport { createTRPCReact, httpBatchLink } from "@trpc/react-query";\nimport type { AppRouter } from "../../server/router";\n\nexport const trpc = createTRPCReact<AppRouter>();\nexport const trpcClient = trpc.createClient({\n links: [httpBatchLink({ url: "/trpc" })],\n});\n```\n\n```tsx\n// src/client/app.tsx\nimport { useState } from "react";\nimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";\nimport { trpc, trpcClient } from "./lib/trpc";\nimport { Button } from "./components/ui/button";\n\nconst queryClient = new QueryClient();\n\nexport function App() {\n return (\n <trpc.Provider client={trpcClient} queryClient={queryClient}>\n <QueryClientProvider client={queryClient}>\n <NotesList />\n </QueryClientProvider>\n </trpc.Provider>\n );\n}\n\nfunction NotesList() {\n const notes = trpc.list_notes.useQuery({ limit: 50 });\n const create = trpc.create_note.useMutation({\n onSuccess: () => notes.refetch(),\n });\n const [title, setTitle] = useState("");\n\n return (\n <div>\n {notes.data?.map((n) => <div key={n.id}>{n.title}</div>)}\n <Button onClick={() => create.mutate({ title, body: "" })}>\n Add note\n </Button>\n </div>\n );\n}\n```\n\nThe same tRPC procedures power the agent (via MCP) and the UI (via\ntyped client). One backend, two front doors.\n\n## `clawnify.json` \u2014 the manifest\n\n```json\n{\n "$schema": "https://app.clawnify.com/schema/v1/clawnify.json",\n "version": 1,\n "name": "Notes",\n "description": "Take and organize notes. Searchable by tag.",\n "icon": "icon.svg",\n "tags": ["productivity"],\n "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "required": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\nRules:\n- **Don\'t hand-edit `api.tools[]`** \u2014 generated at build from tRPC\n `.meta({ mcp: { ... } })` annotations.\n- **Public routes are the exception**, not the default. Every tRPC\n procedure is private (auth-required) unless you explicitly add a\n matching path to `public_routes`. Use only for webhooks, RSS,\n embedded feeds.\n- **`framework: "react+hono"`** for new apps. Never `preact+hono` or\n `vite-preact` \u2014 those are legacy.\n- **`database: true`** if the app uses a DB. Schema is generated\n from `schema.ts` via drizzle-kit; no `schema.sql` to ship.\n\n## Migrations\n\nYou don\'t write migration SQL by hand. You don\'t even run a CLI\ncommand. The workflow is:\n\n1. Edit `src/server/schema.ts` to reflect the new shape.\n2. Restart `pnpm dev` (or it auto-restarts on save in some configs).\n\nThat\'s it. `clawnify dev` runs `drizzle-kit generate` under the\nhood, applies the diff to local D1, and tracks what\'s been applied\nin `.clawnify/applied-migrations.json` so reruns are no-ops.\n\nOn deploy, `clawnify deploy` does the same generate step, then the\ndeploy pipeline applies the migrations transactionally to live D1\nand the Facet (preview tier). Tracked in `__clawnify_migrations`.\n\nFor destructive changes (drop column, rename), Drizzle\'s generator\nemits the SQL; the agent should default to additive changes and\nonly do destructive ones when the user explicitly asks. Renames\nare risky on production data \u2014 prefer "add new column, backfill,\nswitch queries, drop old column" over a single-step rename.\n\n## What the agent must NOT do\n\n- Mount `/mcp` manually. The gateway projects tools from the\n manifest.\n- Author `schema.sql` by hand. Use `schema.ts`.\n- Author migration SQL by hand. The CLI runs `drizzle-kit generate`\n on dev + deploy. Never commit `drizzle/` or `.clawnify/drizzle/`.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw API has `json()` as a helper.\n- Bind tRPC procedures by REST resource shape (`get_user_by_id`).\n Use intent verbs (`onboard_user`, `archive_old_orders`).\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\n the `X-Clawnify-*` headers via `auth.ts`.\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.0` pulls it in transitively; only add it if\n you need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `sql`, `sqliteTable`, `text`, `integer`,\n etc. are all re-exported there). Drop to `drizzle-orm` directly\n only for things not re-exported.\n- Add `.meta({ mcp: { name, description } })` to every state-\n mutating procedure that the user\'s agent might want to call.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the Facet preview tier catches schema drift and\n type errors at build time.\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \u2014 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'
815
883
  }
816
- if (opts?.yes) return "app";
817
- console.log();
818
- console.log(" What are you creating?");
819
- console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
820
- console.log(" 2) website \u2014 public site (Astro)");
821
- console.log();
822
- const choice = await ask2("Type [1]: ") || "1";
823
- return choice === "2" ? "website" : "app";
884
+ ];
885
+ var RULES_CONTENT = "You are working inside a **Clawnify app** \u2014 a full-stack project that deploys to\nCloudflare through the Clawnify platform. Follow these rules.\n\n## Stack (fixed \u2014 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 \u2014 it is the single source of truth.\n- **Never** hand-write SQL migrations or edit a `schema.sql` by hand. `clawnify\n dev` and `clawnify deploy` run `drizzle-kit generate` for you.\n- Every user-facing table needs an `org_id` column, and every query must filter\n by the `X-Clawnify-Org-Id` request header. This is how multi-tenancy works \u2014\n there are no exceptions.\n\n## Identity comes from request headers, never the client\n\nThe platform injects identity headers the client cannot forge:\n`X-Clawnify-User-Id`, `X-Clawnify-Org-Id`, `X-Clawnify-User-Email`,\n`X-Clawnify-Caller`. Read them server-side. Never trust a client-supplied user\nor org id.\n\n## Integrations: use `@clawnify/connections`\n\nDon't store per-service API keys or OAuth secrets in the app. Declare what the\napp needs under `app.credentials` in `clawnify.json`, then call\n`connect(service, env)` and `secret(name, env)` from the SDK. Off-platform\n(local dev, scripts), put a `clw_` org service token in `.dev.vars` as\n`CLAWNIFY_TOKEN` \u2014 the SDK then resolves your **real** org connections over HTTP\nwith no per-service secrets.\n\n## Commands\n\n- `clawnify dev` \u2014 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` \u2014 ships the app live at `https://<slug>.apps.clawnify.com`.\n- Don't invoke raw `wrangler` or `drizzle-kit` \u2014 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 \u2014 routing, OpenAPI route definitions,\nclient data-fetching patterns, file uploads \u2014 read the **build-a-clawnify-app**\nskill installed alongside these rules.\n";
886
+
887
+ // src/lib/skills/install.ts
888
+ import {
889
+ existsSync as existsSync2,
890
+ mkdirSync,
891
+ readFileSync,
892
+ writeFileSync,
893
+ statSync as statSync2,
894
+ rmSync,
895
+ unlinkSync
896
+ } from "fs";
897
+ import { dirname, join as join2 } from "path";
898
+ var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
899
+ function versionHeader(name) {
900
+ return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
824
901
  }
825
- function detectPackageManager() {
826
- const ua = process.env.npm_config_user_agent ?? "";
827
- if (ua.startsWith("pnpm")) return "pnpm";
828
- if (ua.startsWith("yarn")) return "yarn";
829
- if (ua.startsWith("bun")) return "bun";
830
- return "npm";
902
+ function readExistingVersion(path8) {
903
+ if (!existsSync2(path8)) return null;
904
+ try {
905
+ const head = readFileSync(path8, "utf8").slice(0, 500);
906
+ const match = head.match(VERSION_HEADER_RE);
907
+ return match ? match[2] : null;
908
+ } catch {
909
+ return null;
910
+ }
831
911
  }
832
- async function initCommand(dir, opts) {
833
- const type = await askProjectType(opts);
834
- if (type === "website") {
835
- return initWebsite(dir, opts);
912
+ function installSkill(skill, agent, cwd) {
913
+ switch (agent.agent) {
914
+ case "claude":
915
+ return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);
916
+ case "codex":
917
+ return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);
918
+ case "openclaw":
919
+ return writeOpenclawSkill(skill, cwd, agent.target);
920
+ case "cursor":
921
+ return writeCursorRule(skill, cwd, agent.target);
922
+ case "aider":
923
+ return writeAiderSection(skill, cwd, agent.target);
836
924
  }
837
- return initApp(dir, opts);
838
925
  }
839
- async function initApp(dir, opts) {
840
- const yes = !!opts?.yes;
841
- const dirArgName = dir ? path3.basename(path3.resolve(dir)) : void 0;
842
- const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
843
- const slug = slugify(name);
844
- const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
845
- let template;
846
- if (opts?.template) {
847
- template = opts.template === "crud" ? "crud" : "blank";
848
- } else if (yes) {
849
- template = "blank";
850
- } else {
851
- console.log();
852
- console.log(" Templates:");
853
- console.log(" 1) blank \u2014 Empty app with a single API route and page");
854
- console.log(" 2) crud \u2014 CRUD app with database, list, and form");
855
- console.log();
856
- const templateChoice = await ask2("Template [1]: ") || "1";
857
- template = templateChoice === "2" ? "crud" : "blank";
926
+ function formatClaudeSkill(skill) {
927
+ return `${versionHeader(skill.name)}
928
+ ---
929
+ name: ${skill.name}
930
+ description: ${JSON.stringify(skill.description)}
931
+ ---
932
+
933
+ ${skill.content}`;
934
+ }
935
+ function formatCodexSkill(skill) {
936
+ return formatClaudeSkill(skill);
937
+ }
938
+ function writeSkillDir(skill, cwd, targetDir, format) {
939
+ const skillDir = join2(cwd, targetDir, skill.name);
940
+ const filePath = join2(skillDir, "SKILL.md");
941
+ const existing = readExistingVersion(filePath);
942
+ if (existing === CLI_VERSION) {
943
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
858
944
  }
859
- if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
860
- console.error(`Directory ${targetDir} is not empty.`);
861
- process.exit(1);
945
+ mkdirSync(skillDir, { recursive: true });
946
+ writeFileSync(filePath, format(skill));
947
+ return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
948
+ }
949
+ function writeOpenclawSkill(skill, cwd, targetDir) {
950
+ const skillDir = join2(cwd, targetDir, skill.name);
951
+ const mdPath = join2(skillDir, "SKILL.md");
952
+ const jsonPath = join2(skillDir, "skill.json");
953
+ const existing = readExistingVersion(mdPath);
954
+ if (existing === CLI_VERSION) {
955
+ return { status: "skipped", path: mdPath, reason: `already at v${CLI_VERSION}` };
862
956
  }
863
- fs3.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
864
- fs3.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
865
- let storage;
866
- if (opts?.storage !== void 0) {
867
- storage = opts.storage;
868
- } else if (yes) {
869
- storage = false;
870
- } else {
871
- const storageChoice = await ask2("Enable file uploads? [y/N]: ") || "n";
872
- storage = storageChoice.toLowerCase() === "y";
957
+ mkdirSync(skillDir, { recursive: true });
958
+ writeFileSync(mdPath, `${versionHeader(skill.name)}
959
+ ${skill.content}`);
960
+ writeFileSync(
961
+ jsonPath,
962
+ JSON.stringify(
963
+ {
964
+ name: skill.name,
965
+ displayName: skill.name.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join(" "),
966
+ description: skill.description,
967
+ trigger: "manual",
968
+ inputs: []
969
+ },
970
+ null,
971
+ 2
972
+ )
973
+ );
974
+ return existing ? { status: "updated", path: mdPath, previousVersion: existing } : { status: "installed", path: mdPath };
975
+ }
976
+ function writeCursorRule(skill, cwd, targetDir) {
977
+ const dir = join2(cwd, targetDir);
978
+ const filePath = join2(dir, `${skill.name}.mdc`);
979
+ const existing = readExistingVersion(filePath);
980
+ if (existing === CLI_VERSION) {
981
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
873
982
  }
874
- write(targetDir, "clawnify.json", JSON.stringify({
875
- $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
876
- version: 1,
877
- name,
878
- description: "",
879
- app: { framework: "react+hono", database: true, storage }
880
- }, null, 2));
881
- const devDeps = {
882
- "@cloudflare/workers-types": "^4.0.0",
883
- "@tailwindcss/vite": "^4.0.0",
884
- "@types/react": "^19.0.0",
885
- "@types/react-dom": "^19.0.0",
886
- "@vitejs/plugin-react": "^4.0.0",
887
- clawnify: "^0.3.0",
888
- "drizzle-kit": "^0.31.0",
889
- tailwindcss: "^4.0.0",
890
- vite: "^6.0.0",
891
- wrangler: "^4.0.0"
892
- };
893
- write(targetDir, "package.json", JSON.stringify({
894
- name: slug,
895
- private: true,
896
- type: "module",
897
- scripts: {
898
- dev: "clawnify dev",
899
- build: "vite build",
900
- deploy: "clawnify deploy"
901
- },
902
- dependencies: {
903
- "@clawnify/db": "^0.4.1",
904
- "@hono/zod-openapi": "^0.19.0",
905
- hono: "^4.0.0",
906
- react: "^19.0.0",
907
- "react-dom": "^19.0.0",
908
- zod: "^3.0.0"
909
- },
910
- devDependencies: devDeps,
983
+ mkdirSync(dir, { recursive: true });
984
+ const body = `${versionHeader(skill.name)}
985
+ ---
986
+ description: ${JSON.stringify(skill.description)}
987
+ alwaysApply: false
988
+ ---
989
+
990
+ ${skill.content}`;
991
+ writeFileSync(filePath, body);
992
+ return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
993
+ }
994
+ function writeAiderSection(skill, cwd, targetFile) {
995
+ const filePath = join2(cwd, targetFile);
996
+ const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;
997
+ const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;
998
+ const section = `${startMarker}
999
+ ${versionHeader(skill.name)}
1000
+ ${skill.content}
1001
+ ${endMarker}
1002
+ `;
1003
+ let existing = "";
1004
+ let existingVersion = null;
1005
+ if (existsSync2(filePath)) {
1006
+ existing = readFileSync(filePath, "utf8");
1007
+ const sectionRe = new RegExp(
1008
+ `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
1009
+ );
1010
+ const sectionMatch = existing.match(sectionRe);
1011
+ if (sectionMatch) {
1012
+ const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);
1013
+ existingVersion = headMatch ? headMatch[2] : null;
1014
+ if (existingVersion === CLI_VERSION) {
1015
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
1016
+ }
1017
+ const next = existing.replace(sectionRe, section);
1018
+ mkdirSync(dirname(filePath), { recursive: true });
1019
+ writeFileSync(filePath, next);
1020
+ return existingVersion ? { status: "updated", path: filePath, previousVersion: existingVersion } : { status: "installed", path: filePath };
1021
+ }
1022
+ }
1023
+ mkdirSync(dirname(filePath), { recursive: true });
1024
+ const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
1025
+ writeFileSync(filePath, existing + prefix + section);
1026
+ return { status: "installed", path: filePath };
1027
+ }
1028
+ function escapeRe(s) {
1029
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1030
+ }
1031
+ function removeSkill(skillName, agent, cwd) {
1032
+ if (agent.agent === "aider") {
1033
+ const filePath = join2(cwd, agent.target);
1034
+ if (!existsSync2(filePath)) return false;
1035
+ const content = readFileSync(filePath, "utf8");
1036
+ const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;
1037
+ const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;
1038
+ const sectionRe = new RegExp(
1039
+ `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
1040
+ );
1041
+ if (!sectionRe.test(content)) return false;
1042
+ writeFileSync(filePath, content.replace(sectionRe, ""));
1043
+ return true;
1044
+ }
1045
+ if (agent.agent === "cursor") {
1046
+ const candidate = join2(cwd, agent.target, `${skillName}.mdc`);
1047
+ if (!existsSync2(candidate)) return false;
1048
+ unlinkSync(candidate);
1049
+ return true;
1050
+ }
1051
+ const dir = join2(cwd, agent.target, skillName);
1052
+ if (!existsSync2(dir)) return false;
1053
+ try {
1054
+ const s = statSync2(dir);
1055
+ if (!s.isDirectory()) return false;
1056
+ } catch {
1057
+ return false;
1058
+ }
1059
+ rmSync(dir, { recursive: true, force: true });
1060
+ return true;
1061
+ }
1062
+
1063
+ // src/lib/ai-files/rules.ts
1064
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
1065
+ import { dirname as dirname2, join as join3 } from "path";
1066
+ var RULES_FILE = {
1067
+ claude: "CLAUDE.md",
1068
+ cursor: ".cursorrules",
1069
+ openclaw: "AGENTS.md",
1070
+ codex: "AGENTS.md",
1071
+ aider: "CONVENTIONS.md"
1072
+ };
1073
+ var START = "<!-- clawnify:rules:start -->";
1074
+ var END = "<!-- clawnify:rules:end -->";
1075
+ var VERSION_RE = /<!--\s*clawnify:rules\s+v([\d.]+)\s*-->/;
1076
+ function block() {
1077
+ return `${START}
1078
+ <!-- clawnify:rules v${CLI_VERSION} -->
1079
+ ${RULES_CONTENT.trimEnd()}
1080
+ ${END}
1081
+ `;
1082
+ }
1083
+ function writeRules(cwd, file) {
1084
+ const filePath = join3(cwd, file);
1085
+ const section = block();
1086
+ const sectionRe = new RegExp(`${escapeRe2(START)}[\\s\\S]*?${escapeRe2(END)}\\n?`);
1087
+ if (existsSync3(filePath)) {
1088
+ const existing = readFileSync2(filePath, "utf8");
1089
+ const match = existing.match(sectionRe);
1090
+ if (match) {
1091
+ const versionMatch = match[0].match(VERSION_RE);
1092
+ const previousVersion = versionMatch ? versionMatch[1] : null;
1093
+ if (previousVersion === CLI_VERSION) {
1094
+ return { status: "skipped", file: filePath, reason: `already at v${CLI_VERSION}` };
1095
+ }
1096
+ writeFileSync2(filePath, existing.replace(sectionRe, section));
1097
+ return previousVersion ? { status: "updated", file: filePath, previousVersion } : { status: "installed", file: filePath };
1098
+ }
1099
+ const prefix = existing.endsWith("\n") ? "\n" : "\n\n";
1100
+ writeFileSync2(filePath, existing + prefix + section);
1101
+ return { status: "installed", file: filePath };
1102
+ }
1103
+ mkdirSync2(dirname2(filePath), { recursive: true });
1104
+ writeFileSync2(filePath, section);
1105
+ return { status: "installed", file: filePath };
1106
+ }
1107
+ function removeRules(cwd, file) {
1108
+ const filePath = join3(cwd, file);
1109
+ if (!existsSync3(filePath)) return false;
1110
+ const existing = readFileSync2(filePath, "utf8");
1111
+ const sectionRe = new RegExp(`\\n?${escapeRe2(START)}[\\s\\S]*?${escapeRe2(END)}\\n?`);
1112
+ if (!sectionRe.test(existing)) return false;
1113
+ const next = existing.replace(sectionRe, "\n").replace(/^\n+/, "").trimEnd();
1114
+ if (next) {
1115
+ writeFileSync2(filePath, next + "\n");
1116
+ } else {
1117
+ unlinkSync2(filePath);
1118
+ }
1119
+ return true;
1120
+ }
1121
+ function escapeRe2(s) {
1122
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1123
+ }
1124
+
1125
+ // src/lib/ai-files/mcp.ts
1126
+ import { existsSync as existsSync4, readFileSync as readFileSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "fs";
1127
+ import { join as join4 } from "path";
1128
+ var FILE = ".mcp.json";
1129
+ var SERVER = {
1130
+ command: "npx",
1131
+ args: ["clawnify", "--mcp"]
1132
+ };
1133
+ function writeMcpConfig(cwd) {
1134
+ const filePath = join4(cwd, FILE);
1135
+ let config = {};
1136
+ let existed = false;
1137
+ if (existsSync4(filePath)) {
1138
+ existed = true;
1139
+ try {
1140
+ config = JSON.parse(readFileSync3(filePath, "utf8"));
1141
+ } catch {
1142
+ return { status: "skipped", file: filePath, reason: "existing .mcp.json is not valid JSON" };
1143
+ }
1144
+ }
1145
+ config.mcpServers ??= {};
1146
+ const current = config.mcpServers["clawnify"];
1147
+ if (current && JSON.stringify(current) === JSON.stringify(SERVER)) {
1148
+ return { status: "skipped", file: filePath, reason: "already configured" };
1149
+ }
1150
+ const wasPresent = current !== void 0;
1151
+ config.mcpServers["clawnify"] = SERVER;
1152
+ writeFileSync3(filePath, JSON.stringify(config, null, 2) + "\n");
1153
+ return existed && wasPresent ? { status: "updated", file: filePath } : { status: "installed", file: filePath };
1154
+ }
1155
+ function removeMcpConfig(cwd) {
1156
+ const filePath = join4(cwd, FILE);
1157
+ if (!existsSync4(filePath)) return false;
1158
+ let config;
1159
+ try {
1160
+ config = JSON.parse(readFileSync3(filePath, "utf8"));
1161
+ } catch {
1162
+ return false;
1163
+ }
1164
+ if (!config.mcpServers || !("clawnify" in config.mcpServers)) return false;
1165
+ delete config.mcpServers["clawnify"];
1166
+ if (Object.keys(config.mcpServers).length === 0) delete config.mcpServers;
1167
+ if (Object.keys(config).length === 0) {
1168
+ unlinkSync3(filePath);
1169
+ } else {
1170
+ writeFileSync3(filePath, JSON.stringify(config, null, 2) + "\n");
1171
+ }
1172
+ return true;
1173
+ }
1174
+
1175
+ // src/commands/ai-files.ts
1176
+ function resolveAgents(cwd, forced) {
1177
+ if (forced) {
1178
+ if (!ALL_AGENTS.includes(forced)) {
1179
+ console.error(`Unknown agent: ${forced}
1180
+ Valid: ${ALL_AGENTS.join(", ")}`);
1181
+ process.exit(1);
1182
+ }
1183
+ return { agents: [agentByName(forced)], defaulted: false };
1184
+ }
1185
+ const detected = detectAgents(cwd);
1186
+ if (detected.length > 0) return { agents: detected, defaulted: false };
1187
+ return { agents: [agentByName("claude")], defaulted: true };
1188
+ }
1189
+ function installAiFiles(cwd, agents, opts) {
1190
+ const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];
1191
+ let rules = 0;
1192
+ for (const file of rulesFiles) {
1193
+ const r = writeRules(cwd, file);
1194
+ if (r.status === "skipped") {
1195
+ console.log(` \xB7 rules \u2192 ${r.file} (${r.reason})`);
1196
+ } else if (r.status === "updated") {
1197
+ console.log(` \u2191 rules \u2192 ${r.file} (v${r.previousVersion} \u2192 v${CLI_VERSION})`);
1198
+ rules++;
1199
+ } else {
1200
+ console.log(` \u2713 rules \u2192 ${r.file}`);
1201
+ rules++;
1202
+ }
1203
+ }
1204
+ let skills = 0;
1205
+ for (const skill of BUNDLED_SKILLS) {
1206
+ for (const agent of agents) {
1207
+ const s = installSkill(skill, agent, cwd);
1208
+ if (s.status === "skipped") {
1209
+ console.log(` \xB7 skill ${skill.name} \u2192 ${s.path} (${s.reason})`);
1210
+ } else if (s.status === "updated") {
1211
+ console.log(` \u2191 skill ${skill.name} \u2192 ${s.path} (v${s.previousVersion} \u2192 v${CLI_VERSION})`);
1212
+ skills++;
1213
+ } else {
1214
+ console.log(` \u2713 skill ${skill.name} \u2192 ${s.path}`);
1215
+ skills++;
1216
+ }
1217
+ }
1218
+ }
1219
+ let mcp = false;
1220
+ if (opts.mcp) {
1221
+ const m = writeMcpConfig(cwd);
1222
+ if (m.status === "skipped") {
1223
+ console.log(` \xB7 mcp \u2192 ${m.file} (${m.reason})`);
1224
+ } else {
1225
+ console.log(` ${m.status === "updated" ? "\u2191" : "\u2713"} mcp \u2192 ${m.file}`);
1226
+ mcp = true;
1227
+ }
1228
+ }
1229
+ return { rules, skills, mcp };
1230
+ }
1231
+ async function aiFilesInstallCommand(opts) {
1232
+ const cwd = process.cwd();
1233
+ const { agents, defaulted } = resolveAgents(cwd, opts.agent);
1234
+ console.log(`Installing Clawnify AI files (CLI v${CLI_VERSION}):`);
1235
+ if (defaulted) {
1236
+ console.log(" No coding agent detected \u2014 defaulting to Claude (CLAUDE.md).");
1237
+ }
1238
+ console.log(` Agents: ${agents.map((a) => a.agent).join(", ")}
1239
+ `);
1240
+ installAiFiles(cwd, agents, { mcp: opts.mcp !== false });
1241
+ console.log("\nDone. Your project is agent-ready.");
1242
+ console.log("Tip: leave `clawnify dev` running so generated types stay fresh.");
1243
+ }
1244
+ async function aiFilesUninstallCommand(opts) {
1245
+ const cwd = process.cwd();
1246
+ const agents = opts.agent ? resolveAgents(cwd, opts.agent).agents : detectAgents(cwd);
1247
+ let removed = 0;
1248
+ const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];
1249
+ for (const file of rulesFiles) {
1250
+ if (removeRules(cwd, file)) {
1251
+ console.log(` \u2717 rules removed from ${file}`);
1252
+ removed++;
1253
+ }
1254
+ }
1255
+ for (const skill of BUNDLED_SKILLS) {
1256
+ for (const agent of agents) {
1257
+ if (removeSkill(skill.name, agent, cwd)) {
1258
+ console.log(` \u2717 skill ${skill.name} removed from ${agent.agent}`);
1259
+ removed++;
1260
+ }
1261
+ }
1262
+ }
1263
+ if (removeMcpConfig(cwd)) {
1264
+ console.log(" \u2717 clawnify server removed from .mcp.json");
1265
+ removed++;
1266
+ }
1267
+ console.log(`
1268
+ Done \u2014 removed ${removed} item${removed === 1 ? "" : "s"}.`);
1269
+ }
1270
+
1271
+ // src/commands/init.ts
1272
+ function ask2(question) {
1273
+ const rl = readline4.createInterface({
1274
+ input: process.stdin,
1275
+ output: process.stdout
1276
+ });
1277
+ return new Promise((resolve) => {
1278
+ rl.question(question, (answer) => {
1279
+ rl.close();
1280
+ resolve(answer.trim());
1281
+ });
1282
+ });
1283
+ }
1284
+ function slugify(name) {
1285
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
1286
+ }
1287
+ async function askProjectType(opts) {
1288
+ if (opts?.type === "app" || opts?.type === "website") return opts.type;
1289
+ if (opts?.type) {
1290
+ console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);
1291
+ process.exit(1);
1292
+ }
1293
+ if (opts?.yes) return "app";
1294
+ console.log();
1295
+ console.log(" What are you creating?");
1296
+ console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
1297
+ console.log(" 2) website \u2014 public site (Astro)");
1298
+ console.log();
1299
+ const choice = await ask2("Type [1]: ") || "1";
1300
+ return choice === "2" ? "website" : "app";
1301
+ }
1302
+ function detectPackageManager() {
1303
+ const ua = process.env.npm_config_user_agent ?? "";
1304
+ if (ua.startsWith("pnpm")) return "pnpm";
1305
+ if (ua.startsWith("yarn")) return "yarn";
1306
+ if (ua.startsWith("bun")) return "bun";
1307
+ return "npm";
1308
+ }
1309
+ async function initCommand(dir, opts) {
1310
+ const type = await askProjectType(opts);
1311
+ if (type === "website") {
1312
+ return initWebsite(dir, opts);
1313
+ }
1314
+ return initApp(dir, opts);
1315
+ }
1316
+ async function initApp(dir, opts) {
1317
+ const yes = !!opts?.yes;
1318
+ const dirArgName = dir ? path3.basename(path3.resolve(dir)) : void 0;
1319
+ const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
1320
+ const slug = slugify(name);
1321
+ let targetDir;
1322
+ if (dir) {
1323
+ targetDir = path3.resolve(dir);
1324
+ } else {
1325
+ const ws = findWorkspaceRoot(process.cwd());
1326
+ targetDir = ws ? path3.join(ws.dir, "apps", slug) : path3.resolve(slug);
1327
+ }
1328
+ let template;
1329
+ if (opts?.template) {
1330
+ template = opts.template === "crud" ? "crud" : "blank";
1331
+ } else if (yes) {
1332
+ template = "blank";
1333
+ } else {
1334
+ console.log();
1335
+ console.log(" Templates:");
1336
+ console.log(" 1) blank \u2014 Empty app with a single API route and page");
1337
+ console.log(" 2) crud \u2014 CRUD app with database, list, and form");
1338
+ console.log();
1339
+ const templateChoice = await ask2("Template [1]: ") || "1";
1340
+ template = templateChoice === "2" ? "crud" : "blank";
1341
+ }
1342
+ if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
1343
+ console.error(`Directory ${targetDir} is not empty.`);
1344
+ process.exit(1);
1345
+ }
1346
+ fs3.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
1347
+ fs3.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
1348
+ let storage;
1349
+ if (opts?.storage !== void 0) {
1350
+ storage = opts.storage;
1351
+ } else if (yes) {
1352
+ storage = false;
1353
+ } else {
1354
+ const storageChoice = await ask2("Enable file uploads? [y/N]: ") || "n";
1355
+ storage = storageChoice.toLowerCase() === "y";
1356
+ }
1357
+ write(targetDir, "clawnify.json", JSON.stringify({
1358
+ $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
1359
+ version: 1,
1360
+ name,
1361
+ description: "",
1362
+ app: { framework: "react+hono", database: true, storage }
1363
+ }, null, 2));
1364
+ const devDeps = {
1365
+ "@cloudflare/workers-types": "^4.0.0",
1366
+ "@tailwindcss/vite": "^4.0.0",
1367
+ "@types/react": "^19.0.0",
1368
+ "@types/react-dom": "^19.0.0",
1369
+ "@vitejs/plugin-react": "^4.0.0",
1370
+ clawnify: "^0.3.0",
1371
+ "drizzle-kit": "^0.31.0",
1372
+ tailwindcss: "^4.0.0",
1373
+ vite: "^6.0.0",
1374
+ wrangler: "^4.0.0"
1375
+ };
1376
+ write(targetDir, "package.json", JSON.stringify({
1377
+ name: slug,
1378
+ private: true,
1379
+ type: "module",
1380
+ scripts: {
1381
+ dev: "clawnify dev",
1382
+ build: "vite build",
1383
+ deploy: "clawnify deploy"
1384
+ },
1385
+ dependencies: {
1386
+ "@clawnify/db": "^0.4.1",
1387
+ "@hono/zod-openapi": "^0.19.0",
1388
+ hono: "^4.0.0",
1389
+ react: "^19.0.0",
1390
+ "react-dom": "^19.0.0",
1391
+ zod: "^3.0.0"
1392
+ },
1393
+ devDependencies: devDeps,
911
1394
  engines: { node: ">=22" },
912
1395
  pnpm: { onlyBuiltDependencies: ["esbuild"] }
913
1396
  }, null, 2));
@@ -980,7 +1463,7 @@ data.db-shm
980
1463
  *
981
1464
  * Multi-tenancy reminder: every user-facing table should carry an
982
1465
  * \`org_id\` column and every query should filter by the X-Clawnify-Org-Id
983
- * header. See docs/build-a-clawnify-app.md.
1466
+ * header. See docs/internal/build-a-clawnify-app.md.
984
1467
  */
985
1468
  export const items = sqliteTable("items", {
986
1469
  id: integer("id").primaryKey({ autoIncrement: true }),
@@ -1096,6 +1579,13 @@ createRoot(document.getElementById("app")!).render(
1096
1579
  } else {
1097
1580
  writeBlankTemplate(targetDir, name);
1098
1581
  }
1582
+ if (opts?.aiFiles !== false) {
1583
+ const detected = detectAgents(targetDir);
1584
+ const agents = detected.length > 0 ? detected : [agentByName("claude")];
1585
+ console.log();
1586
+ console.log(" Installing AI files (rules + skills + MCP):");
1587
+ installAiFiles(targetDir, agents, { mcp: true });
1588
+ }
1099
1589
  const pm = detectPackageManager();
1100
1590
  console.log();
1101
1591
  console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
@@ -1110,10 +1600,21 @@ createRoot(document.getElementById("app")!).render(
1110
1600
  async function initWebsite(dir, opts) {
1111
1601
  const name = opts?.name || await ask2("Site name: ") || "my-site";
1112
1602
  const slug = slugify(name);
1113
- const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
1114
- if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
1115
- console.error(`Directory ${targetDir} is not empty.`);
1116
- process.exit(1);
1603
+ let targetDir;
1604
+ if (dir) {
1605
+ targetDir = path3.resolve(dir);
1606
+ } else {
1607
+ const ws = findWorkspaceRoot(process.cwd());
1608
+ targetDir = ws ? path3.join(ws.dir, "website") : path3.resolve(slug);
1609
+ }
1610
+ if (fs3.existsSync(targetDir)) {
1611
+ const entries = fs3.readdirSync(targetDir);
1612
+ const onlyGitkeep = entries.length === 1 && entries[0] === ".gitkeep";
1613
+ if (entries.length > 0 && !onlyGitkeep) {
1614
+ console.error(`Directory ${targetDir} is not empty.`);
1615
+ process.exit(1);
1616
+ }
1617
+ if (onlyGitkeep) fs3.rmSync(path3.join(targetDir, ".gitkeep"));
1117
1618
  }
1118
1619
  fs3.mkdirSync(targetDir, { recursive: true });
1119
1620
  write(targetDir, "clawnify.json", JSON.stringify({
@@ -1302,8 +1803,8 @@ export default api;
1302
1803
 
1303
1804
  <p className="mt-8 text-xs text-slate-500">
1304
1805
  Read{" "}
1305
- <a href="https://github.com/clawnify/clawnify/blob/main/docs/build-a-clawnify-app.md" target="_blank" rel="noreferrer" className="underline underline-offset-2">
1306
- docs/build-a-clawnify-app.md
1806
+ <a href="https://github.com/clawnify/clawnify/blob/main/docs/internal/build-a-clawnify-app.md" target="_blank" rel="noreferrer" className="underline underline-offset-2">
1807
+ docs/internal/build-a-clawnify-app.md
1307
1808
  </a>{" "}
1308
1809
  for the full gold-standard guide.
1309
1810
  </p>
@@ -1913,12 +2414,132 @@ async function orgUseCommand(slugOrId) {
1913
2414
  console.error("Not logged in. Run `clawnify login` first.");
1914
2415
  process.exit(1);
1915
2416
  }
1916
- saveAuth({ ...auth, org_id: match.id });
1917
- console.log(` Active org set to ${match.name} (${match.slug})`);
2417
+ saveAuth({ ...auth, org_id: match.id });
2418
+ console.log(` Active org set to ${match.name} (${match.slug})`);
2419
+ }
2420
+
2421
+ // src/commands/workspace.ts
2422
+ import fs5 from "fs";
2423
+ import path7 from "path";
2424
+ function slugify3(name) {
2425
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
2426
+ }
2427
+ async function resolveOrg(opts) {
2428
+ const orgs = await listMyOrgs();
2429
+ if (orgs.length === 0) {
2430
+ console.error("No organizations on your account. Run `clawnify login` first.");
2431
+ process.exit(1);
2432
+ }
2433
+ if (opts?.org) {
2434
+ const match = orgs.find((o) => o.id === opts.org || o.slug === opts.org);
2435
+ if (!match) {
2436
+ console.error(
2437
+ `No org matched "${opts.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
2438
+ );
2439
+ process.exit(1);
2440
+ }
2441
+ return match;
2442
+ }
2443
+ const auth = loadAuth();
2444
+ const active = orgs.find((o) => o.id === auth?.org_id);
2445
+ if (active) return active;
2446
+ if (orgs.length === 1) return orgs[0];
2447
+ console.error(
2448
+ `Multiple orgs \u2014 pick one with \`--org <slug>\` (or set a default: \`clawnify org use <slug>\`).
2449
+ Available: ${orgs.map((o) => o.slug).join(", ")}`
2450
+ );
2451
+ process.exit(1);
2452
+ }
2453
+ function write2(dir, file, content) {
2454
+ const fullPath = path7.join(dir, file);
2455
+ fs5.mkdirSync(path7.dirname(fullPath), { recursive: true });
2456
+ fs5.writeFileSync(fullPath, content);
2457
+ }
2458
+ async function workspaceInitCommand(dir, opts) {
2459
+ const org = await resolveOrg(opts);
2460
+ const name = opts?.name || org.name;
2461
+ const targetDir = dir ? path7.resolve(dir) : path7.resolve(slugify3(org.slug));
2462
+ if (fs5.existsSync(targetDir) && fs5.readdirSync(targetDir).length > 0) {
2463
+ console.error(`Directory ${targetDir} is not empty.`);
2464
+ process.exit(1);
2465
+ }
2466
+ write2(targetDir, "clawnify.json", JSON.stringify({
2467
+ $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
2468
+ version: 1,
2469
+ name,
2470
+ workspace: { org: org.slug }
2471
+ }, null, 2));
2472
+ write2(targetDir, "pnpm-workspace.yaml", `packages:
2473
+ - "apps/*"
2474
+ - "website"
2475
+ `);
2476
+ write2(targetDir, "package.json", JSON.stringify({
2477
+ name: slugify3(org.slug),
2478
+ private: true,
2479
+ type: "module"
2480
+ }, null, 2));
2481
+ write2(targetDir, ".gitignore", `node_modules
2482
+ dist
2483
+ .wrangler
2484
+ .clawnify
2485
+ .env*
2486
+ !.env.example
2487
+ .dev.vars
2488
+ data.db
2489
+ data.db-wal
2490
+ data.db-shm
2491
+ `);
2492
+ write2(targetDir, "README.md", `# ${name}
2493
+
2494
+ Clawnify workspace for the **${org.name}** org (\`${org.slug}\`).
2495
+
2496
+ Layout:
2497
+
2498
+ - \`apps/<name>/\` \u2014 one folder per app; each deploys to this org automatically.
2499
+ - \`website/\` \u2014 the org's single public website (Astro).
2500
+
2501
+ ## Add an app / the website
2502
+
2503
+ \`\`\`bash
2504
+ clawnify init # app \u2192 apps/<name>/ (inherits the org)
2505
+ clawnify init --type website # site \u2192 website/
2506
+ \`\`\`
2507
+
2508
+ ## Deploy
2509
+
2510
+ \`\`\`bash
2511
+ clawnify deploy apps/<name> # one app (or: cd apps/<name> && clawnify deploy)
2512
+ clawnify deploy website # the website
2513
+ \`\`\`
2514
+
2515
+ ## Install dependencies
2516
+
2517
+ \`\`\`bash
2518
+ pnpm install # hoists deps for every app + the website
2519
+ \`\`\`
2520
+
2521
+ ## GitHub sync (optional)
2522
+
2523
+ Push this repo to a single GitHub monorepo, then in the dashboard link each app
2524
+ and the website to its own subdirectory (\`apps/<name>\`, \`website\`). Pushing the
2525
+ repo auto-deploys only the targets whose folder changed; Clawnify mirrors edits
2526
+ back under the same subdirs. See \`docs/internal/adr-company-monorepo.md\` \xA7 "GitHub sync".
2527
+ `);
2528
+ write2(targetDir, "apps/.gitkeep", "");
2529
+ write2(targetDir, "website/.gitkeep", "");
2530
+ const rel = path7.relative(process.cwd(), targetDir) || ".";
2531
+ console.log();
2532
+ console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);
2533
+ console.log();
2534
+ console.log(" Get started:");
2535
+ if (rel !== ".") console.log(` cd ${rel}`);
2536
+ console.log(` clawnify init # add an app under apps/`);
2537
+ console.log(` clawnify deploy apps/<name>`);
2538
+ console.log();
1918
2539
  }
1919
2540
 
1920
2541
  // src/commands/execute.ts
1921
- import fs5 from "fs";
2542
+ import fs6 from "fs";
1922
2543
 
1923
2544
  // src/lib/mcp-client.ts
1924
2545
  var MCP_URL = "https://mcp.clawnify.com/mcp";
@@ -1968,7 +2589,7 @@ async function executeCommand(file, options) {
1968
2589
  code = options.code;
1969
2590
  } else if (file) {
1970
2591
  try {
1971
- code = fs5.readFileSync(file, "utf-8");
2592
+ code = fs6.readFileSync(file, "utf-8");
1972
2593
  } catch (err) {
1973
2594
  process.stderr.write(`Failed to read ${file}: ${String(err)}
1974
2595
  `);
@@ -1984,7 +2605,7 @@ Usage: clawnify execute path/to/file.ts
1984
2605
  process.exit(1);
1985
2606
  }
1986
2607
  const timeout_ms = options.timeout ? Math.max(1e3, parseInt(options.timeout, 10) * 1e3) : 3e4;
1987
- const resp = await callTool("clawnify.execute", { code, timeout_ms });
2608
+ const resp = await callTool("clawnify_execute", { code, timeout_ms });
1988
2609
  if (isError(resp)) {
1989
2610
  process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}
1990
2611
  `);
@@ -2023,8 +2644,8 @@ async function docsCommand(slug, options) {
2023
2644
  process.exit(1);
2024
2645
  }
2025
2646
  const caller = options.caller ?? "external";
2026
- const path7 = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;
2027
- const res = await fetch(DOCS_URL + path7, {
2647
+ const path8 = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;
2648
+ const res = await fetch(DOCS_URL + path8, {
2028
2649
  headers: {
2029
2650
  authorization: "Bearer " + token
2030
2651
  }
@@ -2104,228 +2725,6 @@ async function sdkInstallCommand() {
2104
2725
  process.exit(1);
2105
2726
  }
2106
2727
 
2107
- // src/lib/skills/content.gen.ts
2108
- var CLI_VERSION = "0.5.0";
2109
- var BUNDLED_SKILLS = [
2110
- {
2111
- name: "build-a-clawnify-app",
2112
- description: "Gold-standard structure for building Clawnify apps end-to-end (Hono + React + tRPC + @clawnify/db).",
2113
- content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same\ncontent for humans reading the docs and for agents (Pi, OpenClaw,\nClaude Code) injecting this as instructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare the patterns the platform expects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + tRPC + `@clawnify/db` (Drizzle)\n + Tailwind + shadcn/ui. Nothing else.\n- **Schema lives in `schema.ts`** (Drizzle DSL) \u2014 single source of\n truth. Never write SQL DDL by hand.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **`clawnify.json`** declares framework, env, and public routes.\n Build emits `api.tools[]` from tRPC procedure meta.\n- **No `/mcp` endpoint.** The org\'s MCP gateway projects tools\n from the manifest.\n- **Identity flows via `X-Clawnify-*` headers** injected by the\n platform. Read them, don\'t fake them.\n\n## Stack rationale\n\nOne template, one set of decisions. Full reasoning lives in\n[`docs/template-strategy.md`](./template-strategy.md). Don\'t deviate\nunless the user has explicitly asked.\n\n## File layout\n\n```\nmy-app/\n clawnify.json \u2190 Manifest (validated against /schema/v1/clawnify.json)\n package.json\n tsconfig.json\n vite.config.ts\n tailwind.config.ts\n components.json \u2190 shadcn/ui config\n index.html\n drizzle.config.ts \u2190 Points at src/server/schema.ts\n drizzle/ \u2190 Generated migrations + snapshots (DON\'T hand-edit)\n 0000_init.sql\n meta/\n _journal.json\n 0000_snapshot.json\n src/\n server/\n index.ts \u2190 Hono entry \u2014 mounts the tRPC router\n schema.ts \u2190 Drizzle table definitions \u2014 THE schema\n router.ts \u2190 tRPC router with MCP-tagged procedures\n auth.ts \u2190 Read X-Clawnify-* identity headers\n env.d.ts \u2190 Worker bindings types\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component\n lib/\n trpc.ts \u2190 Typed tRPC client\n components/ \u2190 shadcn/ui + your components\n styles.css\n```\n\n## `schema.ts` \u2014 the only place tables exist\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \u2014 Drizzle\n serializes on write and parses on read.\n- Multi-tenancy: every user-facing table has `org_id`. Every query\n filters by it. No exceptions.\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\n\n## `drizzle.config.ts`\n\n```ts\nimport { defineConfig } from "drizzle-kit";\n\nexport default defineConfig({\n schema: "./src/server/schema.ts",\n out: "./drizzle",\n dialect: "sqlite",\n});\n```\n\nThe build pipeline reads this and runs `drizzle-kit generate` when\nthe schema changes, then applies migrations transactionally.\n\n## `src/server/index.ts` \u2014 Hono entry\n\n```ts\nimport { Hono } from "hono";\nimport { trpcServer } from "@hono/trpc-server";\nimport { appRouter } from "./router";\nimport { createContext } from "./auth";\n\nconst app = new Hono<{ Bindings: Env }>();\n\napp.use("/trpc/*", trpcServer({\n router: appRouter,\n createContext: (opts, c) => createContext(opts, c.env, c.req.raw),\n}));\n\n// SPA fallback \u2014 Vite-built static assets served by the platform\napp.notFound((c) => c.env.ASSETS.fetch(c.req.raw));\n\nexport default app;\n```\n\nThat\'s it. The Worker entry is thin. No MCP mounting, no inline\nroute handlers \u2014 tRPC owns the API surface.\n\n## `src/server/auth.ts` \u2014 identity from headers\n\n```ts\nimport type { Context } from "hono";\n\nexport interface User {\n id: string;\n orgId: string;\n email: string;\n caller: "user" | "agent" | "agent-browser" | "system";\n}\n\nexport function readUser(req: Request): User | null {\n const id = req.headers.get("X-Clawnify-User-Id");\n const orgId = req.headers.get("X-Clawnify-Org-Id");\n const email = req.headers.get("X-Clawnify-User-Email") ?? "";\n const caller = (req.headers.get("X-Clawnify-Caller") ?? "user") as User["caller"];\n if (!id || !orgId) return null;\n return { id, orgId, email, caller };\n}\n\nexport function createContext(_opts: unknown, env: Env, req: Request) {\n const user = readUser(req);\n return { env, user };\n}\n```\n\nTrust these headers \u2014 the platform strips client-supplied versions\nand reinjects authenticated ones at the perimeter. Never read\n`Authorization` or session cookies directly.\n\n## `src/server/router.ts` \u2014 tRPC procedures with MCP meta\n\n```ts\nimport { initTRPC } from "@trpc/server";\nimport { z } from "zod";\nimport { getDB, eq, desc, and } from "@clawnify/db";\nimport * as schema from "./schema";\nimport type { User } from "./auth";\n\nconst t = initTRPC.context<{ env: Env; user: User | null }>().create();\n\nconst authed = t.procedure.use(({ ctx, next }) => {\n if (!ctx.user) throw new Error("UNAUTHORIZED");\n return next({ ctx: { ...ctx, user: ctx.user } });\n});\n\nexport const appRouter = t.router({\n list_notes: authed\n .meta({ mcp: { name: "list_notes", description: "List the user\'s notes." } })\n .input(z.object({ limit: z.number().int().min(1).max(100).default(50) }))\n .output(z.array(z.object({\n id: z.number(),\n title: z.string(),\n body: z.string(),\n tags: z.array(z.string()),\n createdAt: z.string(),\n })))\n .query(async ({ ctx, input }) => {\n const db = getDB(ctx.env, { schema });\n return db\n .select()\n .from(schema.notes)\n .where(eq(schema.notes.orgId, ctx.user.orgId))\n .orderBy(desc(schema.notes.createdAt))\n .limit(input.limit);\n }),\n\n create_note: authed\n .meta({ mcp: { name: "create_note", description: "Create a new note." } })\n .input(z.object({\n title: z.string().min(1),\n body: z.string().default(""),\n tags: z.array(z.string()).default([]),\n }))\n .mutation(async ({ ctx, input }) => {\n const db = getDB(ctx.env, { schema });\n const [row] = await db\n .insert(schema.notes)\n .values({ ...input, orgId: ctx.user.orgId })\n .returning();\n return row;\n }),\n});\n\nexport type AppRouter = typeof appRouter;\n```\n\nPatterns to follow:\n- **Every state-mutating procedure** that an agent might want to\n call gets `.meta({ mcp: { name, description } })`. The build\n picks these up into `clawnify.json api.tools[]`. The Clawnify\n MCP gateway projects them as MCP tools.\n- **Auth via middleware** (`authed`). Never check headers inside\n a procedure body.\n- **Filter by `ctx.user.orgId`** on every query. No exceptions.\n- **Schema-validated input + output** with Zod. The output schema\n is what the agent sees as the tool\'s return shape.\n- **Procedure names are intent verbs** (`archive_old_notes`,\n `publish_post`), not REST resource shapes (`get_notes`,\n `update_note`). Tools describe what the agent wants to do.\n\n## `src/client` \u2014 React + tRPC + shadcn\n\n```tsx\n// src/client/lib/trpc.ts\nimport { createTRPCReact, httpBatchLink } from "@trpc/react-query";\nimport type { AppRouter } from "../../server/router";\n\nexport const trpc = createTRPCReact<AppRouter>();\nexport const trpcClient = trpc.createClient({\n links: [httpBatchLink({ url: "/trpc" })],\n});\n```\n\n```tsx\n// src/client/app.tsx\nimport { useState } from "react";\nimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";\nimport { trpc, trpcClient } from "./lib/trpc";\nimport { Button } from "./components/ui/button";\n\nconst queryClient = new QueryClient();\n\nexport function App() {\n return (\n <trpc.Provider client={trpcClient} queryClient={queryClient}>\n <QueryClientProvider client={queryClient}>\n <NotesList />\n </QueryClientProvider>\n </trpc.Provider>\n );\n}\n\nfunction NotesList() {\n const notes = trpc.list_notes.useQuery({ limit: 50 });\n const create = trpc.create_note.useMutation({\n onSuccess: () => notes.refetch(),\n });\n const [title, setTitle] = useState("");\n\n return (\n <div>\n {notes.data?.map((n) => <div key={n.id}>{n.title}</div>)}\n <Button onClick={() => create.mutate({ title, body: "" })}>\n Add note\n </Button>\n </div>\n );\n}\n```\n\nThe same tRPC procedures power the agent (via MCP) and the UI (via\ntyped client). One backend, two front doors.\n\n## `clawnify.json` \u2014 the manifest\n\n```json\n{\n "$schema": "https://app.clawnify.com/schema/v1/clawnify.json",\n "version": 1,\n "name": "Notes",\n "description": "Take and organize notes. Searchable by tag.",\n "icon": "icon.svg",\n "tags": ["productivity"],\n "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "required": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\nRules:\n- **Don\'t hand-edit `api.tools[]`** \u2014 generated at build from tRPC\n `.meta({ mcp: { ... } })` annotations.\n- **Public routes are the exception**, not the default. Every tRPC\n procedure is private (auth-required) unless you explicitly add a\n matching path to `public_routes`. Use only for webhooks, RSS,\n embedded feeds.\n- **`framework: "react+hono"`** for new apps. Never `preact+hono` or\n `vite-preact` \u2014 those are legacy.\n- **`database: true`** if the app uses a DB. Schema is generated\n from `schema.ts` via drizzle-kit; no `schema.sql` to ship.\n\n## Migrations\n\nYou don\'t write migration SQL by hand. The workflow:\n\n1. Edit `src/server/schema.ts` to reflect the new shape.\n2. Build pipeline runs `drizzle-kit generate` \u2014 emits a new file\n under `drizzle/` and updates the snapshot.\n3. Build applies pending migrations transactionally to D1 and to\n the Facet (preview tier). Tracked in `__clawnify_migrations`.\n\nFor destructive changes (drop column, rename), Drizzle\'s generator\nwill prompt \u2014 agents should default to additive changes and only\ndo destructive ones when the user explicitly asks. Renames are\nrisky 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- Mount `/mcp` manually. The gateway projects tools from the\n manifest \u2014 exception is in `docs/packages.md`.\n- Author `schema.sql` by hand. Use `schema.ts`.\n- Author migration SQL by hand. Let `drizzle-kit generate` do it.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw API has `json()` as a helper.\n- Bind tRPC procedures by REST resource shape (`get_user_by_id`).\n Use intent verbs (`onboard_user`, `archive_old_orders`).\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\n the `X-Clawnify-*` headers via `auth.ts`.\n- Pin `drizzle-orm` in the app\'s `package.json` to a version that\n drifts from `@clawnify/db`\'s peer range. Pin it to the same\n major/minor.\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `sql`, `sqliteTable`, `text`, `integer`,\n etc. are all re-exported there). Drop to `drizzle-orm` directly\n only for things not re-exported.\n- Add `.meta({ mcp: { name, description } })` to every state-\n mutating procedure that the user\'s agent might want to call.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the Facet preview tier catches schema drift and\n type errors at build time.\n- When unsure about a Drizzle pattern, check\n [`packages/db/README.md`](../packages/db/README.md) for the\n 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` \u2014 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## See also\n\n- [`docs/template-strategy.md`](./template-strategy.md) \u2014 why this\n stack\n- [`docs/packages.md`](./packages.md) \u2014 what `@clawnify/db`\n exposes; planned package surface\n- [`docs/clawnify-mcp-gateway.md`](./clawnify-mcp-gateway.md) \u2014\n how the gateway projects your manifest as MCP tools\n- [`docs/clawnify-apps-migrations.md`](./clawnify-apps-migrations.md)\n \u2014 migration internals\n- [`packages/db/README.md`](../packages/db/README.md) \u2014 full API\n'
2114
- }
2115
- ];
2116
-
2117
- // src/lib/skills/detect.ts
2118
- import { statSync } from "fs";
2119
- import { join } from "path";
2120
- var DETECTORS = [
2121
- { agent: "claude", markers: [".claude", ".claude.json", "CLAUDE.md"], target: ".claude/skills" },
2122
- { agent: "cursor", markers: [".cursor", ".cursorrules"], target: ".cursor/rules" },
2123
- { agent: "openclaw", markers: [".openclaw", "openclaw.json"], target: ".openclaw/skills" },
2124
- { agent: "codex", markers: [".codex", "AGENTS.md"], target: ".codex/skills" },
2125
- { agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
2126
- ];
2127
- function exists(cwd, name) {
2128
- const path7 = join(cwd, name);
2129
- try {
2130
- statSync(path7);
2131
- return true;
2132
- } catch {
2133
- return false;
2134
- }
2135
- }
2136
- function detectAgents(cwd) {
2137
- const found = [];
2138
- for (const d of DETECTORS) {
2139
- const hit = d.markers.find((m) => exists(cwd, m));
2140
- if (hit) {
2141
- found.push({ agent: d.agent, target: d.target, marker: hit });
2142
- }
2143
- }
2144
- return found;
2145
- }
2146
- function agentByName(name) {
2147
- const d = DETECTORS.find((x) => x.agent === name);
2148
- if (!d) throw new Error(`Unknown agent: ${name}`);
2149
- return { agent: d.agent, target: d.target, marker: "(forced)" };
2150
- }
2151
- var ALL_AGENTS = DETECTORS.map((d) => d.agent);
2152
-
2153
- // src/lib/skills/install.ts
2154
- import {
2155
- existsSync as existsSync2,
2156
- mkdirSync,
2157
- readFileSync,
2158
- writeFileSync,
2159
- statSync as statSync2,
2160
- rmSync,
2161
- unlinkSync
2162
- } from "fs";
2163
- import { dirname, join as join2 } from "path";
2164
- var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
2165
- function versionHeader(name) {
2166
- return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
2167
- }
2168
- function readExistingVersion(path7) {
2169
- if (!existsSync2(path7)) return null;
2170
- try {
2171
- const head = readFileSync(path7, "utf8").slice(0, 500);
2172
- const match = head.match(VERSION_HEADER_RE);
2173
- return match ? match[2] : null;
2174
- } catch {
2175
- return null;
2176
- }
2177
- }
2178
- function installSkill(skill, agent, cwd) {
2179
- switch (agent.agent) {
2180
- case "claude":
2181
- return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);
2182
- case "codex":
2183
- return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);
2184
- case "openclaw":
2185
- return writeOpenclawSkill(skill, cwd, agent.target);
2186
- case "cursor":
2187
- return writeCursorRule(skill, cwd, agent.target);
2188
- case "aider":
2189
- return writeAiderSection(skill, cwd, agent.target);
2190
- }
2191
- }
2192
- function formatClaudeSkill(skill) {
2193
- return `${versionHeader(skill.name)}
2194
- ---
2195
- name: ${skill.name}
2196
- description: ${JSON.stringify(skill.description)}
2197
- ---
2198
-
2199
- ${skill.content}`;
2200
- }
2201
- function formatCodexSkill(skill) {
2202
- return formatClaudeSkill(skill);
2203
- }
2204
- function writeSkillDir(skill, cwd, targetDir, format) {
2205
- const skillDir = join2(cwd, targetDir, skill.name);
2206
- const filePath = join2(skillDir, "SKILL.md");
2207
- const existing = readExistingVersion(filePath);
2208
- if (existing === CLI_VERSION) {
2209
- return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
2210
- }
2211
- mkdirSync(skillDir, { recursive: true });
2212
- writeFileSync(filePath, format(skill));
2213
- return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
2214
- }
2215
- function writeOpenclawSkill(skill, cwd, targetDir) {
2216
- const skillDir = join2(cwd, targetDir, skill.name);
2217
- const mdPath = join2(skillDir, "SKILL.md");
2218
- const jsonPath = join2(skillDir, "skill.json");
2219
- const existing = readExistingVersion(mdPath);
2220
- if (existing === CLI_VERSION) {
2221
- return { status: "skipped", path: mdPath, reason: `already at v${CLI_VERSION}` };
2222
- }
2223
- mkdirSync(skillDir, { recursive: true });
2224
- writeFileSync(mdPath, `${versionHeader(skill.name)}
2225
- ${skill.content}`);
2226
- writeFileSync(
2227
- jsonPath,
2228
- JSON.stringify(
2229
- {
2230
- name: skill.name,
2231
- displayName: skill.name.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join(" "),
2232
- description: skill.description,
2233
- trigger: "manual",
2234
- inputs: []
2235
- },
2236
- null,
2237
- 2
2238
- )
2239
- );
2240
- return existing ? { status: "updated", path: mdPath, previousVersion: existing } : { status: "installed", path: mdPath };
2241
- }
2242
- function writeCursorRule(skill, cwd, targetDir) {
2243
- const dir = join2(cwd, targetDir);
2244
- const filePath = join2(dir, `${skill.name}.mdc`);
2245
- const existing = readExistingVersion(filePath);
2246
- if (existing === CLI_VERSION) {
2247
- return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
2248
- }
2249
- mkdirSync(dir, { recursive: true });
2250
- const body = `${versionHeader(skill.name)}
2251
- ---
2252
- description: ${JSON.stringify(skill.description)}
2253
- alwaysApply: false
2254
- ---
2255
-
2256
- ${skill.content}`;
2257
- writeFileSync(filePath, body);
2258
- return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
2259
- }
2260
- function writeAiderSection(skill, cwd, targetFile) {
2261
- const filePath = join2(cwd, targetFile);
2262
- const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;
2263
- const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;
2264
- const section = `${startMarker}
2265
- ${versionHeader(skill.name)}
2266
- ${skill.content}
2267
- ${endMarker}
2268
- `;
2269
- let existing = "";
2270
- let existingVersion = null;
2271
- if (existsSync2(filePath)) {
2272
- existing = readFileSync(filePath, "utf8");
2273
- const sectionRe = new RegExp(
2274
- `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
2275
- );
2276
- const sectionMatch = existing.match(sectionRe);
2277
- if (sectionMatch) {
2278
- const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);
2279
- existingVersion = headMatch ? headMatch[2] : null;
2280
- if (existingVersion === CLI_VERSION) {
2281
- return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
2282
- }
2283
- const next = existing.replace(sectionRe, section);
2284
- mkdirSync(dirname(filePath), { recursive: true });
2285
- writeFileSync(filePath, next);
2286
- return existingVersion ? { status: "updated", path: filePath, previousVersion: existingVersion } : { status: "installed", path: filePath };
2287
- }
2288
- }
2289
- mkdirSync(dirname(filePath), { recursive: true });
2290
- const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
2291
- writeFileSync(filePath, existing + prefix + section);
2292
- return { status: "installed", path: filePath };
2293
- }
2294
- function escapeRe(s) {
2295
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2296
- }
2297
- function removeSkill(skillName, agent, cwd) {
2298
- if (agent.agent === "aider") {
2299
- const filePath = join2(cwd, agent.target);
2300
- if (!existsSync2(filePath)) return false;
2301
- const content = readFileSync(filePath, "utf8");
2302
- const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;
2303
- const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;
2304
- const sectionRe = new RegExp(
2305
- `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
2306
- );
2307
- if (!sectionRe.test(content)) return false;
2308
- writeFileSync(filePath, content.replace(sectionRe, ""));
2309
- return true;
2310
- }
2311
- if (agent.agent === "cursor") {
2312
- const candidate = join2(cwd, agent.target, `${skillName}.mdc`);
2313
- if (!existsSync2(candidate)) return false;
2314
- unlinkSync(candidate);
2315
- return true;
2316
- }
2317
- const dir = join2(cwd, agent.target, skillName);
2318
- if (!existsSync2(dir)) return false;
2319
- try {
2320
- const s = statSync2(dir);
2321
- if (!s.isDirectory()) return false;
2322
- } catch {
2323
- return false;
2324
- }
2325
- rmSync(dir, { recursive: true, force: true });
2326
- return true;
2327
- }
2328
-
2329
2728
  // src/commands/skills.ts
2330
2729
  function skillsListCommand() {
2331
2730
  console.log(`Clawnify skills (v${CLI_VERSION}):
@@ -2345,7 +2744,7 @@ async function skillsAddCommand(name, opts) {
2345
2744
  console.error("No skill specified. Pass a name or --all. See `clawnify skills list`.");
2346
2745
  process.exit(1);
2347
2746
  }
2348
- const agents = resolveAgents(opts.agent);
2747
+ const agents = resolveAgents2(opts.agent);
2349
2748
  if (agents.length === 0) {
2350
2749
  console.error(
2351
2750
  "No coding agent detected in this directory. Looked for:\n .claude/ (Claude Code)\n .cursor/ (Cursor)\n .openclaw/ (OpenClaw)\n .codex/ or AGENTS.md (Codex)\n CONVENTIONS.md or .aider.conf.yml (Aider)\n\nForce a target with --agent <claude|cursor|openclaw|codex|aider>."
@@ -2392,7 +2791,7 @@ async function skillsRemoveCommand(name, opts) {
2392
2791
  console.error("No skill specified. Pass a name or --all.");
2393
2792
  process.exit(1);
2394
2793
  }
2395
- const agents = resolveAgents(opts.agent);
2794
+ const agents = resolveAgents2(opts.agent);
2396
2795
  if (agents.length === 0) {
2397
2796
  console.error("No coding agent detected. Nothing to remove.");
2398
2797
  return;
@@ -2423,7 +2822,7 @@ Available: ${BUNDLED_SKILLS.map((s) => s.name).join(", ")}`
2423
2822
  }
2424
2823
  return [match];
2425
2824
  }
2426
- function resolveAgents(forced) {
2825
+ function resolveAgents2(forced) {
2427
2826
  if (forced) {
2428
2827
  if (!ALL_AGENTS.includes(forced)) {
2429
2828
  console.error(
@@ -2438,19 +2837,21 @@ Valid: ${ALL_AGENTS.join(", ")}`
2438
2837
  }
2439
2838
 
2440
2839
  // src/cli.ts
2441
- function runCli() {
2840
+ async function runCli() {
2442
2841
  const program = new Command();
2443
2842
  program.name("clawnify").description("Deploy apps to Clawnify").version("0.1.0");
2444
- program.command("init [dir]").description("Scaffold a new Clawnify project (app or website)").option("--type <type>", "Project type: app or website (skips prompt)").option("--name <name>", "Project name (skips prompt)").option("--template <template>", "App template: blank or crud (apps only)").option("--storage", "Enable file uploads (R2) \u2014 apps only").option("-y, --yes", "Non-interactive: use all defaults (app, blank, no storage)").action(initCommand);
2843
+ program.command("init [dir]").description("Scaffold a new Clawnify project (app or website)").option("--type <type>", "Project type: app or website (skips prompt)").option("--name <name>", "Project name (skips prompt)").option("--template <template>", "App template: blank or crud (apps only)").option("--storage", "Enable file uploads (R2) \u2014 apps only").option("-y, --yes", "Non-interactive: use all defaults (app, blank, no storage)").option("--no-ai-files", "Skip installing AI files (rules + skills + MCP) after scaffolding").action(initCommand);
2445
2844
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
2446
2845
  program.command("login").description("Authenticate with Clawnify").action(loginCommand);
2447
- program.command("deploy [dir]").description("Deploy an app or website to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on slug conflict, update existing app").option("--update-existing", "Non-interactive: on slug conflict, overwrite existing app").option("--create-new", "Non-interactive: on slug conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
2846
+ program.command("deploy [dir]").description("Deploy an app or website to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--path <subdir>", "Subdirectory within the --from repo that holds the app (monorepo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on slug conflict, update existing app").option("--update-existing", "Non-interactive: on slug conflict, overwrite existing app").option("--create-new", "Non-interactive: on slug conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
2448
2847
  program.command("link <app-id-or-slug>").description("Link the current directory to an existing Clawnify app (accepts id or slug)").option("--dir <dir>", "Directory to link (default: cwd)").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(linkCommand);
2449
2848
  const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
2450
2849
  pull.command("schema").description("Fetch the deployed app's current schema.sql snapshot into the local repo").option("--from <app-id-or-slug>", "App to fetch from (required)").option("--out <path>", "Where to write (default: ./schema.sql)").option("--force", "Overwrite a locally-modified or uncommitted schema.sql").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(pullSchemaCommand);
2451
2850
  const org = program.command("org").description("Manage organizations");
2452
2851
  org.command("list").description("List orgs you belong to").action(orgListCommand);
2453
2852
  org.command("use <slug-or-id>").description("Set the active org for global commands (ls, whoami, etc.)").action(orgUseCommand);
2853
+ const workspace = program.command("workspace").description("Manage a monorepo that hosts an org's apps");
2854
+ workspace.command("init [dir]").description("Scaffold a workspace monorepo bound to an org").option("--org <slug-or-id>", "Org to bind the workspace to (defaults to active org)").option("--name <name>", "Workspace display name (defaults to the org name)").action(workspaceInitCommand);
2454
2855
  program.command("ls").description("List deployed apps").action(lsCommand);
2455
2856
  program.command("logs <app-id>").description("Show build logs for an app").action(logsCommand);
2456
2857
  program.command("rm <app-id>").description("Delete an app").action(rmCommand);
@@ -2463,13 +2864,23 @@ function runCli() {
2463
2864
  skills.command("list").description("List available skills").action(skillsListCommand);
2464
2865
  skills.command("add [name]").description("Install a skill into every detected agent (Claude, Cursor, OpenClaw, Codex, Aider)").option("--all", "Install every available skill").option("--agent <agent>", "Force a specific target (claude | cursor | openclaw | codex | aider)").action((name, opts) => skillsAddCommand(name, opts));
2465
2866
  skills.command("remove [name]").description("Remove a previously-installed skill from detected agents").option("--all", "Remove every installed skill").option("--agent <agent>", "Restrict to a specific agent").action((name, opts) => skillsRemoveCommand(name, opts));
2867
+ const aiFiles = program.command("ai-files").description("Install Clawnify rules + skills + MCP into your coding agent(s)");
2868
+ aiFiles.command("install").description("Write rules, install skills, and wire the MCP server (defaults to Claude if no agent is detected)").option("--agent <agent>", "Force a specific target (claude | cursor | openclaw | codex | aider)").option("--no-mcp", "Skip writing .mcp.json").action((opts) => aiFilesInstallCommand(opts));
2869
+ aiFiles.command("uninstall").description("Remove the Clawnify rules block, skills, and MCP server entry").option("--agent <agent>", "Restrict to a specific agent").action((opts) => aiFilesUninstallCommand(opts));
2466
2870
  const sdk = program.command("sdk").description("Inspect and manage the per-org SDK surface");
2467
2871
  sdk.command("inspect <slug>").description("Show the typed-procedure README for an app (external density)").option("--caller <hint>", "Caller density hint: internal | dashboard | external", "external").action(sdkInspectCommand);
2468
2872
  sdk.command("login").description("Authenticate / rotate the OAuth grant (alias of `clawnify login`)").action(sdkLoginCommand);
2469
2873
  sdk.command("install").description("(Deferred) Install @clawnify/sdk locally \u2014 pending Phase 5b").action(sdkInstallCommand);
2470
- program.parse();
2874
+ try {
2875
+ await program.parseAsync();
2876
+ } catch (err) {
2877
+ console.error(err?.message ?? err);
2878
+ process.exitCode = 1;
2879
+ }
2880
+ await new Promise((resolve) => process.stdout.write("", () => resolve()));
2881
+ process.exit(process.exitCode ?? 0);
2471
2882
  }
2472
2883
  export {
2473
2884
  runCli
2474
2885
  };
2475
- //# sourceMappingURL=cli-XYGLEX6Q.js.map
2886
+ //# sourceMappingURL=cli-OQPC6TYM.js.map