clawnify 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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";
@@ -328,7 +330,7 @@ function assertNodeVersion() {
328
330
  process.exit(1);
329
331
  }
330
332
  }
331
- async function resolveOrgId(options, linkedProject) {
333
+ async function resolveOrgId(options, linkedProject, resolvedDir) {
332
334
  if (options.org) {
333
335
  const orgs = await listMyOrgs();
334
336
  const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
@@ -351,8 +353,26 @@ async function resolveOrgId(options, linkedProject) {
351
353
  if (linkedProject?.app_id && linkedProject.org_id) {
352
354
  return linkedProject.org_id;
353
355
  }
356
+ if (resolvedDir) {
357
+ const wsOrg = await workspaceOrgId(resolvedDir);
358
+ if (wsOrg) return wsOrg;
359
+ }
354
360
  return void 0;
355
361
  }
362
+ async function workspaceOrgId(resolvedDir) {
363
+ const ws = findWorkspaceRoot(resolvedDir);
364
+ if (!ws?.org) return void 0;
365
+ const orgs = await listMyOrgs();
366
+ const match = orgs.find((o) => o.id === ws.org || o.slug === ws.org);
367
+ if (!match) {
368
+ console.error(
369
+ `This workspace is bound to org "${ws.org}", but you're not a member of it (or it no longer exists).
370
+ Available: ${orgs.map((o) => o.slug).join(", ")}`
371
+ );
372
+ process.exit(EXIT_USAGE);
373
+ }
374
+ return match.id;
375
+ }
356
376
  async function resolveConflictDecision(options, conflict) {
357
377
  if (options.updateExisting) return "update";
358
378
  if (options.createNew) return "create";
@@ -443,6 +463,8 @@ async function deployWebsite(dir, options) {
443
463
  orgId = match.id;
444
464
  } else if (linkedProject?.website_id && linkedProject.org_id) {
445
465
  orgId = linkedProject.org_id;
466
+ } else {
467
+ orgId = await workspaceOrgId(resolvedDir);
446
468
  }
447
469
  if (options.dryRun) {
448
470
  const sizeKB = (archive.length / 1024).toFixed(1);
@@ -480,15 +502,30 @@ async function deployWebsite(dir, options) {
480
502
  `);
481
503
  process.exit(1);
482
504
  }
483
- console.log(`
484
- \u2713 Deployed! ${result.data.url}
505
+ if (polled.status === "live") {
506
+ console.log(`
507
+ \u2713 Published! ${result.data.url}
485
508
  `);
509
+ } else {
510
+ console.log(
511
+ `
512
+ \u2713 Deployed to draft.
513
+ Review it in the dashboard, then "Publish to live" when ready.
514
+ `
515
+ );
516
+ }
486
517
  }
487
518
  async function deployCommand(dir, options = {}) {
488
519
  assertNodeVersion();
489
520
  if (!options.from) {
490
521
  const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
491
522
  const manifest = readManifest(resolvedDir);
523
+ if (!manifest && readWorkspaceConfig(resolvedDir)) {
524
+ console.error(
525
+ "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"
526
+ );
527
+ process.exit(EXIT_USAGE);
528
+ }
492
529
  if (manifest) {
493
530
  try {
494
531
  const kind = manifestKind(manifest);
@@ -508,15 +545,18 @@ async function deployCommand(dir, options = {}) {
508
545
  let syncTargetDir;
509
546
  if (options.from) {
510
547
  const repo = options.from.replace(/^github:/, "");
548
+ const subdir = options.path?.trim().replace(/^\/+|\/+$/g, "") || void 0;
511
549
  if (options.dryRun) {
512
- console.log(`
513
- Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main)
514
- `);
550
+ console.log(
551
+ `
552
+ Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : ""})
553
+ `
554
+ );
515
555
  return;
516
556
  }
517
- console.log(`Deploying from ${repo}...`);
557
+ console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : ""}...`);
518
558
  const orgId = options.org ? await resolveOrgId(options, null) : void 0;
519
- const res = await api.post("/v1/apps/deploy", { repo, branch: "main" }, { orgId });
559
+ const res = await api.post("/v1/apps/deploy", { repo, branch: "main", subdir }, { orgId });
520
560
  if (!res.ok) {
521
561
  const err = await res.json().catch(() => ({}));
522
562
  console.error(`Deploy failed: ${err.error || res.statusText}`);
@@ -536,7 +576,7 @@ async function deployCommand(dir, options = {}) {
536
576
  const linkedProject = readProject(resolvedDir);
537
577
  await regenerateDrizzleMigrations(resolvedDir);
538
578
  const { archive, files } = createArchive(resolvedDir);
539
- const orgId = await resolveOrgId(options, linkedProject);
579
+ const orgId = await resolveOrgId(options, linkedProject, resolvedDir);
540
580
  if (options.dryRun) {
541
581
  summarizeArchive(archive, files, framework, baseName);
542
582
  if (linkedProject?.app_id) {
@@ -792,123 +832,562 @@ async function whoamiCommand() {
792
832
  import fs3 from "fs";
793
833
  import path3 from "path";
794
834
  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
- });
835
+
836
+ // src/lib/skills/detect.ts
837
+ import { statSync } from "fs";
838
+ import { join } from "path";
839
+ var DETECTORS = [
840
+ { agent: "claude", markers: [".claude", ".claude.json", "CLAUDE.md"], target: ".claude/skills" },
841
+ { agent: "cursor", markers: [".cursor", ".cursorrules"], target: ".cursor/rules" },
842
+ { agent: "openclaw", markers: [".openclaw", "openclaw.json"], target: ".openclaw/skills" },
843
+ { agent: "codex", markers: [".codex", "AGENTS.md"], target: ".codex/skills" },
844
+ { agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
845
+ ];
846
+ function exists(cwd, name) {
847
+ const path8 = join(cwd, name);
848
+ try {
849
+ statSync(path8);
850
+ return true;
851
+ } catch {
852
+ return false;
853
+ }
806
854
  }
807
- function slugify(name) {
808
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
855
+ function detectAgents(cwd) {
856
+ const found = [];
857
+ for (const d of DETECTORS) {
858
+ const hit = d.markers.find((m) => exists(cwd, m));
859
+ if (hit) {
860
+ found.push({ agent: d.agent, target: d.target, marker: hit });
861
+ }
862
+ }
863
+ return found;
809
864
  }
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);
865
+ function agentByName(name) {
866
+ const d = DETECTORS.find((x) => x.agent === name);
867
+ if (!d) throw new Error(`Unknown agent: ${name}`);
868
+ return { agent: d.agent, target: d.target, marker: "(forced)" };
869
+ }
870
+ var ALL_AGENTS = DETECTORS.map((d) => d.agent);
871
+
872
+ // src/lib/skills/content.gen.ts
873
+ var CLI_VERSION = "0.6.0";
874
+ var BUNDLED_SKILLS = [
875
+ {
876
+ name: "build-a-clawnify-app",
877
+ description: "Gold-standard structure for building Clawnify apps end-to-end (Hono + React + tRPC + @clawnify/db).",
878
+ 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/internal/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 \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 \u2014 exception is in `docs/internal/packages.md`.\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\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/internal/template-strategy.md`](./template-strategy.md) \u2014 why this\n stack\n- [`docs/internal/packages.md`](./packages.md) \u2014 what `@clawnify/db`\n exposes; planned package surface\n- [`docs/internal/clawnify-mcp-gateway.md`](./clawnify-mcp-gateway.md) \u2014\n how the gateway projects your manifest as MCP tools\n- [`docs/internal/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'
815
879
  }
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";
880
+ ];
881
+ 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";
882
+
883
+ // src/lib/skills/install.ts
884
+ import {
885
+ existsSync as existsSync2,
886
+ mkdirSync,
887
+ readFileSync,
888
+ writeFileSync,
889
+ statSync as statSync2,
890
+ rmSync,
891
+ unlinkSync
892
+ } from "fs";
893
+ import { dirname, join as join2 } from "path";
894
+ var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
895
+ function versionHeader(name) {
896
+ return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
824
897
  }
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";
898
+ function readExistingVersion(path8) {
899
+ if (!existsSync2(path8)) return null;
900
+ try {
901
+ const head = readFileSync(path8, "utf8").slice(0, 500);
902
+ const match = head.match(VERSION_HEADER_RE);
903
+ return match ? match[2] : null;
904
+ } catch {
905
+ return null;
906
+ }
831
907
  }
832
- async function initCommand(dir, opts) {
833
- const type = await askProjectType(opts);
834
- if (type === "website") {
835
- return initWebsite(dir, opts);
908
+ function installSkill(skill, agent, cwd) {
909
+ switch (agent.agent) {
910
+ case "claude":
911
+ return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);
912
+ case "codex":
913
+ return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);
914
+ case "openclaw":
915
+ return writeOpenclawSkill(skill, cwd, agent.target);
916
+ case "cursor":
917
+ return writeCursorRule(skill, cwd, agent.target);
918
+ case "aider":
919
+ return writeAiderSection(skill, cwd, agent.target);
836
920
  }
837
- return initApp(dir, opts);
838
921
  }
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";
922
+ function formatClaudeSkill(skill) {
923
+ return `${versionHeader(skill.name)}
924
+ ---
925
+ name: ${skill.name}
926
+ description: ${JSON.stringify(skill.description)}
927
+ ---
928
+
929
+ ${skill.content}`;
930
+ }
931
+ function formatCodexSkill(skill) {
932
+ return formatClaudeSkill(skill);
933
+ }
934
+ function writeSkillDir(skill, cwd, targetDir, format) {
935
+ const skillDir = join2(cwd, targetDir, skill.name);
936
+ const filePath = join2(skillDir, "SKILL.md");
937
+ const existing = readExistingVersion(filePath);
938
+ if (existing === CLI_VERSION) {
939
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
858
940
  }
859
- if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
860
- console.error(`Directory ${targetDir} is not empty.`);
861
- process.exit(1);
941
+ mkdirSync(skillDir, { recursive: true });
942
+ writeFileSync(filePath, format(skill));
943
+ return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
944
+ }
945
+ function writeOpenclawSkill(skill, cwd, targetDir) {
946
+ const skillDir = join2(cwd, targetDir, skill.name);
947
+ const mdPath = join2(skillDir, "SKILL.md");
948
+ const jsonPath = join2(skillDir, "skill.json");
949
+ const existing = readExistingVersion(mdPath);
950
+ if (existing === CLI_VERSION) {
951
+ return { status: "skipped", path: mdPath, reason: `already at v${CLI_VERSION}` };
862
952
  }
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";
953
+ mkdirSync(skillDir, { recursive: true });
954
+ writeFileSync(mdPath, `${versionHeader(skill.name)}
955
+ ${skill.content}`);
956
+ writeFileSync(
957
+ jsonPath,
958
+ JSON.stringify(
959
+ {
960
+ name: skill.name,
961
+ displayName: skill.name.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join(" "),
962
+ description: skill.description,
963
+ trigger: "manual",
964
+ inputs: []
965
+ },
966
+ null,
967
+ 2
968
+ )
969
+ );
970
+ return existing ? { status: "updated", path: mdPath, previousVersion: existing } : { status: "installed", path: mdPath };
971
+ }
972
+ function writeCursorRule(skill, cwd, targetDir) {
973
+ const dir = join2(cwd, targetDir);
974
+ const filePath = join2(dir, `${skill.name}.mdc`);
975
+ const existing = readExistingVersion(filePath);
976
+ if (existing === CLI_VERSION) {
977
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
873
978
  }
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,
911
- engines: { node: ">=22" },
979
+ mkdirSync(dir, { recursive: true });
980
+ const body = `${versionHeader(skill.name)}
981
+ ---
982
+ description: ${JSON.stringify(skill.description)}
983
+ alwaysApply: false
984
+ ---
985
+
986
+ ${skill.content}`;
987
+ writeFileSync(filePath, body);
988
+ return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
989
+ }
990
+ function writeAiderSection(skill, cwd, targetFile) {
991
+ const filePath = join2(cwd, targetFile);
992
+ const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;
993
+ const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;
994
+ const section = `${startMarker}
995
+ ${versionHeader(skill.name)}
996
+ ${skill.content}
997
+ ${endMarker}
998
+ `;
999
+ let existing = "";
1000
+ let existingVersion = null;
1001
+ if (existsSync2(filePath)) {
1002
+ existing = readFileSync(filePath, "utf8");
1003
+ const sectionRe = new RegExp(
1004
+ `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
1005
+ );
1006
+ const sectionMatch = existing.match(sectionRe);
1007
+ if (sectionMatch) {
1008
+ const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);
1009
+ existingVersion = headMatch ? headMatch[2] : null;
1010
+ if (existingVersion === CLI_VERSION) {
1011
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
1012
+ }
1013
+ const next = existing.replace(sectionRe, section);
1014
+ mkdirSync(dirname(filePath), { recursive: true });
1015
+ writeFileSync(filePath, next);
1016
+ return existingVersion ? { status: "updated", path: filePath, previousVersion: existingVersion } : { status: "installed", path: filePath };
1017
+ }
1018
+ }
1019
+ mkdirSync(dirname(filePath), { recursive: true });
1020
+ const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
1021
+ writeFileSync(filePath, existing + prefix + section);
1022
+ return { status: "installed", path: filePath };
1023
+ }
1024
+ function escapeRe(s) {
1025
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1026
+ }
1027
+ function removeSkill(skillName, agent, cwd) {
1028
+ if (agent.agent === "aider") {
1029
+ const filePath = join2(cwd, agent.target);
1030
+ if (!existsSync2(filePath)) return false;
1031
+ const content = readFileSync(filePath, "utf8");
1032
+ const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;
1033
+ const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;
1034
+ const sectionRe = new RegExp(
1035
+ `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
1036
+ );
1037
+ if (!sectionRe.test(content)) return false;
1038
+ writeFileSync(filePath, content.replace(sectionRe, ""));
1039
+ return true;
1040
+ }
1041
+ if (agent.agent === "cursor") {
1042
+ const candidate = join2(cwd, agent.target, `${skillName}.mdc`);
1043
+ if (!existsSync2(candidate)) return false;
1044
+ unlinkSync(candidate);
1045
+ return true;
1046
+ }
1047
+ const dir = join2(cwd, agent.target, skillName);
1048
+ if (!existsSync2(dir)) return false;
1049
+ try {
1050
+ const s = statSync2(dir);
1051
+ if (!s.isDirectory()) return false;
1052
+ } catch {
1053
+ return false;
1054
+ }
1055
+ rmSync(dir, { recursive: true, force: true });
1056
+ return true;
1057
+ }
1058
+
1059
+ // src/lib/ai-files/rules.ts
1060
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
1061
+ import { dirname as dirname2, join as join3 } from "path";
1062
+ var RULES_FILE = {
1063
+ claude: "CLAUDE.md",
1064
+ cursor: ".cursorrules",
1065
+ openclaw: "AGENTS.md",
1066
+ codex: "AGENTS.md",
1067
+ aider: "CONVENTIONS.md"
1068
+ };
1069
+ var START = "<!-- clawnify:rules:start -->";
1070
+ var END = "<!-- clawnify:rules:end -->";
1071
+ var VERSION_RE = /<!--\s*clawnify:rules\s+v([\d.]+)\s*-->/;
1072
+ function block() {
1073
+ return `${START}
1074
+ <!-- clawnify:rules v${CLI_VERSION} -->
1075
+ ${RULES_CONTENT.trimEnd()}
1076
+ ${END}
1077
+ `;
1078
+ }
1079
+ function writeRules(cwd, file) {
1080
+ const filePath = join3(cwd, file);
1081
+ const section = block();
1082
+ const sectionRe = new RegExp(`${escapeRe2(START)}[\\s\\S]*?${escapeRe2(END)}\\n?`);
1083
+ if (existsSync3(filePath)) {
1084
+ const existing = readFileSync2(filePath, "utf8");
1085
+ const match = existing.match(sectionRe);
1086
+ if (match) {
1087
+ const versionMatch = match[0].match(VERSION_RE);
1088
+ const previousVersion = versionMatch ? versionMatch[1] : null;
1089
+ if (previousVersion === CLI_VERSION) {
1090
+ return { status: "skipped", file: filePath, reason: `already at v${CLI_VERSION}` };
1091
+ }
1092
+ writeFileSync2(filePath, existing.replace(sectionRe, section));
1093
+ return previousVersion ? { status: "updated", file: filePath, previousVersion } : { status: "installed", file: filePath };
1094
+ }
1095
+ const prefix = existing.endsWith("\n") ? "\n" : "\n\n";
1096
+ writeFileSync2(filePath, existing + prefix + section);
1097
+ return { status: "installed", file: filePath };
1098
+ }
1099
+ mkdirSync2(dirname2(filePath), { recursive: true });
1100
+ writeFileSync2(filePath, section);
1101
+ return { status: "installed", file: filePath };
1102
+ }
1103
+ function removeRules(cwd, file) {
1104
+ const filePath = join3(cwd, file);
1105
+ if (!existsSync3(filePath)) return false;
1106
+ const existing = readFileSync2(filePath, "utf8");
1107
+ const sectionRe = new RegExp(`\\n?${escapeRe2(START)}[\\s\\S]*?${escapeRe2(END)}\\n?`);
1108
+ if (!sectionRe.test(existing)) return false;
1109
+ const next = existing.replace(sectionRe, "\n").replace(/^\n+/, "").trimEnd();
1110
+ if (next) {
1111
+ writeFileSync2(filePath, next + "\n");
1112
+ } else {
1113
+ unlinkSync2(filePath);
1114
+ }
1115
+ return true;
1116
+ }
1117
+ function escapeRe2(s) {
1118
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1119
+ }
1120
+
1121
+ // src/lib/ai-files/mcp.ts
1122
+ import { existsSync as existsSync4, readFileSync as readFileSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "fs";
1123
+ import { join as join4 } from "path";
1124
+ var FILE = ".mcp.json";
1125
+ var SERVER = {
1126
+ command: "npx",
1127
+ args: ["clawnify", "--mcp"]
1128
+ };
1129
+ function writeMcpConfig(cwd) {
1130
+ const filePath = join4(cwd, FILE);
1131
+ let config = {};
1132
+ let existed = false;
1133
+ if (existsSync4(filePath)) {
1134
+ existed = true;
1135
+ try {
1136
+ config = JSON.parse(readFileSync3(filePath, "utf8"));
1137
+ } catch {
1138
+ return { status: "skipped", file: filePath, reason: "existing .mcp.json is not valid JSON" };
1139
+ }
1140
+ }
1141
+ config.mcpServers ??= {};
1142
+ const current = config.mcpServers["clawnify"];
1143
+ if (current && JSON.stringify(current) === JSON.stringify(SERVER)) {
1144
+ return { status: "skipped", file: filePath, reason: "already configured" };
1145
+ }
1146
+ const wasPresent = current !== void 0;
1147
+ config.mcpServers["clawnify"] = SERVER;
1148
+ writeFileSync3(filePath, JSON.stringify(config, null, 2) + "\n");
1149
+ return existed && wasPresent ? { status: "updated", file: filePath } : { status: "installed", file: filePath };
1150
+ }
1151
+ function removeMcpConfig(cwd) {
1152
+ const filePath = join4(cwd, FILE);
1153
+ if (!existsSync4(filePath)) return false;
1154
+ let config;
1155
+ try {
1156
+ config = JSON.parse(readFileSync3(filePath, "utf8"));
1157
+ } catch {
1158
+ return false;
1159
+ }
1160
+ if (!config.mcpServers || !("clawnify" in config.mcpServers)) return false;
1161
+ delete config.mcpServers["clawnify"];
1162
+ if (Object.keys(config.mcpServers).length === 0) delete config.mcpServers;
1163
+ if (Object.keys(config).length === 0) {
1164
+ unlinkSync3(filePath);
1165
+ } else {
1166
+ writeFileSync3(filePath, JSON.stringify(config, null, 2) + "\n");
1167
+ }
1168
+ return true;
1169
+ }
1170
+
1171
+ // src/commands/ai-files.ts
1172
+ function resolveAgents(cwd, forced) {
1173
+ if (forced) {
1174
+ if (!ALL_AGENTS.includes(forced)) {
1175
+ console.error(`Unknown agent: ${forced}
1176
+ Valid: ${ALL_AGENTS.join(", ")}`);
1177
+ process.exit(1);
1178
+ }
1179
+ return { agents: [agentByName(forced)], defaulted: false };
1180
+ }
1181
+ const detected = detectAgents(cwd);
1182
+ if (detected.length > 0) return { agents: detected, defaulted: false };
1183
+ return { agents: [agentByName("claude")], defaulted: true };
1184
+ }
1185
+ function installAiFiles(cwd, agents, opts) {
1186
+ const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];
1187
+ let rules = 0;
1188
+ for (const file of rulesFiles) {
1189
+ const r = writeRules(cwd, file);
1190
+ if (r.status === "skipped") {
1191
+ console.log(` \xB7 rules \u2192 ${r.file} (${r.reason})`);
1192
+ } else if (r.status === "updated") {
1193
+ console.log(` \u2191 rules \u2192 ${r.file} (v${r.previousVersion} \u2192 v${CLI_VERSION})`);
1194
+ rules++;
1195
+ } else {
1196
+ console.log(` \u2713 rules \u2192 ${r.file}`);
1197
+ rules++;
1198
+ }
1199
+ }
1200
+ let skills = 0;
1201
+ for (const skill of BUNDLED_SKILLS) {
1202
+ for (const agent of agents) {
1203
+ const s = installSkill(skill, agent, cwd);
1204
+ if (s.status === "skipped") {
1205
+ console.log(` \xB7 skill ${skill.name} \u2192 ${s.path} (${s.reason})`);
1206
+ } else if (s.status === "updated") {
1207
+ console.log(` \u2191 skill ${skill.name} \u2192 ${s.path} (v${s.previousVersion} \u2192 v${CLI_VERSION})`);
1208
+ skills++;
1209
+ } else {
1210
+ console.log(` \u2713 skill ${skill.name} \u2192 ${s.path}`);
1211
+ skills++;
1212
+ }
1213
+ }
1214
+ }
1215
+ let mcp = false;
1216
+ if (opts.mcp) {
1217
+ const m = writeMcpConfig(cwd);
1218
+ if (m.status === "skipped") {
1219
+ console.log(` \xB7 mcp \u2192 ${m.file} (${m.reason})`);
1220
+ } else {
1221
+ console.log(` ${m.status === "updated" ? "\u2191" : "\u2713"} mcp \u2192 ${m.file}`);
1222
+ mcp = true;
1223
+ }
1224
+ }
1225
+ return { rules, skills, mcp };
1226
+ }
1227
+ async function aiFilesInstallCommand(opts) {
1228
+ const cwd = process.cwd();
1229
+ const { agents, defaulted } = resolveAgents(cwd, opts.agent);
1230
+ console.log(`Installing Clawnify AI files (CLI v${CLI_VERSION}):`);
1231
+ if (defaulted) {
1232
+ console.log(" No coding agent detected \u2014 defaulting to Claude (CLAUDE.md).");
1233
+ }
1234
+ console.log(` Agents: ${agents.map((a) => a.agent).join(", ")}
1235
+ `);
1236
+ installAiFiles(cwd, agents, { mcp: opts.mcp !== false });
1237
+ console.log("\nDone. Your project is agent-ready.");
1238
+ console.log("Tip: leave `clawnify dev` running so generated types stay fresh.");
1239
+ }
1240
+ async function aiFilesUninstallCommand(opts) {
1241
+ const cwd = process.cwd();
1242
+ const agents = opts.agent ? resolveAgents(cwd, opts.agent).agents : detectAgents(cwd);
1243
+ let removed = 0;
1244
+ const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];
1245
+ for (const file of rulesFiles) {
1246
+ if (removeRules(cwd, file)) {
1247
+ console.log(` \u2717 rules removed from ${file}`);
1248
+ removed++;
1249
+ }
1250
+ }
1251
+ for (const skill of BUNDLED_SKILLS) {
1252
+ for (const agent of agents) {
1253
+ if (removeSkill(skill.name, agent, cwd)) {
1254
+ console.log(` \u2717 skill ${skill.name} removed from ${agent.agent}`);
1255
+ removed++;
1256
+ }
1257
+ }
1258
+ }
1259
+ if (removeMcpConfig(cwd)) {
1260
+ console.log(" \u2717 clawnify server removed from .mcp.json");
1261
+ removed++;
1262
+ }
1263
+ console.log(`
1264
+ Done \u2014 removed ${removed} item${removed === 1 ? "" : "s"}.`);
1265
+ }
1266
+
1267
+ // src/commands/init.ts
1268
+ function ask2(question) {
1269
+ const rl = readline4.createInterface({
1270
+ input: process.stdin,
1271
+ output: process.stdout
1272
+ });
1273
+ return new Promise((resolve) => {
1274
+ rl.question(question, (answer) => {
1275
+ rl.close();
1276
+ resolve(answer.trim());
1277
+ });
1278
+ });
1279
+ }
1280
+ function slugify(name) {
1281
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
1282
+ }
1283
+ async function askProjectType(opts) {
1284
+ if (opts?.type === "app" || opts?.type === "website") return opts.type;
1285
+ if (opts?.type) {
1286
+ console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);
1287
+ process.exit(1);
1288
+ }
1289
+ if (opts?.yes) return "app";
1290
+ console.log();
1291
+ console.log(" What are you creating?");
1292
+ console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
1293
+ console.log(" 2) website \u2014 public site (Astro)");
1294
+ console.log();
1295
+ const choice = await ask2("Type [1]: ") || "1";
1296
+ return choice === "2" ? "website" : "app";
1297
+ }
1298
+ function detectPackageManager() {
1299
+ const ua = process.env.npm_config_user_agent ?? "";
1300
+ if (ua.startsWith("pnpm")) return "pnpm";
1301
+ if (ua.startsWith("yarn")) return "yarn";
1302
+ if (ua.startsWith("bun")) return "bun";
1303
+ return "npm";
1304
+ }
1305
+ async function initCommand(dir, opts) {
1306
+ const type = await askProjectType(opts);
1307
+ if (type === "website") {
1308
+ return initWebsite(dir, opts);
1309
+ }
1310
+ return initApp(dir, opts);
1311
+ }
1312
+ async function initApp(dir, opts) {
1313
+ const yes = !!opts?.yes;
1314
+ const dirArgName = dir ? path3.basename(path3.resolve(dir)) : void 0;
1315
+ const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
1316
+ const slug = slugify(name);
1317
+ let targetDir;
1318
+ if (dir) {
1319
+ targetDir = path3.resolve(dir);
1320
+ } else {
1321
+ const ws = findWorkspaceRoot(process.cwd());
1322
+ targetDir = ws ? path3.join(ws.dir, "apps", slug) : path3.resolve(slug);
1323
+ }
1324
+ let template;
1325
+ if (opts?.template) {
1326
+ template = opts.template === "crud" ? "crud" : "blank";
1327
+ } else if (yes) {
1328
+ template = "blank";
1329
+ } else {
1330
+ console.log();
1331
+ console.log(" Templates:");
1332
+ console.log(" 1) blank \u2014 Empty app with a single API route and page");
1333
+ console.log(" 2) crud \u2014 CRUD app with database, list, and form");
1334
+ console.log();
1335
+ const templateChoice = await ask2("Template [1]: ") || "1";
1336
+ template = templateChoice === "2" ? "crud" : "blank";
1337
+ }
1338
+ if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
1339
+ console.error(`Directory ${targetDir} is not empty.`);
1340
+ process.exit(1);
1341
+ }
1342
+ fs3.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
1343
+ fs3.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
1344
+ let storage;
1345
+ if (opts?.storage !== void 0) {
1346
+ storage = opts.storage;
1347
+ } else if (yes) {
1348
+ storage = false;
1349
+ } else {
1350
+ const storageChoice = await ask2("Enable file uploads? [y/N]: ") || "n";
1351
+ storage = storageChoice.toLowerCase() === "y";
1352
+ }
1353
+ write(targetDir, "clawnify.json", JSON.stringify({
1354
+ $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
1355
+ version: 1,
1356
+ name,
1357
+ description: "",
1358
+ app: { framework: "react+hono", database: true, storage }
1359
+ }, null, 2));
1360
+ const devDeps = {
1361
+ "@cloudflare/workers-types": "^4.0.0",
1362
+ "@tailwindcss/vite": "^4.0.0",
1363
+ "@types/react": "^19.0.0",
1364
+ "@types/react-dom": "^19.0.0",
1365
+ "@vitejs/plugin-react": "^4.0.0",
1366
+ clawnify: "^0.3.0",
1367
+ "drizzle-kit": "^0.31.0",
1368
+ tailwindcss: "^4.0.0",
1369
+ vite: "^6.0.0",
1370
+ wrangler: "^4.0.0"
1371
+ };
1372
+ write(targetDir, "package.json", JSON.stringify({
1373
+ name: slug,
1374
+ private: true,
1375
+ type: "module",
1376
+ scripts: {
1377
+ dev: "clawnify dev",
1378
+ build: "vite build",
1379
+ deploy: "clawnify deploy"
1380
+ },
1381
+ dependencies: {
1382
+ "@clawnify/db": "^0.4.1",
1383
+ "@hono/zod-openapi": "^0.19.0",
1384
+ hono: "^4.0.0",
1385
+ react: "^19.0.0",
1386
+ "react-dom": "^19.0.0",
1387
+ zod: "^3.0.0"
1388
+ },
1389
+ devDependencies: devDeps,
1390
+ engines: { node: ">=22" },
912
1391
  pnpm: { onlyBuiltDependencies: ["esbuild"] }
913
1392
  }, null, 2));
914
1393
  write(targetDir, "tsconfig.json", JSON.stringify({
@@ -980,7 +1459,7 @@ data.db-shm
980
1459
  *
981
1460
  * Multi-tenancy reminder: every user-facing table should carry an
982
1461
  * \`org_id\` column and every query should filter by the X-Clawnify-Org-Id
983
- * header. See docs/build-a-clawnify-app.md.
1462
+ * header. See docs/internal/build-a-clawnify-app.md.
984
1463
  */
985
1464
  export const items = sqliteTable("items", {
986
1465
  id: integer("id").primaryKey({ autoIncrement: true }),
@@ -1096,6 +1575,13 @@ createRoot(document.getElementById("app")!).render(
1096
1575
  } else {
1097
1576
  writeBlankTemplate(targetDir, name);
1098
1577
  }
1578
+ if (opts?.aiFiles !== false) {
1579
+ const detected = detectAgents(targetDir);
1580
+ const agents = detected.length > 0 ? detected : [agentByName("claude")];
1581
+ console.log();
1582
+ console.log(" Installing AI files (rules + skills + MCP):");
1583
+ installAiFiles(targetDir, agents, { mcp: true });
1584
+ }
1099
1585
  const pm = detectPackageManager();
1100
1586
  console.log();
1101
1587
  console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
@@ -1110,10 +1596,21 @@ createRoot(document.getElementById("app")!).render(
1110
1596
  async function initWebsite(dir, opts) {
1111
1597
  const name = opts?.name || await ask2("Site name: ") || "my-site";
1112
1598
  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);
1599
+ let targetDir;
1600
+ if (dir) {
1601
+ targetDir = path3.resolve(dir);
1602
+ } else {
1603
+ const ws = findWorkspaceRoot(process.cwd());
1604
+ targetDir = ws ? path3.join(ws.dir, "website") : path3.resolve(slug);
1605
+ }
1606
+ if (fs3.existsSync(targetDir)) {
1607
+ const entries = fs3.readdirSync(targetDir);
1608
+ const onlyGitkeep = entries.length === 1 && entries[0] === ".gitkeep";
1609
+ if (entries.length > 0 && !onlyGitkeep) {
1610
+ console.error(`Directory ${targetDir} is not empty.`);
1611
+ process.exit(1);
1612
+ }
1613
+ if (onlyGitkeep) fs3.rmSync(path3.join(targetDir, ".gitkeep"));
1117
1614
  }
1118
1615
  fs3.mkdirSync(targetDir, { recursive: true });
1119
1616
  write(targetDir, "clawnify.json", JSON.stringify({
@@ -1302,8 +1799,8 @@ export default api;
1302
1799
 
1303
1800
  <p className="mt-8 text-xs text-slate-500">
1304
1801
  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
1802
+ <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">
1803
+ docs/internal/build-a-clawnify-app.md
1307
1804
  </a>{" "}
1308
1805
  for the full gold-standard guide.
1309
1806
  </p>
@@ -1913,12 +2410,132 @@ async function orgUseCommand(slugOrId) {
1913
2410
  console.error("Not logged in. Run `clawnify login` first.");
1914
2411
  process.exit(1);
1915
2412
  }
1916
- saveAuth({ ...auth, org_id: match.id });
1917
- console.log(` Active org set to ${match.name} (${match.slug})`);
2413
+ saveAuth({ ...auth, org_id: match.id });
2414
+ console.log(` Active org set to ${match.name} (${match.slug})`);
2415
+ }
2416
+
2417
+ // src/commands/workspace.ts
2418
+ import fs5 from "fs";
2419
+ import path7 from "path";
2420
+ function slugify3(name) {
2421
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
2422
+ }
2423
+ async function resolveOrg(opts) {
2424
+ const orgs = await listMyOrgs();
2425
+ if (orgs.length === 0) {
2426
+ console.error("No organizations on your account. Run `clawnify login` first.");
2427
+ process.exit(1);
2428
+ }
2429
+ if (opts?.org) {
2430
+ const match = orgs.find((o) => o.id === opts.org || o.slug === opts.org);
2431
+ if (!match) {
2432
+ console.error(
2433
+ `No org matched "${opts.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
2434
+ );
2435
+ process.exit(1);
2436
+ }
2437
+ return match;
2438
+ }
2439
+ const auth = loadAuth();
2440
+ const active = orgs.find((o) => o.id === auth?.org_id);
2441
+ if (active) return active;
2442
+ if (orgs.length === 1) return orgs[0];
2443
+ console.error(
2444
+ `Multiple orgs \u2014 pick one with \`--org <slug>\` (or set a default: \`clawnify org use <slug>\`).
2445
+ Available: ${orgs.map((o) => o.slug).join(", ")}`
2446
+ );
2447
+ process.exit(1);
2448
+ }
2449
+ function write2(dir, file, content) {
2450
+ const fullPath = path7.join(dir, file);
2451
+ fs5.mkdirSync(path7.dirname(fullPath), { recursive: true });
2452
+ fs5.writeFileSync(fullPath, content);
2453
+ }
2454
+ async function workspaceInitCommand(dir, opts) {
2455
+ const org = await resolveOrg(opts);
2456
+ const name = opts?.name || org.name;
2457
+ const targetDir = dir ? path7.resolve(dir) : path7.resolve(slugify3(org.slug));
2458
+ if (fs5.existsSync(targetDir) && fs5.readdirSync(targetDir).length > 0) {
2459
+ console.error(`Directory ${targetDir} is not empty.`);
2460
+ process.exit(1);
2461
+ }
2462
+ write2(targetDir, "clawnify.json", JSON.stringify({
2463
+ $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
2464
+ version: 1,
2465
+ name,
2466
+ workspace: { org: org.slug }
2467
+ }, null, 2));
2468
+ write2(targetDir, "pnpm-workspace.yaml", `packages:
2469
+ - "apps/*"
2470
+ - "website"
2471
+ `);
2472
+ write2(targetDir, "package.json", JSON.stringify({
2473
+ name: slugify3(org.slug),
2474
+ private: true,
2475
+ type: "module"
2476
+ }, null, 2));
2477
+ write2(targetDir, ".gitignore", `node_modules
2478
+ dist
2479
+ .wrangler
2480
+ .clawnify
2481
+ .env*
2482
+ !.env.example
2483
+ .dev.vars
2484
+ data.db
2485
+ data.db-wal
2486
+ data.db-shm
2487
+ `);
2488
+ write2(targetDir, "README.md", `# ${name}
2489
+
2490
+ Clawnify workspace for the **${org.name}** org (\`${org.slug}\`).
2491
+
2492
+ Layout:
2493
+
2494
+ - \`apps/<name>/\` \u2014 one folder per app; each deploys to this org automatically.
2495
+ - \`website/\` \u2014 the org's single public website (Astro).
2496
+
2497
+ ## Add an app / the website
2498
+
2499
+ \`\`\`bash
2500
+ clawnify init # app \u2192 apps/<name>/ (inherits the org)
2501
+ clawnify init --type website # site \u2192 website/
2502
+ \`\`\`
2503
+
2504
+ ## Deploy
2505
+
2506
+ \`\`\`bash
2507
+ clawnify deploy apps/<name> # one app (or: cd apps/<name> && clawnify deploy)
2508
+ clawnify deploy website # the website
2509
+ \`\`\`
2510
+
2511
+ ## Install dependencies
2512
+
2513
+ \`\`\`bash
2514
+ pnpm install # hoists deps for every app + the website
2515
+ \`\`\`
2516
+
2517
+ ## GitHub sync (optional)
2518
+
2519
+ Push this repo to a single GitHub monorepo, then in the dashboard link each app
2520
+ and the website to its own subdirectory (\`apps/<name>\`, \`website\`). Pushing the
2521
+ repo auto-deploys only the targets whose folder changed; Clawnify mirrors edits
2522
+ back under the same subdirs. See \`docs/internal/adr-company-monorepo.md\` \xA7 "GitHub sync".
2523
+ `);
2524
+ write2(targetDir, "apps/.gitkeep", "");
2525
+ write2(targetDir, "website/.gitkeep", "");
2526
+ const rel = path7.relative(process.cwd(), targetDir) || ".";
2527
+ console.log();
2528
+ console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);
2529
+ console.log();
2530
+ console.log(" Get started:");
2531
+ if (rel !== ".") console.log(` cd ${rel}`);
2532
+ console.log(` clawnify init # add an app under apps/`);
2533
+ console.log(` clawnify deploy apps/<name>`);
2534
+ console.log();
1918
2535
  }
1919
2536
 
1920
2537
  // src/commands/execute.ts
1921
- import fs5 from "fs";
2538
+ import fs6 from "fs";
1922
2539
 
1923
2540
  // src/lib/mcp-client.ts
1924
2541
  var MCP_URL = "https://mcp.clawnify.com/mcp";
@@ -1968,7 +2585,7 @@ async function executeCommand(file, options) {
1968
2585
  code = options.code;
1969
2586
  } else if (file) {
1970
2587
  try {
1971
- code = fs5.readFileSync(file, "utf-8");
2588
+ code = fs6.readFileSync(file, "utf-8");
1972
2589
  } catch (err) {
1973
2590
  process.stderr.write(`Failed to read ${file}: ${String(err)}
1974
2591
  `);
@@ -1984,7 +2601,7 @@ Usage: clawnify execute path/to/file.ts
1984
2601
  process.exit(1);
1985
2602
  }
1986
2603
  const timeout_ms = options.timeout ? Math.max(1e3, parseInt(options.timeout, 10) * 1e3) : 3e4;
1987
- const resp = await callTool("clawnify.execute", { code, timeout_ms });
2604
+ const resp = await callTool("clawnify_execute", { code, timeout_ms });
1988
2605
  if (isError(resp)) {
1989
2606
  process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}
1990
2607
  `);
@@ -2023,8 +2640,8 @@ async function docsCommand(slug, options) {
2023
2640
  process.exit(1);
2024
2641
  }
2025
2642
  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, {
2643
+ const path8 = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;
2644
+ const res = await fetch(DOCS_URL + path8, {
2028
2645
  headers: {
2029
2646
  authorization: "Bearer " + token
2030
2647
  }
@@ -2104,228 +2721,6 @@ async function sdkInstallCommand() {
2104
2721
  process.exit(1);
2105
2722
  }
2106
2723
 
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
2724
  // src/commands/skills.ts
2330
2725
  function skillsListCommand() {
2331
2726
  console.log(`Clawnify skills (v${CLI_VERSION}):
@@ -2345,7 +2740,7 @@ async function skillsAddCommand(name, opts) {
2345
2740
  console.error("No skill specified. Pass a name or --all. See `clawnify skills list`.");
2346
2741
  process.exit(1);
2347
2742
  }
2348
- const agents = resolveAgents(opts.agent);
2743
+ const agents = resolveAgents2(opts.agent);
2349
2744
  if (agents.length === 0) {
2350
2745
  console.error(
2351
2746
  "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 +2787,7 @@ async function skillsRemoveCommand(name, opts) {
2392
2787
  console.error("No skill specified. Pass a name or --all.");
2393
2788
  process.exit(1);
2394
2789
  }
2395
- const agents = resolveAgents(opts.agent);
2790
+ const agents = resolveAgents2(opts.agent);
2396
2791
  if (agents.length === 0) {
2397
2792
  console.error("No coding agent detected. Nothing to remove.");
2398
2793
  return;
@@ -2423,7 +2818,7 @@ Available: ${BUNDLED_SKILLS.map((s) => s.name).join(", ")}`
2423
2818
  }
2424
2819
  return [match];
2425
2820
  }
2426
- function resolveAgents(forced) {
2821
+ function resolveAgents2(forced) {
2427
2822
  if (forced) {
2428
2823
  if (!ALL_AGENTS.includes(forced)) {
2429
2824
  console.error(
@@ -2438,19 +2833,21 @@ Valid: ${ALL_AGENTS.join(", ")}`
2438
2833
  }
2439
2834
 
2440
2835
  // src/cli.ts
2441
- function runCli() {
2836
+ async function runCli() {
2442
2837
  const program = new Command();
2443
2838
  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);
2839
+ 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
2840
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
2446
2841
  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);
2842
+ 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
2843
  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
2844
  const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
2450
2845
  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
2846
  const org = program.command("org").description("Manage organizations");
2452
2847
  org.command("list").description("List orgs you belong to").action(orgListCommand);
2453
2848
  org.command("use <slug-or-id>").description("Set the active org for global commands (ls, whoami, etc.)").action(orgUseCommand);
2849
+ const workspace = program.command("workspace").description("Manage a monorepo that hosts an org's apps");
2850
+ 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
2851
  program.command("ls").description("List deployed apps").action(lsCommand);
2455
2852
  program.command("logs <app-id>").description("Show build logs for an app").action(logsCommand);
2456
2853
  program.command("rm <app-id>").description("Delete an app").action(rmCommand);
@@ -2463,13 +2860,23 @@ function runCli() {
2463
2860
  skills.command("list").description("List available skills").action(skillsListCommand);
2464
2861
  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
2862
  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));
2863
+ const aiFiles = program.command("ai-files").description("Install Clawnify rules + skills + MCP into your coding agent(s)");
2864
+ 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));
2865
+ 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
2866
  const sdk = program.command("sdk").description("Inspect and manage the per-org SDK surface");
2467
2867
  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
2868
  sdk.command("login").description("Authenticate / rotate the OAuth grant (alias of `clawnify login`)").action(sdkLoginCommand);
2469
2869
  sdk.command("install").description("(Deferred) Install @clawnify/sdk locally \u2014 pending Phase 5b").action(sdkInstallCommand);
2470
- program.parse();
2870
+ try {
2871
+ await program.parseAsync();
2872
+ } catch (err) {
2873
+ console.error(err?.message ?? err);
2874
+ process.exitCode = 1;
2875
+ }
2876
+ await new Promise((resolve) => process.stdout.write("", () => resolve()));
2877
+ process.exit(process.exitCode ?? 0);
2471
2878
  }
2472
2879
  export {
2473
2880
  runCli
2474
2881
  };
2475
- //# sourceMappingURL=cli-XYGLEX6Q.js.map
2882
+ //# sourceMappingURL=cli-SJXQKPED.js.map