clawnify 0.6.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.
@@ -109,7 +109,11 @@ async function loginCommand() {
109
109
  });
110
110
  server.listen(port, () => {
111
111
  console.log("Opening browser to authorize...");
112
- 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
+ });
113
117
  console.log("Waiting for authorization...");
114
118
  });
115
119
  });
@@ -870,12 +874,12 @@ function agentByName(name) {
870
874
  var ALL_AGENTS = DETECTORS.map((d) => d.agent);
871
875
 
872
876
  // src/lib/skills/content.gen.ts
873
- var CLI_VERSION = "0.6.0";
877
+ var CLI_VERSION = "0.6.1";
874
878
  var BUNDLED_SKILLS = [
875
879
  {
876
880
  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'
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'
879
883
  }
880
884
  ];
881
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";
@@ -2879,4 +2883,4 @@ async function runCli() {
2879
2883
  export {
2880
2884
  runCli
2881
2885
  };
2882
- //# sourceMappingURL=cli-SJXQKPED.js.map
2886
+ //# sourceMappingURL=cli-OQPC6TYM.js.map