clawnify 0.1.17 → 0.3.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.
@@ -7,14 +7,16 @@ import {
7
7
  createArchive,
8
8
  generatePkce,
9
9
  getEmailFromToken,
10
+ getValidToken,
10
11
  listMyOrgs,
11
12
  loadAuth,
13
+ manifestKind,
12
14
  pollUntilReady,
13
15
  readManifest,
14
16
  readProject,
15
17
  saveAuth,
16
18
  saveProject
17
- } from "./chunk-CMM323B2.js";
19
+ } from "./chunk-UUTFIFKJ.js";
18
20
 
19
21
  // src/cli.ts
20
22
  import { Command } from "commander";
@@ -397,8 +399,106 @@ function summarizeArchive(buf, files, framework, name) {
397
399
  }
398
400
  console.log();
399
401
  }
402
+ async function uploadWebsiteDeploy(archive, name, orgId) {
403
+ const formData = new FormData();
404
+ formData.append("source", new Blob([archive]), "source.tar.gz");
405
+ if (name) formData.append("name", name);
406
+ const res = await api.postForm("/v1/websites/deploy", formData, { orgId });
407
+ if (res.ok) {
408
+ const data = await res.json();
409
+ return { ok: true, data };
410
+ }
411
+ const err = await res.json().catch(() => ({}));
412
+ return { ok: false, error: err.error || res.statusText };
413
+ }
414
+ async function deployWebsite(dir, options) {
415
+ if (options.from) {
416
+ console.error("--from is app-only for now. Run `clawnify deploy` inside the website project directory.");
417
+ process.exit(EXIT_USAGE);
418
+ }
419
+ const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
420
+ const manifest = readManifest(resolvedDir);
421
+ const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
422
+ const linkedProject = readProject(resolvedDir);
423
+ const { archive, files } = createArchive(resolvedDir);
424
+ let orgId;
425
+ if (options.org) {
426
+ const orgs = await listMyOrgs();
427
+ const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
428
+ if (!match) {
429
+ console.error(
430
+ `No org matched "${options.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
431
+ );
432
+ process.exit(EXIT_USAGE);
433
+ }
434
+ if (linkedProject?.website_id && linkedProject.org_id && linkedProject.org_id !== match.id) {
435
+ console.error(
436
+ `This project is linked to a different org (${linkedProject.org_id}).
437
+ --org ${options.org} resolves to ${match.id}.`
438
+ );
439
+ process.exit(1);
440
+ }
441
+ orgId = match.id;
442
+ } else if (linkedProject?.website_id && linkedProject.org_id) {
443
+ orgId = linkedProject.org_id;
444
+ }
445
+ if (options.dryRun) {
446
+ const sizeKB = (archive.length / 1024).toFixed(1);
447
+ console.log(`
448
+ Dry run \u2014 would deploy website '${baseName}' (astro)`);
449
+ console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped
450
+ `);
451
+ const preview = files.slice(0, 25);
452
+ for (const f of preview) console.log(` ${f}`);
453
+ if (files.length > preview.length) {
454
+ console.log(` ... and ${files.length - preview.length} more`);
455
+ }
456
+ console.log();
457
+ return;
458
+ }
459
+ console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);
460
+ const result = await uploadWebsiteDeploy(archive, baseName, orgId);
461
+ if (!result.ok) {
462
+ console.error(`Deploy failed: ${result.error}`);
463
+ process.exit(1);
464
+ }
465
+ saveProject(resolvedDir, {
466
+ kind: "website",
467
+ org_id: orgId,
468
+ website_id: result.data.website_id,
469
+ slug: result.data.slug
470
+ });
471
+ const polled = await pollUntilReady(result.data.website_id, {
472
+ kind: "website",
473
+ orgId
474
+ });
475
+ if (polled.status === "error") {
476
+ console.error(`
477
+ Deploy failed: ${polled.error || "Unknown error"}
478
+ `);
479
+ process.exit(1);
480
+ }
481
+ console.log(`
482
+ \u2713 Deployed! ${result.data.url}
483
+ `);
484
+ }
400
485
  async function deployCommand(dir, options = {}) {
401
486
  assertNodeVersion();
487
+ if (!options.from) {
488
+ const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
489
+ const manifest = readManifest(resolvedDir);
490
+ if (manifest) {
491
+ try {
492
+ const kind = manifestKind(manifest);
493
+ if (kind === "website") {
494
+ return deployWebsite(dir, options);
495
+ }
496
+ } catch (err) {
497
+ console.error(`${err.message}`);
498
+ process.exit(EXIT_USAGE);
499
+ }
500
+ }
501
+ }
402
502
  let appId;
403
503
  let slug;
404
504
  let appToken;
@@ -679,7 +779,28 @@ function ask2(question) {
679
779
  function slugify(name) {
680
780
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
681
781
  }
782
+ async function askProjectType(opts) {
783
+ if (opts?.type === "app" || opts?.type === "website") return opts.type;
784
+ if (opts?.type) {
785
+ console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);
786
+ process.exit(1);
787
+ }
788
+ console.log();
789
+ console.log(" What are you creating?");
790
+ console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
791
+ console.log(" 2) website \u2014 public site (Astro)");
792
+ console.log();
793
+ const choice = await ask2("Type [1]: ") || "1";
794
+ return choice === "2" ? "website" : "app";
795
+ }
682
796
  async function initCommand(dir, opts) {
797
+ const type = await askProjectType(opts);
798
+ if (type === "website") {
799
+ return initWebsite(dir, opts);
800
+ }
801
+ return initApp(dir, opts);
802
+ }
803
+ async function initApp(dir, opts) {
683
804
  const name = opts?.name || await ask2("App name: ") || "my-app";
684
805
  const slug = slugify(name);
685
806
  const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
@@ -962,8 +1083,135 @@ createRoot(document.getElementById("app")!).render(
962
1083
  console.log(" pnpm deploy # deploy to production");
963
1084
  console.log();
964
1085
  }
1086
+ async function initWebsite(dir, opts) {
1087
+ const name = opts?.name || await ask2("Site name: ") || "my-site";
1088
+ const slug = slugify(name);
1089
+ const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
1090
+ if (fs2.existsSync(targetDir) && fs2.readdirSync(targetDir).length > 0) {
1091
+ console.error(`Directory ${targetDir} is not empty.`);
1092
+ process.exit(1);
1093
+ }
1094
+ fs2.mkdirSync(targetDir, { recursive: true });
1095
+ write(targetDir, "clawnify.json", JSON.stringify({
1096
+ $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
1097
+ version: 1,
1098
+ name,
1099
+ description: "",
1100
+ website: { framework: "astro" }
1101
+ }, null, 2));
1102
+ write(targetDir, "package.json", JSON.stringify({
1103
+ name: slug,
1104
+ private: true,
1105
+ type: "module",
1106
+ scripts: {
1107
+ dev: "astro dev",
1108
+ build: "astro build",
1109
+ preview: "astro preview",
1110
+ deploy: "clawnify deploy"
1111
+ },
1112
+ dependencies: {
1113
+ "@astrojs/cloudflare": "^12.0.0",
1114
+ "@tailwindcss/vite": "^4.0.0",
1115
+ astro: "^5.0.0",
1116
+ tailwindcss: "^4.0.0"
1117
+ },
1118
+ devDependencies: {
1119
+ clawnify: "^0.1.15",
1120
+ "wrangler": "^4.0.0"
1121
+ },
1122
+ engines: { node: ">=22" }
1123
+ }, null, 2));
1124
+ write(targetDir, "tsconfig.json", JSON.stringify({
1125
+ extends: "astro/tsconfigs/strict",
1126
+ include: ["src/**/*", ".astro/types.d.ts"],
1127
+ exclude: ["dist", "node_modules"]
1128
+ }, null, 2));
1129
+ write(targetDir, "astro.config.mjs", `import { defineConfig } from "astro/config";
1130
+ import cloudflare from "@astrojs/cloudflare";
1131
+ import tailwindcss from "@tailwindcss/vite";
1132
+
1133
+ export default defineConfig({
1134
+ output: "server",
1135
+ adapter: cloudflare(),
1136
+ vite: {
1137
+ plugins: [tailwindcss()],
1138
+ },
1139
+ });
1140
+ `);
1141
+ write(targetDir, ".gitignore", `node_modules
1142
+ dist
1143
+ .astro
1144
+ .wrangler
1145
+ .clawnify
1146
+ .env*
1147
+ !.env.example
1148
+ .dev.vars
1149
+ `);
1150
+ write(targetDir, "src/styles/global.css", `@import "tailwindcss";
1151
+
1152
+ :root {
1153
+ --color-primary: oklch(0.55 0.18 250);
1154
+ --color-ink: oklch(0.2 0.02 250);
1155
+ --color-canvas: oklch(0.99 0 0);
1156
+ }
1157
+
1158
+ body {
1159
+ background-color: var(--color-canvas);
1160
+ color: var(--color-ink);
1161
+ font-family: ui-sans-serif, system-ui, sans-serif;
1162
+ }
1163
+ `);
1164
+ write(targetDir, "src/layouts/BaseLayout.astro", `---
1165
+ interface Props {
1166
+ title?: string;
1167
+ description?: string;
1168
+ }
1169
+
1170
+ const { title = "${name}", description = "" } = Astro.props;
1171
+ ---
1172
+ <!doctype html>
1173
+ <html lang="en">
1174
+ <head>
1175
+ <meta charset="utf-8" />
1176
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1177
+ <title>{title}</title>
1178
+ {description && <meta name="description" content={description} />}
1179
+ <link rel="stylesheet" href="/src/styles/global.css" />
1180
+ </head>
1181
+ <body>
1182
+ <slot />
1183
+ </body>
1184
+ </html>
1185
+ `);
1186
+ write(targetDir, "src/pages/index.astro", `---
1187
+ import BaseLayout from "../layouts/BaseLayout.astro";
1188
+ ---
1189
+ <BaseLayout title="${name}">
1190
+ <main class="mx-auto max-w-3xl px-6 py-24">
1191
+ <h1 class="text-5xl font-semibold tracking-tight">${name}</h1>
1192
+ <p class="mt-4 text-lg opacity-70">
1193
+ Edit <code>src/pages/index.astro</code> to get started.
1194
+ </p>
1195
+ <p class="mt-8">
1196
+ <a class="underline" href="https://docs.astro.build" target="_blank" rel="noreferrer">
1197
+ Astro docs \u2192
1198
+ </a>
1199
+ </p>
1200
+ </main>
1201
+ </BaseLayout>
1202
+ `);
1203
+ console.log();
1204
+ console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
1205
+ console.log();
1206
+ console.log(" Get started:");
1207
+ console.log(` cd ${path3.relative(process.cwd(), targetDir)}`);
1208
+ console.log(" pnpm install");
1209
+ console.log(" pnpm dev # local dev at http://localhost:4321");
1210
+ console.log(" pnpm deploy # deploy as your org's website");
1211
+ console.log();
1212
+ }
965
1213
  function writeBlankTemplate(dir, name) {
966
- write(dir, "src/server/schema.sql", `CREATE TABLE IF NOT EXISTS items (
1214
+ write(dir, "schema.sql", `CREATE TABLE IF NOT EXISTS items (
967
1215
  id INTEGER PRIMARY KEY AUTOINCREMENT,
968
1216
  name TEXT NOT NULL,
969
1217
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
@@ -1028,7 +1276,7 @@ export function App() {
1028
1276
  `);
1029
1277
  }
1030
1278
  function writeCrudTemplate(dir, name) {
1031
- write(dir, "src/server/schema.sql", `CREATE TABLE IF NOT EXISTS items (
1279
+ write(dir, "schema.sql", `CREATE TABLE IF NOT EXISTS items (
1032
1280
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1033
1281
  title TEXT NOT NULL,
1034
1282
  status TEXT NOT NULL DEFAULT 'active',
@@ -1293,6 +1541,12 @@ async function devCommand(dir, options) {
1293
1541
  console.error("No clawnify.json found. Run `clawnify init` first.");
1294
1542
  process.exit(1);
1295
1543
  }
1544
+ if (!manifest.app) {
1545
+ console.error(
1546
+ "`clawnify dev` is for app projects only. For a website, run `pnpm dev` (astro dev) directly."
1547
+ );
1548
+ process.exit(1);
1549
+ }
1296
1550
  const slug = slugify2(manifest.name);
1297
1551
  const database = manifest.app.database !== false;
1298
1552
  const storage = manifest.app.storage === true;
@@ -1301,8 +1555,12 @@ async function devCommand(dir, options) {
1301
1555
  fs3.mkdirSync(clawnifyDir, { recursive: true });
1302
1556
  const wranglerPath = path4.join(clawnifyDir, "wrangler.toml");
1303
1557
  fs3.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
1304
- const schemaPath = path4.join(resolvedDir, "src/server/schema.sql");
1305
- if (database && fs3.existsSync(schemaPath)) {
1558
+ const schemaCandidates = [
1559
+ path4.join(resolvedDir, "schema.sql"),
1560
+ path4.join(resolvedDir, "src/server/schema.sql")
1561
+ ];
1562
+ const schemaPath = schemaCandidates.find((p) => fs3.existsSync(p));
1563
+ if (database && schemaPath) {
1306
1564
  await runQuiet(resolvedDir, "npx", [
1307
1565
  "wrangler",
1308
1566
  "d1",
@@ -1560,14 +1818,534 @@ async function orgUseCommand(slugOrId) {
1560
1818
  console.log(` Active org set to ${match.name} (${match.slug})`);
1561
1819
  }
1562
1820
 
1821
+ // src/commands/execute.ts
1822
+ import fs4 from "fs";
1823
+
1824
+ // src/lib/mcp-client.ts
1825
+ var MCP_URL = "https://mcp.clawnify.com/mcp";
1826
+ async function callTool(name, args) {
1827
+ const token = await getValidToken();
1828
+ if (!token) {
1829
+ process.stderr.write("Not logged in. Run `clawnify login` first.\n");
1830
+ process.exit(1);
1831
+ }
1832
+ const auth = loadAuth();
1833
+ const headers = {
1834
+ "content-type": "application/json",
1835
+ authorization: "Bearer " + token
1836
+ };
1837
+ if (auth?.org_id) {
1838
+ headers["X-Clawnify-Org-Id"] = auth.org_id;
1839
+ }
1840
+ const res = await fetch(MCP_URL, {
1841
+ method: "POST",
1842
+ headers,
1843
+ body: JSON.stringify({
1844
+ jsonrpc: "2.0",
1845
+ id: Date.now(),
1846
+ method: "tools/call",
1847
+ params: { name, arguments: args }
1848
+ })
1849
+ });
1850
+ if (res.status === 401) {
1851
+ process.stderr.write("Authentication failed. Run `clawnify login` again.\n");
1852
+ process.exit(1);
1853
+ }
1854
+ const body = await res.json();
1855
+ if (body.error) return { error: body.error };
1856
+ if (!body.result) {
1857
+ return { error: { code: -32603, message: "Empty response from MCP gateway" } };
1858
+ }
1859
+ return { result: body.result };
1860
+ }
1861
+ function isError(resp) {
1862
+ return "error" in resp;
1863
+ }
1864
+
1865
+ // src/commands/execute.ts
1866
+ async function executeCommand(file, options) {
1867
+ let code;
1868
+ if (options.code) {
1869
+ code = options.code;
1870
+ } else if (file) {
1871
+ try {
1872
+ code = fs4.readFileSync(file, "utf-8");
1873
+ } catch (err) {
1874
+ process.stderr.write(`Failed to read ${file}: ${String(err)}
1875
+ `);
1876
+ process.exit(1);
1877
+ }
1878
+ } else {
1879
+ process.stderr.write(
1880
+ `Provide a file path or --code 'inline code'.
1881
+ Usage: clawnify execute path/to/file.ts
1882
+ clawnify execute -c "console.log(1 + 1)"
1883
+ `
1884
+ );
1885
+ process.exit(1);
1886
+ }
1887
+ const timeout_ms = options.timeout ? Math.max(1e3, parseInt(options.timeout, 10) * 1e3) : 3e4;
1888
+ const resp = await callTool("clawnify.execute", { code, timeout_ms });
1889
+ if (isError(resp)) {
1890
+ process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}
1891
+ `);
1892
+ process.exit(1);
1893
+ }
1894
+ const sc = resp.result.structuredContent;
1895
+ if (sc) {
1896
+ if (sc.stdout) process.stdout.write(sc.stdout);
1897
+ if (sc.stderr) process.stderr.write(sc.stderr);
1898
+ if (sc.timed_out) {
1899
+ process.stderr.write(`
1900
+ [clawnify] timed out after ${timeout_ms}ms on ${sc.substrate_id}
1901
+ `);
1902
+ }
1903
+ process.exit(sc.exit_code ?? 0);
1904
+ }
1905
+ for (const c of resp.result.content) {
1906
+ if (c.type === "text") process.stdout.write(c.text + "\n");
1907
+ }
1908
+ process.exit(resp.result.isError ? 1 : 0);
1909
+ }
1910
+
1911
+ // src/commands/docs.ts
1912
+ var DOCS_URL = "https://clawnify-mcp-docs.workers.dev";
1913
+ async function docsCommand(slug, options) {
1914
+ const token = await getValidToken();
1915
+ if (!token) {
1916
+ process.stderr.write("Not logged in. Run `clawnify login` first.\n");
1917
+ process.exit(1);
1918
+ }
1919
+ const auth = loadAuth();
1920
+ if (!auth?.org_id) {
1921
+ process.stderr.write(
1922
+ "No active org. Pick one with `clawnify org use <slug-or-id>` first.\n"
1923
+ );
1924
+ process.exit(1);
1925
+ }
1926
+ const caller = options.caller ?? "external";
1927
+ const path7 = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;
1928
+ const res = await fetch(DOCS_URL + path7, {
1929
+ headers: {
1930
+ authorization: "Bearer " + token
1931
+ }
1932
+ });
1933
+ if (!res.ok) {
1934
+ process.stderr.write(`Failed to fetch docs: ${res.status} ${res.statusText}
1935
+ `);
1936
+ process.exit(1);
1937
+ }
1938
+ const md = await res.text();
1939
+ process.stdout.write(md);
1940
+ if (!md.endsWith("\n")) process.stdout.write("\n");
1941
+ }
1942
+
1943
+ // src/commands/mcp-bridge.ts
1944
+ import readline5 from "readline";
1945
+ var MCP_URL2 = "https://mcp.clawnify.com/mcp";
1946
+ async function mcpBridgeCommand() {
1947
+ const token = await getValidToken();
1948
+ if (!token) {
1949
+ process.stderr.write("Not logged in. Run `clawnify login` first.\n");
1950
+ process.exit(1);
1951
+ }
1952
+ const auth = loadAuth();
1953
+ const baseHeaders = {
1954
+ "content-type": "application/json",
1955
+ authorization: "Bearer " + token
1956
+ };
1957
+ if (auth?.org_id) {
1958
+ baseHeaders["X-Clawnify-Org-Id"] = auth.org_id;
1959
+ }
1960
+ const rl = readline5.createInterface({ input: process.stdin, terminal: false });
1961
+ rl.on("line", async (line) => {
1962
+ const trimmed = line.trim();
1963
+ if (!trimmed) return;
1964
+ let parsedId = null;
1965
+ try {
1966
+ parsedId = JSON.parse(trimmed).id ?? null;
1967
+ } catch {
1968
+ }
1969
+ try {
1970
+ const res = await fetch(MCP_URL2, {
1971
+ method: "POST",
1972
+ headers: baseHeaders,
1973
+ body: trimmed
1974
+ });
1975
+ const text = await res.text();
1976
+ if (text.length > 0) {
1977
+ process.stdout.write(text);
1978
+ if (!text.endsWith("\n")) process.stdout.write("\n");
1979
+ }
1980
+ } catch (err) {
1981
+ const errResp = {
1982
+ jsonrpc: "2.0",
1983
+ id: parsedId,
1984
+ error: { code: -32603, message: "bridge transport error: " + String(err) }
1985
+ };
1986
+ process.stdout.write(JSON.stringify(errResp) + "\n");
1987
+ }
1988
+ });
1989
+ rl.on("close", () => {
1990
+ process.exit(0);
1991
+ });
1992
+ }
1993
+
1994
+ // src/commands/sdk.ts
1995
+ async function sdkInspectCommand(slug, options) {
1996
+ await docsCommand(slug, { caller: options.caller ?? "external" });
1997
+ }
1998
+ async function sdkLoginCommand() {
1999
+ await loginCommand();
2000
+ }
2001
+ async function sdkInstallCommand() {
2002
+ process.stderr.write(
2003
+ "`clawnify sdk install` is not yet implemented.\nIt depends on the `@clawnify/sdk` npm package being published, which depends on the build-pipeline manifest writer (template-strategy.md).\nTrack in the Phase 5 follow-up.\n"
2004
+ );
2005
+ process.exit(1);
2006
+ }
2007
+
2008
+ // src/lib/skills/content.gen.ts
2009
+ var CLI_VERSION = "0.3.0";
2010
+ var BUNDLED_SKILLS = [
2011
+ {
2012
+ name: "build-a-clawnify-app",
2013
+ description: "Gold-standard structure for building Clawnify apps end-to-end (Hono + React + tRPC + @clawnify/db).",
2014
+ 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'
2015
+ }
2016
+ ];
2017
+
2018
+ // src/lib/skills/detect.ts
2019
+ import { statSync } from "fs";
2020
+ import { join } from "path";
2021
+ var DETECTORS = [
2022
+ { agent: "claude", markers: [".claude", ".claude.json", "CLAUDE.md"], target: ".claude/skills" },
2023
+ { agent: "cursor", markers: [".cursor", ".cursorrules"], target: ".cursor/rules" },
2024
+ { agent: "openclaw", markers: [".openclaw", "openclaw.json"], target: ".openclaw/skills" },
2025
+ { agent: "codex", markers: [".codex", "AGENTS.md"], target: ".codex/skills" },
2026
+ { agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
2027
+ ];
2028
+ function exists(cwd, name) {
2029
+ const path7 = join(cwd, name);
2030
+ try {
2031
+ statSync(path7);
2032
+ return true;
2033
+ } catch {
2034
+ return false;
2035
+ }
2036
+ }
2037
+ function detectAgents(cwd) {
2038
+ const found = [];
2039
+ for (const d of DETECTORS) {
2040
+ const hit = d.markers.find((m) => exists(cwd, m));
2041
+ if (hit) {
2042
+ found.push({ agent: d.agent, target: d.target, marker: hit });
2043
+ }
2044
+ }
2045
+ return found;
2046
+ }
2047
+ function agentByName(name) {
2048
+ const d = DETECTORS.find((x) => x.agent === name);
2049
+ if (!d) throw new Error(`Unknown agent: ${name}`);
2050
+ return { agent: d.agent, target: d.target, marker: "(forced)" };
2051
+ }
2052
+ var ALL_AGENTS = DETECTORS.map((d) => d.agent);
2053
+
2054
+ // src/lib/skills/install.ts
2055
+ import {
2056
+ existsSync as existsSync2,
2057
+ mkdirSync,
2058
+ readFileSync,
2059
+ writeFileSync,
2060
+ statSync as statSync2,
2061
+ rmSync,
2062
+ unlinkSync
2063
+ } from "fs";
2064
+ import { dirname, join as join2 } from "path";
2065
+ var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
2066
+ function versionHeader(name) {
2067
+ return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
2068
+ }
2069
+ function readExistingVersion(path7) {
2070
+ if (!existsSync2(path7)) return null;
2071
+ try {
2072
+ const head = readFileSync(path7, "utf8").slice(0, 500);
2073
+ const match = head.match(VERSION_HEADER_RE);
2074
+ return match ? match[2] : null;
2075
+ } catch {
2076
+ return null;
2077
+ }
2078
+ }
2079
+ function installSkill(skill, agent, cwd) {
2080
+ switch (agent.agent) {
2081
+ case "claude":
2082
+ return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);
2083
+ case "codex":
2084
+ return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);
2085
+ case "openclaw":
2086
+ return writeOpenclawSkill(skill, cwd, agent.target);
2087
+ case "cursor":
2088
+ return writeCursorRule(skill, cwd, agent.target);
2089
+ case "aider":
2090
+ return writeAiderSection(skill, cwd, agent.target);
2091
+ }
2092
+ }
2093
+ function formatClaudeSkill(skill) {
2094
+ return `${versionHeader(skill.name)}
2095
+ ---
2096
+ name: ${skill.name}
2097
+ description: ${JSON.stringify(skill.description)}
2098
+ ---
2099
+
2100
+ ${skill.content}`;
2101
+ }
2102
+ function formatCodexSkill(skill) {
2103
+ return formatClaudeSkill(skill);
2104
+ }
2105
+ function writeSkillDir(skill, cwd, targetDir, format) {
2106
+ const skillDir = join2(cwd, targetDir, skill.name);
2107
+ const filePath = join2(skillDir, "SKILL.md");
2108
+ const existing = readExistingVersion(filePath);
2109
+ if (existing === CLI_VERSION) {
2110
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
2111
+ }
2112
+ mkdirSync(skillDir, { recursive: true });
2113
+ writeFileSync(filePath, format(skill));
2114
+ return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
2115
+ }
2116
+ function writeOpenclawSkill(skill, cwd, targetDir) {
2117
+ const skillDir = join2(cwd, targetDir, skill.name);
2118
+ const mdPath = join2(skillDir, "SKILL.md");
2119
+ const jsonPath = join2(skillDir, "skill.json");
2120
+ const existing = readExistingVersion(mdPath);
2121
+ if (existing === CLI_VERSION) {
2122
+ return { status: "skipped", path: mdPath, reason: `already at v${CLI_VERSION}` };
2123
+ }
2124
+ mkdirSync(skillDir, { recursive: true });
2125
+ writeFileSync(mdPath, `${versionHeader(skill.name)}
2126
+ ${skill.content}`);
2127
+ writeFileSync(
2128
+ jsonPath,
2129
+ JSON.stringify(
2130
+ {
2131
+ name: skill.name,
2132
+ displayName: skill.name.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join(" "),
2133
+ description: skill.description,
2134
+ trigger: "manual",
2135
+ inputs: []
2136
+ },
2137
+ null,
2138
+ 2
2139
+ )
2140
+ );
2141
+ return existing ? { status: "updated", path: mdPath, previousVersion: existing } : { status: "installed", path: mdPath };
2142
+ }
2143
+ function writeCursorRule(skill, cwd, targetDir) {
2144
+ const dir = join2(cwd, targetDir);
2145
+ const filePath = join2(dir, `${skill.name}.mdc`);
2146
+ const existing = readExistingVersion(filePath);
2147
+ if (existing === CLI_VERSION) {
2148
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
2149
+ }
2150
+ mkdirSync(dir, { recursive: true });
2151
+ const body = `${versionHeader(skill.name)}
2152
+ ---
2153
+ description: ${JSON.stringify(skill.description)}
2154
+ alwaysApply: false
2155
+ ---
2156
+
2157
+ ${skill.content}`;
2158
+ writeFileSync(filePath, body);
2159
+ return existing ? { status: "updated", path: filePath, previousVersion: existing } : { status: "installed", path: filePath };
2160
+ }
2161
+ function writeAiderSection(skill, cwd, targetFile) {
2162
+ const filePath = join2(cwd, targetFile);
2163
+ const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;
2164
+ const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;
2165
+ const section = `${startMarker}
2166
+ ${versionHeader(skill.name)}
2167
+ ${skill.content}
2168
+ ${endMarker}
2169
+ `;
2170
+ let existing = "";
2171
+ let existingVersion = null;
2172
+ if (existsSync2(filePath)) {
2173
+ existing = readFileSync(filePath, "utf8");
2174
+ const sectionRe = new RegExp(
2175
+ `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
2176
+ );
2177
+ const sectionMatch = existing.match(sectionRe);
2178
+ if (sectionMatch) {
2179
+ const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);
2180
+ existingVersion = headMatch ? headMatch[2] : null;
2181
+ if (existingVersion === CLI_VERSION) {
2182
+ return { status: "skipped", path: filePath, reason: `already at v${CLI_VERSION}` };
2183
+ }
2184
+ const next = existing.replace(sectionRe, section);
2185
+ mkdirSync(dirname(filePath), { recursive: true });
2186
+ writeFileSync(filePath, next);
2187
+ return existingVersion ? { status: "updated", path: filePath, previousVersion: existingVersion } : { status: "installed", path: filePath };
2188
+ }
2189
+ }
2190
+ mkdirSync(dirname(filePath), { recursive: true });
2191
+ const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
2192
+ writeFileSync(filePath, existing + prefix + section);
2193
+ return { status: "installed", path: filePath };
2194
+ }
2195
+ function escapeRe(s) {
2196
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2197
+ }
2198
+ function removeSkill(skillName, agent, cwd) {
2199
+ if (agent.agent === "aider") {
2200
+ const filePath = join2(cwd, agent.target);
2201
+ if (!existsSync2(filePath)) return false;
2202
+ const content = readFileSync(filePath, "utf8");
2203
+ const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;
2204
+ const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;
2205
+ const sectionRe = new RegExp(
2206
+ `${escapeRe(startMarker)}[\\s\\S]*?${escapeRe(endMarker)}\\n?`
2207
+ );
2208
+ if (!sectionRe.test(content)) return false;
2209
+ writeFileSync(filePath, content.replace(sectionRe, ""));
2210
+ return true;
2211
+ }
2212
+ if (agent.agent === "cursor") {
2213
+ const candidate = join2(cwd, agent.target, `${skillName}.mdc`);
2214
+ if (!existsSync2(candidate)) return false;
2215
+ unlinkSync(candidate);
2216
+ return true;
2217
+ }
2218
+ const dir = join2(cwd, agent.target, skillName);
2219
+ if (!existsSync2(dir)) return false;
2220
+ try {
2221
+ const s = statSync2(dir);
2222
+ if (!s.isDirectory()) return false;
2223
+ } catch {
2224
+ return false;
2225
+ }
2226
+ rmSync(dir, { recursive: true, force: true });
2227
+ return true;
2228
+ }
2229
+
2230
+ // src/commands/skills.ts
2231
+ function skillsListCommand() {
2232
+ console.log(`Clawnify skills (v${CLI_VERSION}):
2233
+ `);
2234
+ for (const s of BUNDLED_SKILLS) {
2235
+ console.log(` ${s.name}`);
2236
+ console.log(` ${s.description}
2237
+ `);
2238
+ }
2239
+ console.log(`Add one: clawnify skills add <name>`);
2240
+ console.log(`Add all: clawnify skills add --all`);
2241
+ console.log(`Remove: clawnify skills remove <name>`);
2242
+ }
2243
+ async function skillsAddCommand(name, opts) {
2244
+ const skills = resolveSkills(name, opts.all);
2245
+ if (skills.length === 0) {
2246
+ console.error("No skill specified. Pass a name or --all. See `clawnify skills list`.");
2247
+ process.exit(1);
2248
+ }
2249
+ const agents = resolveAgents(opts.agent);
2250
+ if (agents.length === 0) {
2251
+ console.error(
2252
+ "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>."
2253
+ );
2254
+ process.exit(1);
2255
+ }
2256
+ const cwd = process.cwd();
2257
+ console.log(
2258
+ `Installing ${skills.length} skill${skills.length === 1 ? "" : "s"} into ${agents.length} agent${agents.length === 1 ? "" : "s"}:`
2259
+ );
2260
+ console.log(` CLI version: v${CLI_VERSION}`);
2261
+ console.log(
2262
+ ` Agents: ${agents.map((a) => `${a.agent} (${a.marker})`).join(", ")}
2263
+ `
2264
+ );
2265
+ let installed = 0;
2266
+ let updated = 0;
2267
+ let skipped = 0;
2268
+ for (const skill of skills) {
2269
+ for (const agent of agents) {
2270
+ const result = installSkill(skill, agent, cwd);
2271
+ if (result.status === "installed") {
2272
+ installed++;
2273
+ console.log(` \u2713 ${skill.name} \u2192 ${result.path}`);
2274
+ } else if (result.status === "updated") {
2275
+ updated++;
2276
+ console.log(
2277
+ ` \u2191 ${skill.name} \u2192 ${result.path} (v${result.previousVersion} \u2192 v${CLI_VERSION})`
2278
+ );
2279
+ } else {
2280
+ skipped++;
2281
+ console.log(` \xB7 ${skill.name} \u2192 ${result.path} (${result.reason})`);
2282
+ }
2283
+ }
2284
+ }
2285
+ console.log(
2286
+ `
2287
+ Done \u2014 ${installed} installed, ${updated} updated, ${skipped} unchanged.`
2288
+ );
2289
+ }
2290
+ async function skillsRemoveCommand(name, opts) {
2291
+ const skills = resolveSkills(name, opts.all);
2292
+ if (skills.length === 0) {
2293
+ console.error("No skill specified. Pass a name or --all.");
2294
+ process.exit(1);
2295
+ }
2296
+ const agents = resolveAgents(opts.agent);
2297
+ if (agents.length === 0) {
2298
+ console.error("No coding agent detected. Nothing to remove.");
2299
+ return;
2300
+ }
2301
+ const cwd = process.cwd();
2302
+ let removed = 0;
2303
+ for (const skill of skills) {
2304
+ for (const agent of agents) {
2305
+ if (removeSkill(skill.name, agent, cwd)) {
2306
+ removed++;
2307
+ console.log(` \u2717 ${skill.name} removed from ${agent.agent}`);
2308
+ }
2309
+ }
2310
+ }
2311
+ console.log(`
2312
+ Done \u2014 removed ${removed} file${removed === 1 ? "" : "s"}.`);
2313
+ }
2314
+ function resolveSkills(name, all) {
2315
+ if (all) return [...BUNDLED_SKILLS];
2316
+ if (!name) return [];
2317
+ const match = BUNDLED_SKILLS.find((s) => s.name === name);
2318
+ if (!match) {
2319
+ console.error(
2320
+ `Unknown skill: ${name}
2321
+ Available: ${BUNDLED_SKILLS.map((s) => s.name).join(", ")}`
2322
+ );
2323
+ process.exit(1);
2324
+ }
2325
+ return [match];
2326
+ }
2327
+ function resolveAgents(forced) {
2328
+ if (forced) {
2329
+ if (!ALL_AGENTS.includes(forced)) {
2330
+ console.error(
2331
+ `Unknown agent: ${forced}
2332
+ Valid: ${ALL_AGENTS.join(", ")}`
2333
+ );
2334
+ process.exit(1);
2335
+ }
2336
+ return [agentByName(forced)];
2337
+ }
2338
+ return detectAgents(process.cwd());
2339
+ }
2340
+
1563
2341
  // src/cli.ts
1564
2342
  function runCli() {
1565
2343
  const program = new Command();
1566
2344
  program.name("clawnify").description("Deploy apps to Clawnify").version("0.1.0");
1567
- program.command("init [dir]").description("Scaffold a new Clawnify app").option("--name <name>", "App name (skips prompt)").option("--template <template>", "Template: blank or crud (skips prompt)").option("--storage", "Enable file uploads (R2)").action(initCommand);
2345
+ 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").action(initCommand);
1568
2346
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
1569
2347
  program.command("login").description("Authenticate with Clawnify").action(loginCommand);
1570
- program.command("deploy [dir]").description("Deploy an app 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);
2348
+ 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);
1571
2349
  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);
1572
2350
  const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
1573
2351
  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);
@@ -1579,9 +2357,20 @@ function runCli() {
1579
2357
  program.command("rm <app-id>").description("Delete an app").action(rmCommand);
1580
2358
  program.command("open <slug>").description("Open an app in the browser").action(openCommand);
1581
2359
  program.command("whoami").description("Show current user info").action(whoamiCommand);
2360
+ program.command("execute [file]").description("Run TypeScript code on the active org's substrate via mcp.clawnify.com").option("-c, --code <inline>", "Inline code instead of a file path").option("--timeout <seconds>", "Execution timeout in seconds (default 30)").action(executeCommand);
2361
+ program.command("docs [slug]").description("Fetch the skill-convention README for an app (or org index if slug omitted)").option("--caller <hint>", "Caller density hint: internal | dashboard | external", "external").action(docsCommand);
2362
+ program.command("mcp").description("Run a stdio MCP bridge that proxies to mcp.clawnify.com (for Claude Desktop / ChatGPT / bash-less clients)").action(mcpBridgeCommand);
2363
+ const skills = program.command("skills").description("Install Clawnify-curated skills into your coding agent(s)");
2364
+ skills.command("list").description("List available skills").action(skillsListCommand);
2365
+ 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));
2366
+ 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));
2367
+ const sdk = program.command("sdk").description("Inspect and manage the per-org SDK surface");
2368
+ 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);
2369
+ sdk.command("login").description("Authenticate / rotate the OAuth grant (alias of `clawnify login`)").action(sdkLoginCommand);
2370
+ sdk.command("install").description("(Deferred) Install @clawnify/sdk locally \u2014 pending Phase 5b").action(sdkInstallCommand);
1582
2371
  program.parse();
1583
2372
  }
1584
2373
  export {
1585
2374
  runCli
1586
2375
  };
1587
- //# sourceMappingURL=cli-I45E7PD2.js.map
2376
+ //# sourceMappingURL=cli-P6F6JKMF.js.map