clawnify 0.4.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.
- package/README.md +45 -17
- package/dist/{chunk-UUTFIFKJ.js → chunk-HOCFYU72.js} +51 -10
- package/dist/chunk-HOCFYU72.js.map +1 -0
- package/dist/{cli-5KZ7W67B.js → cli-SJXQKPED.js} +858 -389
- package/dist/cli-SJXQKPED.js.map +1 -0
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/{mcp-W3X7BY7G.js → mcp-3JPAW35L.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-UUTFIFKJ.js.map +0 -1
- package/dist/cli-5KZ7W67B.js.map +0 -1
- /package/dist/{mcp-W3X7BY7G.js.map → mcp-3JPAW35L.js.map} +0 -0
|
@@ -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-
|
|
21
|
+
} from "./chunk-HOCFYU72.js";
|
|
20
22
|
|
|
21
23
|
// src/cli.ts
|
|
22
24
|
import { Command } from "commander";
|
|
@@ -171,8 +173,10 @@ async function loginCommand() {
|
|
|
171
173
|
}
|
|
172
174
|
|
|
173
175
|
// src/commands/deploy.ts
|
|
176
|
+
import fs2 from "fs";
|
|
174
177
|
import path2 from "path";
|
|
175
178
|
import readline2 from "readline";
|
|
179
|
+
import { spawn } from "child_process";
|
|
176
180
|
|
|
177
181
|
// src/lib/sync-schema.ts
|
|
178
182
|
import fs from "fs/promises";
|
|
@@ -326,7 +330,7 @@ function assertNodeVersion() {
|
|
|
326
330
|
process.exit(1);
|
|
327
331
|
}
|
|
328
332
|
}
|
|
329
|
-
async function resolveOrgId(options, linkedProject) {
|
|
333
|
+
async function resolveOrgId(options, linkedProject, resolvedDir) {
|
|
330
334
|
if (options.org) {
|
|
331
335
|
const orgs = await listMyOrgs();
|
|
332
336
|
const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
|
|
@@ -349,8 +353,26 @@ async function resolveOrgId(options, linkedProject) {
|
|
|
349
353
|
if (linkedProject?.app_id && linkedProject.org_id) {
|
|
350
354
|
return linkedProject.org_id;
|
|
351
355
|
}
|
|
356
|
+
if (resolvedDir) {
|
|
357
|
+
const wsOrg = await workspaceOrgId(resolvedDir);
|
|
358
|
+
if (wsOrg) return wsOrg;
|
|
359
|
+
}
|
|
352
360
|
return void 0;
|
|
353
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
|
+
}
|
|
354
376
|
async function resolveConflictDecision(options, conflict) {
|
|
355
377
|
if (options.updateExisting) return "update";
|
|
356
378
|
if (options.createNew) return "create";
|
|
@@ -441,6 +463,8 @@ async function deployWebsite(dir, options) {
|
|
|
441
463
|
orgId = match.id;
|
|
442
464
|
} else if (linkedProject?.website_id && linkedProject.org_id) {
|
|
443
465
|
orgId = linkedProject.org_id;
|
|
466
|
+
} else {
|
|
467
|
+
orgId = await workspaceOrgId(resolvedDir);
|
|
444
468
|
}
|
|
445
469
|
if (options.dryRun) {
|
|
446
470
|
const sizeKB = (archive.length / 1024).toFixed(1);
|
|
@@ -478,15 +502,30 @@ async function deployWebsite(dir, options) {
|
|
|
478
502
|
`);
|
|
479
503
|
process.exit(1);
|
|
480
504
|
}
|
|
481
|
-
|
|
482
|
-
|
|
505
|
+
if (polled.status === "live") {
|
|
506
|
+
console.log(`
|
|
507
|
+
\u2713 Published! ${result.data.url}
|
|
483
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
|
+
}
|
|
484
517
|
}
|
|
485
518
|
async function deployCommand(dir, options = {}) {
|
|
486
519
|
assertNodeVersion();
|
|
487
520
|
if (!options.from) {
|
|
488
521
|
const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
|
|
489
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
|
+
}
|
|
490
529
|
if (manifest) {
|
|
491
530
|
try {
|
|
492
531
|
const kind = manifestKind(manifest);
|
|
@@ -506,15 +545,18 @@ async function deployCommand(dir, options = {}) {
|
|
|
506
545
|
let syncTargetDir;
|
|
507
546
|
if (options.from) {
|
|
508
547
|
const repo = options.from.replace(/^github:/, "");
|
|
548
|
+
const subdir = options.path?.trim().replace(/^\/+|\/+$/g, "") || void 0;
|
|
509
549
|
if (options.dryRun) {
|
|
510
|
-
console.log(
|
|
511
|
-
|
|
512
|
-
`)
|
|
550
|
+
console.log(
|
|
551
|
+
`
|
|
552
|
+
Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : ""})
|
|
553
|
+
`
|
|
554
|
+
);
|
|
513
555
|
return;
|
|
514
556
|
}
|
|
515
|
-
console.log(`Deploying from ${repo}...`);
|
|
557
|
+
console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : ""}...`);
|
|
516
558
|
const orgId = options.org ? await resolveOrgId(options, null) : void 0;
|
|
517
|
-
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 });
|
|
518
560
|
if (!res.ok) {
|
|
519
561
|
const err = await res.json().catch(() => ({}));
|
|
520
562
|
console.error(`Deploy failed: ${err.error || res.statusText}`);
|
|
@@ -532,8 +574,9 @@ async function deployCommand(dir, options = {}) {
|
|
|
532
574
|
const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
|
|
533
575
|
const framework = manifest?.app?.framework || "vite-preact";
|
|
534
576
|
const linkedProject = readProject(resolvedDir);
|
|
577
|
+
await regenerateDrizzleMigrations(resolvedDir);
|
|
535
578
|
const { archive, files } = createArchive(resolvedDir);
|
|
536
|
-
const orgId = await resolveOrgId(options, linkedProject);
|
|
579
|
+
const orgId = await resolveOrgId(options, linkedProject, resolvedDir);
|
|
537
580
|
if (options.dryRun) {
|
|
538
581
|
summarizeArchive(archive, files, framework, baseName);
|
|
539
582
|
if (linkedProject?.app_id) {
|
|
@@ -643,6 +686,31 @@ async function deployCommand(dir, options = {}) {
|
|
|
643
686
|
}
|
|
644
687
|
}
|
|
645
688
|
}
|
|
689
|
+
async function regenerateDrizzleMigrations(resolvedDir) {
|
|
690
|
+
const schemaTs = path2.join(resolvedDir, "src/server/schema.ts");
|
|
691
|
+
const drizzleConfig = path2.join(resolvedDir, "drizzle.config.ts");
|
|
692
|
+
if (!fs2.existsSync(schemaTs) || !fs2.existsSync(drizzleConfig)) return;
|
|
693
|
+
await new Promise((resolve) => {
|
|
694
|
+
const proc = spawn("npx", ["drizzle-kit", "generate"], {
|
|
695
|
+
cwd: resolvedDir,
|
|
696
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
697
|
+
env: { ...process.env }
|
|
698
|
+
});
|
|
699
|
+
let stderr = "";
|
|
700
|
+
proc.stderr?.on("data", (d) => {
|
|
701
|
+
stderr += d.toString();
|
|
702
|
+
});
|
|
703
|
+
proc.on("exit", (code) => {
|
|
704
|
+
if (code !== 0) {
|
|
705
|
+
console.warn(
|
|
706
|
+
` warning: drizzle-kit generate failed (${stderr.trim().slice(0, 200)}). Continuing with existing .clawnify/drizzle/ contents.`
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
resolve();
|
|
710
|
+
});
|
|
711
|
+
proc.on("error", () => resolve());
|
|
712
|
+
});
|
|
713
|
+
}
|
|
646
714
|
|
|
647
715
|
// src/commands/ls.ts
|
|
648
716
|
async function lsCommand() {
|
|
@@ -761,120 +829,557 @@ async function whoamiCommand() {
|
|
|
761
829
|
}
|
|
762
830
|
|
|
763
831
|
// src/commands/init.ts
|
|
764
|
-
import
|
|
832
|
+
import fs3 from "fs";
|
|
765
833
|
import path3 from "path";
|
|
766
834
|
import readline4 from "readline";
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
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
|
+
}
|
|
778
854
|
}
|
|
779
|
-
function
|
|
780
|
-
|
|
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;
|
|
781
864
|
}
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
if (
|
|
785
|
-
|
|
786
|
-
|
|
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'
|
|
787
879
|
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
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} -->`;
|
|
796
897
|
}
|
|
797
|
-
function
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
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
|
+
}
|
|
803
907
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
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);
|
|
808
920
|
}
|
|
809
|
-
return initApp(dir, opts);
|
|
810
921
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
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}` };
|
|
830
940
|
}
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
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}` };
|
|
834
952
|
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
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}` };
|
|
846
978
|
}
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
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: {
|
|
871
1377
|
dev: "clawnify dev",
|
|
872
1378
|
build: "vite build",
|
|
873
|
-
deploy: "clawnify deploy"
|
|
874
|
-
"db:generate": "drizzle-kit generate"
|
|
1379
|
+
deploy: "clawnify deploy"
|
|
875
1380
|
},
|
|
876
1381
|
dependencies: {
|
|
877
|
-
"@clawnify/db": "^0.4.
|
|
1382
|
+
"@clawnify/db": "^0.4.1",
|
|
878
1383
|
"@hono/zod-openapi": "^0.19.0",
|
|
879
1384
|
hono: "^4.0.0",
|
|
880
1385
|
react: "^19.0.0",
|
|
@@ -954,7 +1459,7 @@ data.db-shm
|
|
|
954
1459
|
*
|
|
955
1460
|
* Multi-tenancy reminder: every user-facing table should carry an
|
|
956
1461
|
* \`org_id\` column and every query should filter by the X-Clawnify-Org-Id
|
|
957
|
-
* header. See docs/build-a-clawnify-app.md.
|
|
1462
|
+
* header. See docs/internal/build-a-clawnify-app.md.
|
|
958
1463
|
*/
|
|
959
1464
|
export const items = sqliteTable("items", {
|
|
960
1465
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
@@ -966,15 +1471,9 @@ export const items = sqliteTable("items", {
|
|
|
966
1471
|
|
|
967
1472
|
export default defineConfig({
|
|
968
1473
|
schema: "./src/server/schema.ts",
|
|
969
|
-
out: "
|
|
1474
|
+
out: "./.clawnify/drizzle",
|
|
970
1475
|
dialect: "sqlite",
|
|
971
1476
|
});
|
|
972
|
-
`);
|
|
973
|
-
write(targetDir, "drizzle/0000_init.sql", `CREATE TABLE \`items\` (
|
|
974
|
-
\`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
975
|
-
\`name\` text NOT NULL,
|
|
976
|
-
\`created_at\` text NOT NULL
|
|
977
|
-
);
|
|
978
1477
|
`);
|
|
979
1478
|
if (storage) {
|
|
980
1479
|
write(targetDir, "src/server/index.ts", `import { OpenAPIHono } from "@hono/zod-openapi";
|
|
@@ -1076,6 +1575,13 @@ createRoot(document.getElementById("app")!).render(
|
|
|
1076
1575
|
} else {
|
|
1077
1576
|
writeBlankTemplate(targetDir, name);
|
|
1078
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
|
+
}
|
|
1079
1585
|
const pm = detectPackageManager();
|
|
1080
1586
|
console.log();
|
|
1081
1587
|
console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
|
|
@@ -1090,12 +1596,23 @@ createRoot(document.getElementById("app")!).render(
|
|
|
1090
1596
|
async function initWebsite(dir, opts) {
|
|
1091
1597
|
const name = opts?.name || await ask2("Site name: ") || "my-site";
|
|
1092
1598
|
const slug = slugify(name);
|
|
1093
|
-
|
|
1094
|
-
if (
|
|
1095
|
-
|
|
1096
|
-
|
|
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"));
|
|
1097
1614
|
}
|
|
1098
|
-
|
|
1615
|
+
fs3.mkdirSync(targetDir, { recursive: true });
|
|
1099
1616
|
write(targetDir, "clawnify.json", JSON.stringify({
|
|
1100
1617
|
$schema: "https://app.clawnify.com/schema/v1/clawnify.json",
|
|
1101
1618
|
version: 1,
|
|
@@ -1282,8 +1799,8 @@ export default api;
|
|
|
1282
1799
|
|
|
1283
1800
|
<p className="mt-8 text-xs text-slate-500">
|
|
1284
1801
|
Read{" "}
|
|
1285
|
-
<a href="https://github.com/clawnify/clawnify/blob/main/docs/build-a-clawnify-app.md" target="_blank" rel="noreferrer" className="underline underline-offset-2">
|
|
1286
|
-
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
|
|
1287
1804
|
</a>{" "}
|
|
1288
1805
|
for the full gold-standard guide.
|
|
1289
1806
|
</p>
|
|
@@ -1302,13 +1819,6 @@ export const items = sqliteTable("items", {
|
|
|
1302
1819
|
status: text("status").notNull().default("active"),
|
|
1303
1820
|
createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),
|
|
1304
1821
|
});
|
|
1305
|
-
`);
|
|
1306
|
-
write(dir, "drizzle/0000_init.sql", `CREATE TABLE \`items\` (
|
|
1307
|
-
\`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
1308
|
-
\`title\` text NOT NULL,
|
|
1309
|
-
\`status\` text DEFAULT 'active' NOT NULL,
|
|
1310
|
-
\`created_at\` text NOT NULL
|
|
1311
|
-
);
|
|
1312
1822
|
`);
|
|
1313
1823
|
write(dir, "src/server/routes.ts", `import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
|
|
1314
1824
|
import { getDB, eq, desc } from "@clawnify/db";
|
|
@@ -1521,14 +2031,14 @@ export function App() {
|
|
|
1521
2031
|
}
|
|
1522
2032
|
function write(dir, file, content) {
|
|
1523
2033
|
const fullPath = path3.join(dir, file);
|
|
1524
|
-
|
|
1525
|
-
|
|
2034
|
+
fs3.mkdirSync(path3.dirname(fullPath), { recursive: true });
|
|
2035
|
+
fs3.writeFileSync(fullPath, content);
|
|
1526
2036
|
}
|
|
1527
2037
|
|
|
1528
2038
|
// src/commands/dev.ts
|
|
1529
|
-
import
|
|
2039
|
+
import fs4 from "fs";
|
|
1530
2040
|
import path4 from "path";
|
|
1531
|
-
import { spawn } from "child_process";
|
|
2041
|
+
import { spawn as spawn2 } from "child_process";
|
|
1532
2042
|
function slugify2(name) {
|
|
1533
2043
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
1534
2044
|
}
|
|
@@ -1589,24 +2099,32 @@ async function devCommand(dir, options) {
|
|
|
1589
2099
|
const storage = manifest.app.storage === true;
|
|
1590
2100
|
const apiPort = options?.port || "8787";
|
|
1591
2101
|
const clawnifyDir = path4.join(resolvedDir, ".clawnify");
|
|
1592
|
-
|
|
2102
|
+
fs4.mkdirSync(clawnifyDir, { recursive: true });
|
|
1593
2103
|
const wranglerPath = path4.join(clawnifyDir, "wrangler.toml");
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
path4.join(resolvedDir, "schema.
|
|
1597
|
-
path4.join(resolvedDir, "
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
2104
|
+
fs4.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
|
|
2105
|
+
if (database) {
|
|
2106
|
+
const schemaTsPath = path4.join(resolvedDir, "src/server/schema.ts");
|
|
2107
|
+
const drizzleConfigPath = path4.join(resolvedDir, "drizzle.config.ts");
|
|
2108
|
+
if (fs4.existsSync(schemaTsPath) && fs4.existsSync(drizzleConfigPath)) {
|
|
2109
|
+
await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath);
|
|
2110
|
+
} else {
|
|
2111
|
+
const schemaCandidates = [
|
|
2112
|
+
path4.join(resolvedDir, "schema.sql"),
|
|
2113
|
+
path4.join(resolvedDir, "src/server/schema.sql")
|
|
2114
|
+
];
|
|
2115
|
+
const schemaPath = schemaCandidates.find((p) => fs4.existsSync(p));
|
|
2116
|
+
if (schemaPath) {
|
|
2117
|
+
await runQuiet(resolvedDir, "npx", [
|
|
2118
|
+
"wrangler",
|
|
2119
|
+
"d1",
|
|
2120
|
+
"execute",
|
|
2121
|
+
`${slug}-db`,
|
|
2122
|
+
"--local",
|
|
2123
|
+
`--file=${schemaPath}`,
|
|
2124
|
+
`--config=${wranglerPath}`
|
|
2125
|
+
]);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
1610
2128
|
}
|
|
1611
2129
|
console.log();
|
|
1612
2130
|
console.log(` ${manifest.name} dev server`);
|
|
@@ -1614,12 +2132,12 @@ async function devCommand(dir, options) {
|
|
|
1614
2132
|
console.log(` UI: http://localhost:5173`);
|
|
1615
2133
|
console.log(` API: http://localhost:${apiPort}`);
|
|
1616
2134
|
console.log();
|
|
1617
|
-
const vite =
|
|
2135
|
+
const vite = spawn2("npx", ["vite"], {
|
|
1618
2136
|
cwd: resolvedDir,
|
|
1619
2137
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1620
2138
|
env: { ...process.env }
|
|
1621
2139
|
});
|
|
1622
|
-
const wrangler =
|
|
2140
|
+
const wrangler = spawn2("npx", [
|
|
1623
2141
|
"wrangler",
|
|
1624
2142
|
"dev",
|
|
1625
2143
|
`--port=${apiPort}`,
|
|
@@ -1678,7 +2196,7 @@ function createFilter(label) {
|
|
|
1678
2196
|
}
|
|
1679
2197
|
function runQuiet(cwd, cmd, args) {
|
|
1680
2198
|
return new Promise((resolve, reject) => {
|
|
1681
|
-
const proc =
|
|
2199
|
+
const proc = spawn2(cmd, args, {
|
|
1682
2200
|
cwd,
|
|
1683
2201
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1684
2202
|
env: { ...process.env }
|
|
@@ -1696,6 +2214,47 @@ function runQuiet(cwd, cmd, args) {
|
|
|
1696
2214
|
});
|
|
1697
2215
|
});
|
|
1698
2216
|
}
|
|
2217
|
+
async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath) {
|
|
2218
|
+
try {
|
|
2219
|
+
await runQuiet(resolvedDir, "npx", ["drizzle-kit", "generate"]);
|
|
2220
|
+
} catch (err) {
|
|
2221
|
+
console.error(
|
|
2222
|
+
` drizzle-kit generate failed. Is \`drizzle-kit\` in devDependencies?
|
|
2223
|
+
${err.message}`
|
|
2224
|
+
);
|
|
2225
|
+
throw err;
|
|
2226
|
+
}
|
|
2227
|
+
const drizzleDir = path4.join(clawnifyDir, "drizzle");
|
|
2228
|
+
if (!fs4.existsSync(drizzleDir)) return;
|
|
2229
|
+
const sqlFiles = fs4.readdirSync(drizzleDir).filter((name) => name.endsWith(".sql")).sort();
|
|
2230
|
+
if (sqlFiles.length === 0) return;
|
|
2231
|
+
const appliedPath = path4.join(clawnifyDir, "applied-migrations.json");
|
|
2232
|
+
let applied = [];
|
|
2233
|
+
if (fs4.existsSync(appliedPath)) {
|
|
2234
|
+
try {
|
|
2235
|
+
applied = JSON.parse(fs4.readFileSync(appliedPath, "utf8"));
|
|
2236
|
+
if (!Array.isArray(applied)) applied = [];
|
|
2237
|
+
} catch {
|
|
2238
|
+
applied = [];
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
const appliedSet = new Set(applied);
|
|
2242
|
+
for (const file of sqlFiles) {
|
|
2243
|
+
if (appliedSet.has(file)) continue;
|
|
2244
|
+
const filePath = path4.join(drizzleDir, file);
|
|
2245
|
+
await runQuiet(resolvedDir, "npx", [
|
|
2246
|
+
"wrangler",
|
|
2247
|
+
"d1",
|
|
2248
|
+
"execute",
|
|
2249
|
+
`${slug}-db`,
|
|
2250
|
+
"--local",
|
|
2251
|
+
`--file=${filePath}`,
|
|
2252
|
+
`--config=${wranglerPath}`
|
|
2253
|
+
]);
|
|
2254
|
+
applied.push(file);
|
|
2255
|
+
}
|
|
2256
|
+
fs4.writeFileSync(appliedPath, JSON.stringify(applied, null, 2) + "\n");
|
|
2257
|
+
}
|
|
1699
2258
|
|
|
1700
2259
|
// src/commands/link.ts
|
|
1701
2260
|
import path5 from "path";
|
|
@@ -1855,8 +2414,128 @@ async function orgUseCommand(slugOrId) {
|
|
|
1855
2414
|
console.log(` Active org set to ${match.name} (${match.slug})`);
|
|
1856
2415
|
}
|
|
1857
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();
|
|
2535
|
+
}
|
|
2536
|
+
|
|
1858
2537
|
// src/commands/execute.ts
|
|
1859
|
-
import
|
|
2538
|
+
import fs6 from "fs";
|
|
1860
2539
|
|
|
1861
2540
|
// src/lib/mcp-client.ts
|
|
1862
2541
|
var MCP_URL = "https://mcp.clawnify.com/mcp";
|
|
@@ -1906,7 +2585,7 @@ async function executeCommand(file, options) {
|
|
|
1906
2585
|
code = options.code;
|
|
1907
2586
|
} else if (file) {
|
|
1908
2587
|
try {
|
|
1909
|
-
code =
|
|
2588
|
+
code = fs6.readFileSync(file, "utf-8");
|
|
1910
2589
|
} catch (err) {
|
|
1911
2590
|
process.stderr.write(`Failed to read ${file}: ${String(err)}
|
|
1912
2591
|
`);
|
|
@@ -1922,7 +2601,7 @@ Usage: clawnify execute path/to/file.ts
|
|
|
1922
2601
|
process.exit(1);
|
|
1923
2602
|
}
|
|
1924
2603
|
const timeout_ms = options.timeout ? Math.max(1e3, parseInt(options.timeout, 10) * 1e3) : 3e4;
|
|
1925
|
-
const resp = await callTool("
|
|
2604
|
+
const resp = await callTool("clawnify_execute", { code, timeout_ms });
|
|
1926
2605
|
if (isError(resp)) {
|
|
1927
2606
|
process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}
|
|
1928
2607
|
`);
|
|
@@ -1961,8 +2640,8 @@ async function docsCommand(slug, options) {
|
|
|
1961
2640
|
process.exit(1);
|
|
1962
2641
|
}
|
|
1963
2642
|
const caller = options.caller ?? "external";
|
|
1964
|
-
const
|
|
1965
|
-
const res = await fetch(DOCS_URL +
|
|
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, {
|
|
1966
2645
|
headers: {
|
|
1967
2646
|
authorization: "Bearer " + token
|
|
1968
2647
|
}
|
|
@@ -2042,228 +2721,6 @@ async function sdkInstallCommand() {
|
|
|
2042
2721
|
process.exit(1);
|
|
2043
2722
|
}
|
|
2044
2723
|
|
|
2045
|
-
// src/lib/skills/content.gen.ts
|
|
2046
|
-
var CLI_VERSION = "0.4.0";
|
|
2047
|
-
var BUNDLED_SKILLS = [
|
|
2048
|
-
{
|
|
2049
|
-
name: "build-a-clawnify-app",
|
|
2050
|
-
description: "Gold-standard structure for building Clawnify apps end-to-end (Hono + React + tRPC + @clawnify/db).",
|
|
2051
|
-
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'
|
|
2052
|
-
}
|
|
2053
|
-
];
|
|
2054
|
-
|
|
2055
|
-
// src/lib/skills/detect.ts
|
|
2056
|
-
import { statSync } from "fs";
|
|
2057
|
-
import { join } from "path";
|
|
2058
|
-
var DETECTORS = [
|
|
2059
|
-
{ agent: "claude", markers: [".claude", ".claude.json", "CLAUDE.md"], target: ".claude/skills" },
|
|
2060
|
-
{ agent: "cursor", markers: [".cursor", ".cursorrules"], target: ".cursor/rules" },
|
|
2061
|
-
{ agent: "openclaw", markers: [".openclaw", "openclaw.json"], target: ".openclaw/skills" },
|
|
2062
|
-
{ agent: "codex", markers: [".codex", "AGENTS.md"], target: ".codex/skills" },
|
|
2063
|
-
{ agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
|
|
2064
|
-
];
|
|
2065
|
-
function exists(cwd, name) {
|
|
2066
|
-
const path7 = join(cwd, name);
|
|
2067
|
-
try {
|
|
2068
|
-
statSync(path7);
|
|
2069
|
-
return true;
|
|
2070
|
-
} catch {
|
|
2071
|
-
return false;
|
|
2072
|
-
}
|
|
2073
|
-
}
|
|
2074
|
-
function detectAgents(cwd) {
|
|
2075
|
-
const found = [];
|
|
2076
|
-
for (const d of DETECTORS) {
|
|
2077
|
-
const hit = d.markers.find((m) => exists(cwd, m));
|
|
2078
|
-
if (hit) {
|
|
2079
|
-
found.push({ agent: d.agent, target: d.target, marker: hit });
|
|
2080
|
-
}
|
|
2081
|
-
}
|
|
2082
|
-
return found;
|
|
2083
|
-
}
|
|
2084
|
-
function agentByName(name) {
|
|
2085
|
-
const d = DETECTORS.find((x) => x.agent === name);
|
|
2086
|
-
if (!d) throw new Error(`Unknown agent: ${name}`);
|
|
2087
|
-
return { agent: d.agent, target: d.target, marker: "(forced)" };
|
|
2088
|
-
}
|
|
2089
|
-
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
2090
|
-
|
|
2091
|
-
// src/lib/skills/install.ts
|
|
2092
|
-
import {
|
|
2093
|
-
existsSync as existsSync2,
|
|
2094
|
-
mkdirSync,
|
|
2095
|
-
readFileSync,
|
|
2096
|
-
writeFileSync,
|
|
2097
|
-
statSync as statSync2,
|
|
2098
|
-
rmSync,
|
|
2099
|
-
unlinkSync
|
|
2100
|
-
} from "fs";
|
|
2101
|
-
import { dirname, join as join2 } from "path";
|
|
2102
|
-
var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
|
|
2103
|
-
function versionHeader(name) {
|
|
2104
|
-
return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
|
|
2105
|
-
}
|
|
2106
|
-
function readExistingVersion(path7) {
|
|
2107
|
-
if (!existsSync2(path7)) return null;
|
|
2108
|
-
try {
|
|
2109
|
-
const head = readFileSync(path7, "utf8").slice(0, 500);
|
|
2110
|
-
const match = head.match(VERSION_HEADER_RE);
|
|
2111
|
-
return match ? match[2] : null;
|
|
2112
|
-
} catch {
|
|
2113
|
-
return null;
|
|
2114
|
-
}
|
|
2115
|
-
}
|
|
2116
|
-
function installSkill(skill, agent, cwd) {
|
|
2117
|
-
switch (agent.agent) {
|
|
2118
|
-
case "claude":
|
|
2119
|
-
return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);
|
|
2120
|
-
case "codex":
|
|
2121
|
-
return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);
|
|
2122
|
-
case "openclaw":
|
|
2123
|
-
return writeOpenclawSkill(skill, cwd, agent.target);
|
|
2124
|
-
case "cursor":
|
|
2125
|
-
return writeCursorRule(skill, cwd, agent.target);
|
|
2126
|
-
case "aider":
|
|
2127
|
-
return writeAiderSection(skill, cwd, agent.target);
|
|
2128
|
-
}
|
|
2129
|
-
}
|
|
2130
|
-
function formatClaudeSkill(skill) {
|
|
2131
|
-
return `${versionHeader(skill.name)}
|
|
2132
|
-
---
|
|
2133
|
-
name: ${skill.name}
|
|
2134
|
-
description: ${JSON.stringify(skill.description)}
|
|
2135
|
-
---
|
|
2136
|
-
|
|
2137
|
-
${skill.content}`;
|
|
2138
|
-
}
|
|
2139
|
-
function formatCodexSkill(skill) {
|
|
2140
|
-
return formatClaudeSkill(skill);
|
|
2141
|
-
}
|
|
2142
|
-
function writeSkillDir(skill, cwd, targetDir, format) {
|
|
2143
|
-
const skillDir = join2(cwd, targetDir, skill.name);
|
|
2144
|
-
const filePath = join2(skillDir, "SKILL.md");
|
|
2145
|
-
const existing = readExistingVersion(filePath);
|
|
2146
|
-
if (existing === CLI_VERSION) {
|
|
2147
|
-
return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
|
|
2148
|
-
}
|
|
2149
|
-
mkdirSync(skillDir, { recursive: true });
|
|
2150
|
-
writeFileSync(filePath, format(skill));
|
|
2151
|
-
return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
|
|
2152
|
-
}
|
|
2153
|
-
function writeOpenclawSkill(skill, cwd, targetDir) {
|
|
2154
|
-
const skillDir = join2(cwd, targetDir, skill.name);
|
|
2155
|
-
const mdPath = join2(skillDir, "SKILL.md");
|
|
2156
|
-
const jsonPath = join2(skillDir, "skill.json");
|
|
2157
|
-
const existing = readExistingVersion(mdPath);
|
|
2158
|
-
if (existing === CLI_VERSION) {
|
|
2159
|
-
return { status: "skipped", path: mdPath, reason: `already at v${CLI_VERSION}` };
|
|
2160
|
-
}
|
|
2161
|
-
mkdirSync(skillDir, { recursive: true });
|
|
2162
|
-
writeFileSync(mdPath, `${versionHeader(skill.name)}
|
|
2163
|
-
${skill.content}`);
|
|
2164
|
-
writeFileSync(
|
|
2165
|
-
jsonPath,
|
|
2166
|
-
JSON.stringify(
|
|
2167
|
-
{
|
|
2168
|
-
name: skill.name,
|
|
2169
|
-
displayName: skill.name.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join(" "),
|
|
2170
|
-
description: skill.description,
|
|
2171
|
-
trigger: "manual",
|
|
2172
|
-
inputs: []
|
|
2173
|
-
},
|
|
2174
|
-
null,
|
|
2175
|
-
2
|
|
2176
|
-
)
|
|
2177
|
-
);
|
|
2178
|
-
return existing ? { status: "updated", path: mdPath, previousVersion: existing } : { status: "installed", path: mdPath };
|
|
2179
|
-
}
|
|
2180
|
-
function writeCursorRule(skill, cwd, targetDir) {
|
|
2181
|
-
const dir = join2(cwd, targetDir);
|
|
2182
|
-
const filePath = join2(dir, `${skill.name}.mdc`);
|
|
2183
|
-
const existing = readExistingVersion(filePath);
|
|
2184
|
-
if (existing === CLI_VERSION) {
|
|
2185
|
-
return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
|
|
2186
|
-
}
|
|
2187
|
-
mkdirSync(dir, { recursive: true });
|
|
2188
|
-
const body = `${versionHeader(skill.name)}
|
|
2189
|
-
---
|
|
2190
|
-
description: ${JSON.stringify(skill.description)}
|
|
2191
|
-
alwaysApply: false
|
|
2192
|
-
---
|
|
2193
|
-
|
|
2194
|
-
${skill.content}`;
|
|
2195
|
-
writeFileSync(filePath, body);
|
|
2196
|
-
return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
|
|
2197
|
-
}
|
|
2198
|
-
function writeAiderSection(skill, cwd, targetFile) {
|
|
2199
|
-
const filePath = join2(cwd, targetFile);
|
|
2200
|
-
const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;
|
|
2201
|
-
const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;
|
|
2202
|
-
const section = `${startMarker}
|
|
2203
|
-
${versionHeader(skill.name)}
|
|
2204
|
-
${skill.content}
|
|
2205
|
-
${endMarker}
|
|
2206
|
-
`;
|
|
2207
|
-
let existing = "";
|
|
2208
|
-
let existingVersion = null;
|
|
2209
|
-
if (existsSync2(filePath)) {
|
|
2210
|
-
existing = readFileSync(filePath, "utf8");
|
|
2211
|
-
const sectionRe = new RegExp(
|
|
2212
|
-
`${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
|
|
2213
|
-
);
|
|
2214
|
-
const sectionMatch = existing.match(sectionRe);
|
|
2215
|
-
if (sectionMatch) {
|
|
2216
|
-
const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);
|
|
2217
|
-
existingVersion = headMatch ? headMatch[2] : null;
|
|
2218
|
-
if (existingVersion === CLI_VERSION) {
|
|
2219
|
-
return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
|
|
2220
|
-
}
|
|
2221
|
-
const next = existing.replace(sectionRe, section);
|
|
2222
|
-
mkdirSync(dirname(filePath), { recursive: true });
|
|
2223
|
-
writeFileSync(filePath, next);
|
|
2224
|
-
return existingVersion ? { status: "updated", path: filePath, previousVersion: existingVersion } : { status: "installed", path: filePath };
|
|
2225
|
-
}
|
|
2226
|
-
}
|
|
2227
|
-
mkdirSync(dirname(filePath), { recursive: true });
|
|
2228
|
-
const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
|
|
2229
|
-
writeFileSync(filePath, existing + prefix + section);
|
|
2230
|
-
return { status: "installed", path: filePath };
|
|
2231
|
-
}
|
|
2232
|
-
function escapeRe(s) {
|
|
2233
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2234
|
-
}
|
|
2235
|
-
function removeSkill(skillName, agent, cwd) {
|
|
2236
|
-
if (agent.agent === "aider") {
|
|
2237
|
-
const filePath = join2(cwd, agent.target);
|
|
2238
|
-
if (!existsSync2(filePath)) return false;
|
|
2239
|
-
const content = readFileSync(filePath, "utf8");
|
|
2240
|
-
const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;
|
|
2241
|
-
const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;
|
|
2242
|
-
const sectionRe = new RegExp(
|
|
2243
|
-
`${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
|
|
2244
|
-
);
|
|
2245
|
-
if (!sectionRe.test(content)) return false;
|
|
2246
|
-
writeFileSync(filePath, content.replace(sectionRe, ""));
|
|
2247
|
-
return true;
|
|
2248
|
-
}
|
|
2249
|
-
if (agent.agent === "cursor") {
|
|
2250
|
-
const candidate = join2(cwd, agent.target, `${skillName}.mdc`);
|
|
2251
|
-
if (!existsSync2(candidate)) return false;
|
|
2252
|
-
unlinkSync(candidate);
|
|
2253
|
-
return true;
|
|
2254
|
-
}
|
|
2255
|
-
const dir = join2(cwd, agent.target, skillName);
|
|
2256
|
-
if (!existsSync2(dir)) return false;
|
|
2257
|
-
try {
|
|
2258
|
-
const s = statSync2(dir);
|
|
2259
|
-
if (!s.isDirectory()) return false;
|
|
2260
|
-
} catch {
|
|
2261
|
-
return false;
|
|
2262
|
-
}
|
|
2263
|
-
rmSync(dir, { recursive: true, force: true });
|
|
2264
|
-
return true;
|
|
2265
|
-
}
|
|
2266
|
-
|
|
2267
2724
|
// src/commands/skills.ts
|
|
2268
2725
|
function skillsListCommand() {
|
|
2269
2726
|
console.log(`Clawnify skills (v${CLI_VERSION}):
|
|
@@ -2283,7 +2740,7 @@ async function skillsAddCommand(name, opts) {
|
|
|
2283
2740
|
console.error("No skill specified. Pass a name or --all. See `clawnify skills list`.");
|
|
2284
2741
|
process.exit(1);
|
|
2285
2742
|
}
|
|
2286
|
-
const agents =
|
|
2743
|
+
const agents = resolveAgents2(opts.agent);
|
|
2287
2744
|
if (agents.length === 0) {
|
|
2288
2745
|
console.error(
|
|
2289
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>."
|
|
@@ -2330,7 +2787,7 @@ async function skillsRemoveCommand(name, opts) {
|
|
|
2330
2787
|
console.error("No skill specified. Pass a name or --all.");
|
|
2331
2788
|
process.exit(1);
|
|
2332
2789
|
}
|
|
2333
|
-
const agents =
|
|
2790
|
+
const agents = resolveAgents2(opts.agent);
|
|
2334
2791
|
if (agents.length === 0) {
|
|
2335
2792
|
console.error("No coding agent detected. Nothing to remove.");
|
|
2336
2793
|
return;
|
|
@@ -2361,7 +2818,7 @@ Available: ${BUNDLED_SKILLS.map((s) => s.name).join(", ")}`
|
|
|
2361
2818
|
}
|
|
2362
2819
|
return [match];
|
|
2363
2820
|
}
|
|
2364
|
-
function
|
|
2821
|
+
function resolveAgents2(forced) {
|
|
2365
2822
|
if (forced) {
|
|
2366
2823
|
if (!ALL_AGENTS.includes(forced)) {
|
|
2367
2824
|
console.error(
|
|
@@ -2376,19 +2833,21 @@ Valid: ${ALL_AGENTS.join(", ")}`
|
|
|
2376
2833
|
}
|
|
2377
2834
|
|
|
2378
2835
|
// src/cli.ts
|
|
2379
|
-
function runCli() {
|
|
2836
|
+
async function runCli() {
|
|
2380
2837
|
const program = new Command();
|
|
2381
2838
|
program.name("clawnify").description("Deploy apps to Clawnify").version("0.1.0");
|
|
2382
|
-
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);
|
|
2383
2840
|
program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
|
|
2384
2841
|
program.command("login").description("Authenticate with Clawnify").action(loginCommand);
|
|
2385
|
-
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);
|
|
2386
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);
|
|
2387
2844
|
const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
|
|
2388
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);
|
|
2389
2846
|
const org = program.command("org").description("Manage organizations");
|
|
2390
2847
|
org.command("list").description("List orgs you belong to").action(orgListCommand);
|
|
2391
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);
|
|
2392
2851
|
program.command("ls").description("List deployed apps").action(lsCommand);
|
|
2393
2852
|
program.command("logs <app-id>").description("Show build logs for an app").action(logsCommand);
|
|
2394
2853
|
program.command("rm <app-id>").description("Delete an app").action(rmCommand);
|
|
@@ -2401,13 +2860,23 @@ function runCli() {
|
|
|
2401
2860
|
skills.command("list").description("List available skills").action(skillsListCommand);
|
|
2402
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));
|
|
2403
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));
|
|
2404
2866
|
const sdk = program.command("sdk").description("Inspect and manage the per-org SDK surface");
|
|
2405
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);
|
|
2406
2868
|
sdk.command("login").description("Authenticate / rotate the OAuth grant (alias of `clawnify login`)").action(sdkLoginCommand);
|
|
2407
2869
|
sdk.command("install").description("(Deferred) Install @clawnify/sdk locally \u2014 pending Phase 5b").action(sdkInstallCommand);
|
|
2408
|
-
|
|
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);
|
|
2409
2878
|
}
|
|
2410
2879
|
export {
|
|
2411
2880
|
runCli
|
|
2412
2881
|
};
|
|
2413
|
-
//# sourceMappingURL=cli-
|
|
2882
|
+
//# sourceMappingURL=cli-SJXQKPED.js.map
|