clawnify 0.14.0 → 0.16.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/dist/{chunk-PXJCILKN.js → chunk-6NPBW4NU.js} +25 -29
- package/dist/chunk-6NPBW4NU.js.map +1 -0
- package/dist/{cli-HOXCM3I2.js → cli-G6ZBPA6D.js} +316 -37
- package/dist/cli-G6ZBPA6D.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{mcp-ZERLZFD6.js → mcp-IA7KEV4T.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-PXJCILKN.js.map +0 -1
- package/dist/cli-HOXCM3I2.js.map +0 -1
- /package/dist/{mcp-ZERLZFD6.js.map → mcp-IA7KEV4T.js.map} +0 -0
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
resolveOrgContext,
|
|
21
21
|
saveAuth,
|
|
22
22
|
saveProject
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-6NPBW4NU.js";
|
|
24
24
|
|
|
25
25
|
// src/cli.ts
|
|
26
26
|
import { Command, Option } from "commander";
|
|
@@ -180,6 +180,71 @@ import path2 from "path";
|
|
|
180
180
|
import readline2 from "readline";
|
|
181
181
|
import { spawn } from "child_process";
|
|
182
182
|
|
|
183
|
+
// src/lib/anon.ts
|
|
184
|
+
function isLoggedOut() {
|
|
185
|
+
return !process.env.CLAWNIFY_TOKEN && !loadAuth();
|
|
186
|
+
}
|
|
187
|
+
function anonExpired(ctx) {
|
|
188
|
+
return new Date(ctx.claim_expires_at).getTime() <= Date.now();
|
|
189
|
+
}
|
|
190
|
+
function saveAnon(dir, ctx, extra = {}) {
|
|
191
|
+
const existing = readProject(dir) ?? {};
|
|
192
|
+
saveProject(dir, { ...existing, ...extra, org_id: ctx.org_id, anon: ctx });
|
|
193
|
+
}
|
|
194
|
+
function clearAnon(dir) {
|
|
195
|
+
const existing = readProject(dir);
|
|
196
|
+
if (!existing?.anon) return;
|
|
197
|
+
const { anon: _anon, app_id: _a, website_id: _w, slug: _s, ...rest } = existing;
|
|
198
|
+
saveProject(dir, rest);
|
|
199
|
+
}
|
|
200
|
+
async function getOrCreateAnonContext(dir, name) {
|
|
201
|
+
const existing = readProject(dir)?.anon;
|
|
202
|
+
if (existing && !anonExpired(existing)) {
|
|
203
|
+
return { ctx: existing, created: false };
|
|
204
|
+
}
|
|
205
|
+
if (existing) clearAnon(dir);
|
|
206
|
+
const res = await api.request("POST", "/claims/orgs", { body: { name } });
|
|
207
|
+
if (!res.ok) {
|
|
208
|
+
const err = await res.json().catch(() => ({}));
|
|
209
|
+
console.error(
|
|
210
|
+
`Could not start an anonymous deploy: ${err.error || res.statusText}
|
|
211
|
+
You can always deploy signed in: clawnify login`
|
|
212
|
+
);
|
|
213
|
+
process.exit(1);
|
|
214
|
+
}
|
|
215
|
+
const data = await res.json();
|
|
216
|
+
const ctx = {
|
|
217
|
+
org_id: data.org_id,
|
|
218
|
+
deploy_token: data.deploy_token,
|
|
219
|
+
claim_url: data.claim_url,
|
|
220
|
+
claim_expires_at: data.claim_expires_at
|
|
221
|
+
};
|
|
222
|
+
saveAnon(dir, ctx);
|
|
223
|
+
return { ctx, created: true };
|
|
224
|
+
}
|
|
225
|
+
async function anonPostForm(path10, formData, ctx) {
|
|
226
|
+
return api.request("POST", path10, { formData, token: ctx.deploy_token });
|
|
227
|
+
}
|
|
228
|
+
function explainAnonUnauthorized(dir) {
|
|
229
|
+
clearAnon(dir);
|
|
230
|
+
console.error(
|
|
231
|
+
"This temporary workspace is no longer writable (claimed or expired).\n Run `clawnify deploy` again to start a fresh one, or sign in: clawnify login"
|
|
232
|
+
);
|
|
233
|
+
process.exit(1);
|
|
234
|
+
}
|
|
235
|
+
function printClaimBlock(ctx) {
|
|
236
|
+
const hoursLeft = Math.max(
|
|
237
|
+
1,
|
|
238
|
+
Math.round((new Date(ctx.claim_expires_at).getTime() - Date.now()) / 36e5)
|
|
239
|
+
);
|
|
240
|
+
console.log(
|
|
241
|
+
` Keep it: ${ctx.claim_url}
|
|
242
|
+
Sign in with Google there to make this workspace yours.
|
|
243
|
+
Unclaimed workspaces are deleted after ~${hoursLeft}h.
|
|
244
|
+
`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
183
248
|
// src/lib/sync-schema.ts
|
|
184
249
|
import fs from "fs/promises";
|
|
185
250
|
import path from "path";
|
|
@@ -316,12 +381,29 @@ function ask(question) {
|
|
|
316
381
|
});
|
|
317
382
|
});
|
|
318
383
|
}
|
|
384
|
+
async function postFormWithRetry(path10, formData, orgId, attempts = 3) {
|
|
385
|
+
let lastErr;
|
|
386
|
+
for (let i = 0; i < attempts; i++) {
|
|
387
|
+
try {
|
|
388
|
+
return await api.postForm(path10, formData, { orgId });
|
|
389
|
+
} catch (err) {
|
|
390
|
+
lastErr = err;
|
|
391
|
+
if (i === attempts - 1) break;
|
|
392
|
+
const waitMs = 1e3 * 2 ** i;
|
|
393
|
+
console.warn(
|
|
394
|
+
` upload failed (${String(err).slice(0, 120)}) \u2014 retrying in ${waitMs / 1e3}s [${i + 2}/${attempts}]`
|
|
395
|
+
);
|
|
396
|
+
await new Promise((r) => setTimeout(r, waitMs));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
throw lastErr;
|
|
400
|
+
}
|
|
319
401
|
async function uploadDeploy(archive, name, framework, orgId) {
|
|
320
402
|
const formData = new FormData();
|
|
321
403
|
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
322
404
|
formData.append("name", name);
|
|
323
405
|
formData.append("framework", framework);
|
|
324
|
-
const res = await
|
|
406
|
+
const res = await postFormWithRetry("/v1/apps/deploy", formData, orgId);
|
|
325
407
|
if (res.ok) {
|
|
326
408
|
const data = await res.json();
|
|
327
409
|
return { ok: true, data };
|
|
@@ -336,7 +418,7 @@ async function uploadDeploy(archive, name, framework, orgId) {
|
|
|
336
418
|
async function uploadRedeploy(appId, archive, orgId) {
|
|
337
419
|
const formData = new FormData();
|
|
338
420
|
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
339
|
-
const res = await
|
|
421
|
+
const res = await postFormWithRetry(`/v1/apps/${appId}/redeploy`, formData, orgId);
|
|
340
422
|
if (res.ok) {
|
|
341
423
|
const data = await res.json();
|
|
342
424
|
return { ok: true, data };
|
|
@@ -510,6 +592,54 @@ async function deployWebsite(dir, options) {
|
|
|
510
592
|
const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
|
|
511
593
|
const linkedProject = readProject(resolvedDir);
|
|
512
594
|
const { archive, files } = createArchive(resolvedDir);
|
|
595
|
+
if (isLoggedOut() && !options.org) {
|
|
596
|
+
if (options.dryRun) {
|
|
597
|
+
const sizeKB = (archive.length / 1024).toFixed(1);
|
|
598
|
+
console.log(`
|
|
599
|
+
Dry run \u2014 would deploy website '${baseName}' anonymously (astro)`);
|
|
600
|
+
console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped
|
|
601
|
+
`);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
const { ctx, created } = await getOrCreateAnonContext(resolvedDir, baseName);
|
|
605
|
+
console.log(
|
|
606
|
+
created ? `No account detected \u2014 deploying ${baseName} to a temporary workspace...` : `Updating ${baseName} (temporary workspace)...`
|
|
607
|
+
);
|
|
608
|
+
const formData = new FormData();
|
|
609
|
+
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
610
|
+
formData.append("name", baseName);
|
|
611
|
+
const res = await anonPostForm("/v1/anon/websites/deploy", formData, ctx);
|
|
612
|
+
if (res.status === 401) explainAnonUnauthorized(resolvedDir);
|
|
613
|
+
if (!res.ok) {
|
|
614
|
+
const err = await res.json().catch(() => ({}));
|
|
615
|
+
console.error(`Deploy failed: ${err.error || res.statusText}`);
|
|
616
|
+
process.exit(1);
|
|
617
|
+
}
|
|
618
|
+
const data = await res.json();
|
|
619
|
+
saveProject(resolvedDir, {
|
|
620
|
+
...readProject(resolvedDir) ?? {},
|
|
621
|
+
kind: "website",
|
|
622
|
+
org_id: ctx.org_id,
|
|
623
|
+
website_id: data.website_id,
|
|
624
|
+
slug: data.slug,
|
|
625
|
+
anon: ctx
|
|
626
|
+
});
|
|
627
|
+
const polled2 = await pollUntilReady(data.website_id, {
|
|
628
|
+
kind: "website",
|
|
629
|
+
anonToken: ctx.deploy_token
|
|
630
|
+
});
|
|
631
|
+
if (polled2.status === "error" || polled2.status === "failed") {
|
|
632
|
+
console.error(`
|
|
633
|
+
Deploy failed: ${polled2.error || "Unknown error"}
|
|
634
|
+
`);
|
|
635
|
+
process.exit(1);
|
|
636
|
+
}
|
|
637
|
+
console.log(`
|
|
638
|
+
\u2713 Deployed to a private draft.
|
|
639
|
+
`);
|
|
640
|
+
printClaimBlock(ctx);
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
513
643
|
let orgId;
|
|
514
644
|
if (options.org) {
|
|
515
645
|
const orgs = await listMyOrgs();
|
|
@@ -699,6 +829,12 @@ async function deployCommand(dir, options = {}) {
|
|
|
699
829
|
process.exit(EXIT_USAGE);
|
|
700
830
|
}
|
|
701
831
|
}
|
|
832
|
+
if (!manifest && (fs2.existsSync(path2.join(resolvedDir, "astro.config.mjs")) || fs2.existsSync(path2.join(resolvedDir, "astro.config.ts"))) && fs2.existsSync(path2.join(resolvedDir, "src", "tree"))) {
|
|
833
|
+
console.error(
|
|
834
|
+
'This looks like a Clawnify website, but it has no clawnify.json so it\ncannot be told apart from an app \u2014 deploying it as one creates a broken app.\n\n Add a clawnify.json here:\n { "version": 1, "name": "website", "website": { "framework": "astro" } }\n\n Or push to the synced workspace repo, which rebuilds the site for you.'
|
|
835
|
+
);
|
|
836
|
+
process.exit(EXIT_USAGE);
|
|
837
|
+
}
|
|
702
838
|
}
|
|
703
839
|
let appId;
|
|
704
840
|
let slug;
|
|
@@ -708,16 +844,18 @@ async function deployCommand(dir, options = {}) {
|
|
|
708
844
|
if (options.from) {
|
|
709
845
|
const repo = options.from.replace(/^github:/, "");
|
|
710
846
|
const subdir = options.path?.trim().replace(/^\/+|\/+$/g, "") || void 0;
|
|
847
|
+
const fromDir = process.cwd();
|
|
848
|
+
const orgId = await resolveOrgId(options, readProject(fromDir), fromDir);
|
|
711
849
|
if (options.dryRun) {
|
|
712
850
|
console.log(
|
|
713
851
|
`
|
|
714
852
|
Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : ""}${options.name ? `, name: ${options.name}` : ""})
|
|
853
|
+
Target org: ${orgId ?? "(unresolved \u2014 would use your default org)"}
|
|
715
854
|
`
|
|
716
855
|
);
|
|
717
856
|
return;
|
|
718
857
|
}
|
|
719
858
|
console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : ""}...`);
|
|
720
|
-
const orgId = options.org ? await resolveOrgId(options, null) : void 0;
|
|
721
859
|
let result2 = await repoDeploy({ repo, subdir, name: options.name, orgId });
|
|
722
860
|
if (!result2.ok && "conflict" in result2) {
|
|
723
861
|
const decision = await resolveConflictDecision(options, result2.conflict);
|
|
@@ -759,7 +897,55 @@ async function deployCommand(dir, options = {}) {
|
|
|
759
897
|
const framework = manifest?.app?.framework || "vite-preact";
|
|
760
898
|
const linkedProject = readProject(resolvedDir);
|
|
761
899
|
await regenerateDrizzleMigrations(resolvedDir);
|
|
900
|
+
assertDatabaseDdlPresent(resolvedDir, manifest);
|
|
762
901
|
const { archive, files } = createArchive(resolvedDir);
|
|
902
|
+
if (isLoggedOut() && !options.org) {
|
|
903
|
+
if (options.dryRun) {
|
|
904
|
+
summarizeArchive(archive, files, framework, baseName);
|
|
905
|
+
console.log(` Would deploy anonymously into a temporary workspace
|
|
906
|
+
`);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const { ctx, created } = await getOrCreateAnonContext(resolvedDir, baseName);
|
|
910
|
+
const isUpdate = Boolean(linkedProject?.app_id && linkedProject?.anon);
|
|
911
|
+
console.log(
|
|
912
|
+
created ? `No account detected \u2014 deploying ${baseName} to a temporary workspace...` : isUpdate ? `Updating ${baseName} (temporary workspace)...` : `Deploying ${baseName} (temporary workspace)...`
|
|
913
|
+
);
|
|
914
|
+
const formData = new FormData();
|
|
915
|
+
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
916
|
+
formData.append("name", baseName);
|
|
917
|
+
formData.append("framework", framework);
|
|
918
|
+
const anonPath = isUpdate ? `/v1/anon/apps/${linkedProject.app_id}/redeploy` : "/v1/anon/apps/deploy";
|
|
919
|
+
const res = await anonPostForm(anonPath, formData, ctx);
|
|
920
|
+
if (res.status === 401) explainAnonUnauthorized(resolvedDir);
|
|
921
|
+
if (!res.ok) {
|
|
922
|
+
const err = await res.json().catch(() => ({}));
|
|
923
|
+
console.error(`Deploy failed: ${err.error || res.statusText}`);
|
|
924
|
+
process.exit(1);
|
|
925
|
+
}
|
|
926
|
+
const data = await res.json();
|
|
927
|
+
saveProject(resolvedDir, {
|
|
928
|
+
...readProject(resolvedDir) ?? {},
|
|
929
|
+
org_id: ctx.org_id,
|
|
930
|
+
app_id: data.app_id,
|
|
931
|
+
slug: data.slug,
|
|
932
|
+
app_token: data.app_token,
|
|
933
|
+
anon: ctx
|
|
934
|
+
});
|
|
935
|
+
const polled = await pollUntilReady(data.app_id, { anonToken: ctx.deploy_token });
|
|
936
|
+
if (polled.status === "error") {
|
|
937
|
+
console.error(`
|
|
938
|
+
Deploy failed: ${polled.error || "Unknown error"}
|
|
939
|
+
`);
|
|
940
|
+
process.exit(1);
|
|
941
|
+
}
|
|
942
|
+
console.log(`
|
|
943
|
+
\u2713 Deployed (private link):`);
|
|
944
|
+
console.log(` https://${data.slug}.apps.clawnify.com?token=${data.app_token}
|
|
945
|
+
`);
|
|
946
|
+
printClaimBlock(ctx);
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
763
949
|
const orgId = await resolveOrgId(options, linkedProject, resolvedDir);
|
|
764
950
|
if (options.dryRun) {
|
|
765
951
|
summarizeArchive(archive, files, framework, baseName);
|
|
@@ -892,9 +1078,34 @@ async function regenerateDrizzleMigrations(resolvedDir) {
|
|
|
892
1078
|
}
|
|
893
1079
|
resolve();
|
|
894
1080
|
});
|
|
895
|
-
proc.on("error", () =>
|
|
1081
|
+
proc.on("error", (err) => {
|
|
1082
|
+
console.warn(` warning: could not run drizzle-kit generate (${String(err).slice(0, 160)}).`);
|
|
1083
|
+
resolve();
|
|
1084
|
+
});
|
|
896
1085
|
});
|
|
897
1086
|
}
|
|
1087
|
+
function assertDatabaseDdlPresent(resolvedDir, manifest) {
|
|
1088
|
+
if (!manifest?.app?.database) return;
|
|
1089
|
+
const hasSchemaSql = fs2.existsSync(path2.join(resolvedDir, "schema.sql")) || fs2.existsSync(path2.join(resolvedDir, "src/server/schema.sql"));
|
|
1090
|
+
if (hasSchemaSql) return;
|
|
1091
|
+
const drizzleDir = path2.join(resolvedDir, ".clawnify", "drizzle");
|
|
1092
|
+
const hasDrizzleSql = fs2.existsSync(drizzleDir) && fs2.readdirSync(drizzleDir).some((f) => f.endsWith(".sql"));
|
|
1093
|
+
if (hasDrizzleSql) return;
|
|
1094
|
+
console.error(
|
|
1095
|
+
`Deploy aborted: this app sets "database": true in clawnify.json, but no schema
|
|
1096
|
+
would be applied \u2014 so every query would fail at runtime with "no such table".
|
|
1097
|
+
|
|
1098
|
+
Fix:
|
|
1099
|
+
\u2022 pnpm db:generate (emits .clawnify/drizzle/*.sql from src/server/schema.ts)
|
|
1100
|
+
If that just failed, see the warning above \u2014 drizzle-kit ships as a
|
|
1101
|
+
devDependency, so run your package manager's install first.
|
|
1102
|
+
\u2022 set "database": false (if this app genuinely has no database)
|
|
1103
|
+
|
|
1104
|
+
schema.ts is the source of truth; a hand-written schema.sql at the app root
|
|
1105
|
+
is also accepted, but only for apps not using Drizzle.`
|
|
1106
|
+
);
|
|
1107
|
+
process.exit(1);
|
|
1108
|
+
}
|
|
898
1109
|
|
|
899
1110
|
// src/commands/ls.ts
|
|
900
1111
|
async function lsCommand() {
|
|
@@ -1345,7 +1556,7 @@ async function whoamiCommand() {
|
|
|
1345
1556
|
}
|
|
1346
1557
|
const email = getEmailFromToken(envToken ?? auth.access_token) ?? "unknown";
|
|
1347
1558
|
console.log(`Email: ${email}`);
|
|
1348
|
-
const orgId =
|
|
1559
|
+
const orgId = await resolveOrgContext();
|
|
1349
1560
|
if (orgId) {
|
|
1350
1561
|
console.log(`Org: ${orgId}`);
|
|
1351
1562
|
}
|
|
@@ -1413,13 +1624,18 @@ function agentByName(name) {
|
|
|
1413
1624
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
1414
1625
|
|
|
1415
1626
|
// src/lib/skills/content.gen.ts
|
|
1416
|
-
var CLI_VERSION = "0.
|
|
1627
|
+
var CLI_VERSION = "0.16.0";
|
|
1417
1628
|
var BUNDLED_SKILLS = [
|
|
1418
1629
|
{
|
|
1419
1630
|
name: "build-a-clawnify-app",
|
|
1420
1631
|
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts (typed queries) kept in sync with schema.sql (the DDL the deploy applies), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and platform-injected identity via user()/orgId()/caller(). Use when building or modifying an app that deploys to the Clawnify platform.",
|
|
1421
1632
|
content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare exactly what `clawnify init` scaffolds and what the platform\nexpects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\n identity) + Tailwind v4. Nothing else.\n- **Schema lives in two files kept in sync** \u2014 `schema.ts` (Drizzle\n DSL, the typed view your queries use) and `schema.sql` (the DDL the\n deploy applies to your app\'s D1). Change one, change the other.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **API routes are `OpenAPIHono` + `createRoute`** \u2014 Zod-validated\n request/response.\n- **`createApp()`** (from `@clawnify/app`) builds the entry \u2014 it returns an\n `OpenAPIHono` with API discovery already mounted (`/api/openapi.json` +\n `/llms.txt`, generated from your live routes). That descriptor *is* the\n tool surface agents discover. Never hand-write those routes.\n- **One import.** `@clawnify/app` re-exports `createRoute`, `z` and\n `OpenAPIHono`, and adds `user` / `orgId` / `caller`. Import from it, not\n from `@clawnify/routes` directly.\n- **`clawnify.json`** declares framework, env, and public routes.\n There is no `api.tools[]` \u2014 the agent discovers and calls your\n endpoints via `/llms.txt` (and the OpenAPI spec).\n- **Identity is injected by the platform** \u2014 read it with `user(c)` /\n `orgId(c)` / `caller(c)` from `@clawnify/app`. Your app never\n authenticates anyone.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\n`blank` template (one GET route + a page) or a `crud` template (a\ntable with list/create/update/delete + a form). Both share the exact\nsame stack below.\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 \u2190 @vitejs/plugin-react + @tailwindcss/vite; proxies /api \u2192 :8787\n index.html\n .gitignore\n .clawnify/ \u2190 CLI cache (gitignored)\n wrangler.toml \u2190 Generated per-dev wrangler config\n src/\n server/\n index.ts \u2190 OpenAPIHono entry \u2014 mounts routes, serves /api/openapi.json\n routes.ts \u2190 OpenAPIHono + createRoute definitions \u2014 the API surface\n schema.ts \u2190 Drizzle table definitions (typed view for queries)\n schema.sql \u2190 canonical DDL the deploy applies \u2014 keep in sync with schema.ts\n worker-env.d.ts \u2190 Cloudflare Workers types reference\n uploads.ts \u2190 R2 helpers (only when storage is enabled)\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component (plain fetch against /api/*)\n index.css \u2190 @import "tailwindcss"\n```\n\n## Schema \u2014 `schema.ts` + `schema.sql`, kept in sync\n\nTwo files describe the same tables. `schema.ts` (Drizzle DSL) is the\ntyped view your queries compile against; `schema.sql` is the DDL the\ndeploy applies to your app\'s D1. **When you change one, update the\nother** \u2014 they must describe the same tables.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```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## `schema.sql` \u2014 the DDL the deploy applies\n\nAlongside `schema.ts`, keep a `schema.sql` describing the same tables.\nThis is the DDL applied to your app\'s database on deploy.\n\n```sql\n-- src/server/schema.sql (mirror of the schema.ts tables)\nCREATE TABLE IF NOT EXISTS notes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n org_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL DEFAULT \'\',\n tags TEXT NOT NULL DEFAULT \'[]\', -- JSON column\n created_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS notes_by_org ON notes(org_id, created_at);\n```\n\nRules:\n- Always `CREATE TABLE IF NOT EXISTS` \u2014 the apply is additive and\n re-run-safe.\n- Add a new column with `ALTER TABLE <t> ADD COLUMN \u2026` at the **end** of\n `schema.sql`, and reflect it in `schema.ts`. The deploy adds it.\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- **Never let `schema.ts` and `schema.sql` drift.** Change one, change\n the other \u2014 they must describe the same tables.\n\n## `src/server/index.ts` \u2014 the entry\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database } };\n\n// db:false \u2014 this app reads the database per request via getDB(c.env),\n// which needs no init middleware.\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.route("/", api);\n\nexport default app;\n```\n\nThe entry is thin: `createApp()` then mount your routes. `createApp`\nreturns an `OpenAPIHono` with **API discovery already mounted** \u2014 it\nserves both `/api/openapi.json` (generated from your `createRoute`\ndefinitions, with schemas) **and** `/llms.txt` (the same, agent-readable).\nAny `/api/*` route written as a plain `app.get` with no `createRoute` is\nstill listed from the live route table, so the endpoint inventory is\nalways complete. **Never hand-write a `/openapi.json` or `/llms.txt`\nhandler** \u2014 and don\'t call `mountDiscovery` yourself; `createApp` did it.\n\nWhen storage (file uploads) is enabled, the entry also wires the R2\nbucket in a middleware before mounting routes:\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 routes with `createRoute`\n\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\ndefinition paired with a handler via `api.openapi(route, handler)`.\nRequest bodies and params are Zod-validated (`c.req.valid("json")`,\n`c.req.valid("param")`); response shapes are declared with\n`.openapi("Name")` Zod schemas so they land in the generated spec.\n\nBlank template \u2014 one read route:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@clawnify/app";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@clawnify/app";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \u2014 a vague summary makes your endpoint invisible in practice.\n- **Validate input with Zod** via `request.body` / `request.params`\n and read it with `c.req.valid("json")` / `c.req.valid("param")`.\n Never parse `c.req.raw` by hand.\n- **Declare response shapes** with `.openapi("Name")` schemas \u2014 they\n become the documented return type in the spec.\n- **Filter by the org** on every user-facing query (see "who is\n calling" below). No exceptions.\n\n## `src/server` \u2014 who is calling\n\nThe platform authenticates every caller at its perimeter and injects a\nverified identity onto the request (it strips any client-supplied\nversion first, so it can\'t be spoofed). Your app never authenticates\nanyone: no `Authorization`, no cookies, no JWT, no login screen.\n\nRead it with the helpers from `@clawnify/app` \u2014 don\'t parse headers\nyourself:\n\n```ts\nimport { user, orgId, caller } from "@clawnify/app";\n\napp.get("/api/notes", async (c) => {\n const org = orgId(c);\n if (!org) return c.json({ error: "unauthorized" }, 401);\n\n const db = getDB(c.env, { schema });\n return c.json(\n await db.select().from(schema.notes).where(eq(schema.notes.orgId, org)),\n );\n});\n```\n\n| Helper | Returns |\n|--------|---------|\n| `orgId(c)` | Organization UUID \u2014 the tenant key. Filter every user-facing query by it. |\n| `user(c)` | `{ id, email, name, avatarUrl, firstName, lastName }` \u2014 or **`null`** when the caller isn\'t a person. |\n| `caller(c)` | `user`, `api`, `agent`, `agent-browser`, `public`, `bypass`, `system`, or `app`. |\n\nTwo rules that catch people out:\n\n- **`user(c)` is null for five of the eight caller kinds**\n (`agent-browser`, `public`, `bypass`, `system`, `app`). Always handle\n the null case \u2014 don\'t assume a person is present just because a\n request arrived. For per-user rows, store `user(c).id` in a `user_id`\n column and filter on it, exactly as you filter on `org_id`.\n- **`firstName` / `lastName` are a heuristic** split of a single stored\n full name (first word / the rest). Fine for a greeting; never persist\n them or treat them as someone\'s legal name \u2014 store `name`.\n\nDon\'t build app-level users, roles, or permissions. Authorization\nalready happened at the perimeter.\n\n## `src/client` \u2014 React + plain fetch\n\nThe client mounts React and talks to the API with plain `fetch`\nagainst the `/api/*` routes. No data-layer library is scaffolded.\n\n```tsx\n// src/client/main.tsx\nimport { StrictMode } from "react";\nimport { createRoot } from "react-dom/client";\nimport { App } from "./app";\nimport "./index.css";\n\ncreateRoot(document.getElementById("app")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n```\n\n```tsx\n// src/client/app.tsx (CRUD template shape)\nimport { useState, useEffect } from "react";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState("");\n\n async function load() {\n const res = await fetch("/api/items");\n setItems(await res.json());\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch("/api/items", {\n method: "POST",\n headers: { "Content-Type": "application/json" },\n body: JSON.stringify({ title }),\n });\n setTitle("");\n load();\n }\n\n // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\n\n return (\n <div className="max-w-xl mx-auto mt-10 px-4">\n {/* form + list */}\n </div>\n );\n}\n```\n\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\n`vite.config.ts`), so the same relative fetch paths work in dev and\nin production. The API is the one contract: the UI calls it over\n`fetch`, and the agent calls it over the OpenAPI spec.\n\n## Design\n\nIf the project contains a `DESIGN.md`, it is the single source of\ntruth for visuals \u2014 follow its tokens, don\'t restyle around it. The\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\n`@import "tailwindcss";` in `index.css`) and nothing else \u2014 no\ncomponent library. The rules every Clawnify app follows:\n\n- **Neutral chrome.** White canvas and surfaces, one text ramp\n (foreground \u2192 muted \u2192 faint), hairline borders. Color is for\n meaning, not decoration.\n- **One primary CTA per screen.** Blue is reserved for links and\n focus rings; never a second accent.\n- **Status colors are muted pairs** \u2014 never pure-saturated fills.\n- **Style with Tailwind utilities.** Don\'t install another component\n library or write a bespoke CSS system unless the user asks.\n- **Sizes in rem**, so browser zoom and font settings are respected.\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 "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "optional": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\n`clawnify init` writes the minimal form:\n`{ app: { framework: "react+hono", database: true, storage } }`. Add\nthe rest as needed.\n\nIf the app talks to third-party services the user has connected\n(ads platforms, CRMs, messaging), declare them:\n\n```json\n{ "app": { "credentials": ["metaads", "googleads"] } }\n```\n\nGet the ids and names from `clawnify connections list` \u2014 see the\nnaming rule below.\n\n`env` supports `required` (deploy warns if missing), `optional`\n(injected when available), and `oneOf` (at least one per group).\n\nRules:\n- **There is no `api.tools[]`.** The manifest\'s `api` object only\n accepts `public_routes` and `automation_bypass`. Your API surface\n is discovered from the generated OpenAPI spec, not a hand-authored\n tools list (see the next section).\n- **Public routes are the exception**, not the default. Every route\n is behind the Clawnify perimeter (auth-required) unless you\n explicitly add a matching path to `api.public_routes`. Use only for\n webhooks, RSS, 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. Ship both `schema.ts`\n (typed) and `schema.sql` (the applied DDL), kept in sync.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions auto-generate a live OpenAPI 3.0 spec\n plus a lean `/llms.txt` index, both served for you \u2014 never hand-write\n or route them yourself. **These are the agent\'s discovery channel:**\n it calls `call_app_api` with `GET /llms.txt` (index of every\n endpoint) or `GET /api/openapi.json` (full request/response schemas).\n Because both are generated from the live route table, they cannot\n drift from the code.\n2. The agent then drives your endpoints with `call_app_api` (a `method`\n + `path` on the live app). No per-app MCP registration and no\n manifest tools array. Use source reading to *modify* code, not to\n discover endpoints.\n\nSo you make an endpoint "agent-callable" by defining it with\n`createRoute()` + `app.openapi()` and giving it a clear\n`summary`/`description` with Zod-typed request/response. The clearer\nthose are, the more reliably the agent uses it.\n\n### `agent.md` \u2014 lead with the procedure, not the endpoint list\n\n`agent.md` is extracted into `agent_instructions` on every build. Since\ndiscovery is already covered by the generated surfaces above, **`agent.md`\nis not an API reference** \u2014 re-listing every payload there just creates a\nsecond source of truth that goes stale the first time a route changes.\nIt is the one place for what generation can\'t produce: **judgment**.\n\nWrite it in this order:\n\n1. **Division of labour, first and short.** What the agent should do\n itself vs. what it must delegate to the app \u2014 and say the wrong move\n out loud (*"never look up contact details yourself; post the records\n and let the app resolve them"*). This one block prevents more misuse\n than the rest of the file combined.\n2. **The procedure** \u2014 numbered steps for the app\'s main job, written so\n the agent can follow them on a request it has never seen.\n3. **Pages**, flagging the screenshot-friendly ones.\n4. **API anchors, not API docs** \u2014 method, path, and *when to reach for\n it*, plus the one or two request shapes the agent writes most often.\n For anything else, let it read `/llms.txt`.\n5. **How to read failures**, and any **cost discipline** \u2014 which calls\n spend the user\'s money and which are free.\n\n**Don\'t ship a per-app skill.** A skill\'s frontmatter stays resident in\nagent context, so one skill per app grows the agent\'s context floor as\nthe app count grows; `agent_instructions` and `/llms.txt` are pulled on\ndemand instead. Skills are for **cross-app** procedures \u2014 if one earns\nreuse across more than one app, promote that single procedure\n(parameterized) to the shared skills library rather than copying it into\nevery app.\n\n## Connections & secrets \u2014 `@clawnify/connections`\n\n**The naming rule \u2014 never invent an identifier.** Before declaring\n`credentials` or env names, run `clawnify connections list`: it shows\nthe org\'s canonical integration ids (`googleads`, never `google_ads`),\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\n`OPENROUTER_KEY`), and custom env vars already defined \u2014 each with\nconnected/set state. Reuse those exact identifiers; a misspelled one\ndoesn\'t fail the build, it silently resolves to nothing at runtime. If\nyou need a custom secret that isn\'t listed, pick a clear name and tell\nthe user to set it in the dashboard.\n\nIf the app needs a third-party service or a provider API key, use\nthe `@clawnify/connections` SDK. Never read credential bindings\ndirectly, never paste API keys, never hardcode a token or endpoint.\n\n```ts\nimport { connect, secret, describe, searchActions } from "@clawnify/connections";\n\n// A connected integration:\nconst meta = connect("metaads", env);\nconst accounts = await meta.adAccounts("name,currency");\n\n// A provider key the user supplied (null if absent):\nconst key = secret("OPENROUTER_API_KEY", env);\n\n// What\'s wired vs missing \u2014 drive your setup/empty state from this:\nconst status = await describe(env, undefined, REQUIRES);\n```\n\nHow to call a connected service \u2014 the mistake that silently breaks\nintegration apps, so get it right:\n\n- **Prefer the typed client\'s semantic methods** where they exist\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\n- **For anything else, discover and run an action:**\n ```ts\n const [best] = await searchActions("list google ads campaigns", env);\n const data = await connect(best.service, env).run(best.slug, body);\n ```\n- Some integrations also expose a raw REST client\n (`connect("bird", env).get("/path")`) \u2014 but if `.get()`/`.post()`\n throws for a service, that service only supports semantic methods\n and `run()`. When unsure, use `run()`.\n- **Need exact paths/arguments for a raw-REST provider?** Some carry\n a `spec_url` (the provider\'s published OpenAPI spec) \u2014\n `clawnify connections list --json` shows it. Download and query it \u2014\n `curl -s <spec_url> -o spec.json && jq \'.paths | keys\' spec.json` \u2014\n never read a whole spec into context (they run to 10+ MB).\n- **Never fall back to raw `fetch`** against a provider API, and\n never invent endpoints or guess tokens.\n\n**The one exception \u2014 a service we don\'t support at all.** If a\nprovider isn\'t in the connections registry (nothing to `connect()`\nto, and `clawnify connections list` doesn\'t show it), the sanctioned\npath *is* a raw call with a user-supplied key: declare the key(s) it\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\nthe user to set them in the dashboard, read them with\n`secret("THAT_KEY", env)`, and `fetch` the provider\'s documented\nendpoints directly. This is the escape hatch for the long tail of\nintegrations we don\'t model yet \u2014 it does **not** apply to a service\nwe *do* support (use `connect()` / `run()` for those, always). Keep\nthe endpoint and token server-side, never in the client bundle.\n\nBuild a `describe()`-driven setup state instead of assuming\nconnections exist \u2014 show the user what\'s missing and where to\nconnect it.\n\n## Scheduling & deferred work \u2014 the managed queue\n\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\n`ASSETS` + `UPLOADS`). To run work later \u2014 a scheduled publish, a reminder, a\nretry, a "do this in 10 minutes" \u2014 use the **Clawnify managed queue service**\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\nendpoint on *your own app* back at the scheduled time.\n\nIt\'s a thin seam over a platform primitive, same shape as `@clawnify/db` /\n`@clawnify/connections` (a `@clawnify/queue` package is coming; inline the seam\nuntil then). Auth is the build-injected `env.CLAWNIFY_TOKEN`; with no token\n(local dev) the seam degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\nconst res = await fetch("https://services.clawnify.com/queue/enqueue", {\n method: "POST",\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, "Content-Type": "application/json" },\n body: JSON.stringify({\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n run_at: new Date(whenMs).toISOString(),\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n }),\n});\nconst { job_id } = await res.json(); // store it to cancel/reschedule\n```\n\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\nreschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \u2014\nthe signature *is* its auth (never trust an unsigned call):\n\n```jsonc\n// clawnify.json\n"api": { "public_routes": [ { "path": "/api/internal/publish", "methods": ["POST"] } ] }\n```\n\nDeliveries are signed with the platform\'s **ECDSA P-256 (ES256)** key,\nStripe-style over `${timestamp}.${rawBody}`, verified against\n`https://services.clawnify.com/.well-known/jwks.json` (public key \u2014 nothing\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\ntolerance (~5 min) before doing anything:\n\n```ts\napp.post("/api/internal/publish", async (c) => {\n const raw = await c.req.text();\n const ok = await verifyDelivery(raw, {\n signature: c.req.header("x-clawnify-signature"),\n timestamp: c.req.header("x-clawnify-timestamp"),\n keyId: c.req.header("x-clawnify-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \u2026do the deferred work (short: it\'s one normal Worker invocation)\u2026\n return c.json({ ok: true });\n});\n```\n\nEach fire is a normal Worker request \u2014 size the work to one invocation (publish a\npost, send a digest). For long compute *now* (not deferred), hold the request\nopen and return when done; don\'t fire-and-forget past the response.\n\n## Migrations\n\nKeep `schema.ts` and `schema.sql` in sync by hand. The workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Make the matching edit in `src/server/schema.sql` \u2014 a new\n `CREATE TABLE IF NOT EXISTS`, or `ALTER TABLE \u2026 ADD COLUMN \u2026` at the\n **end** of the file for a new column.\n3. Run `clawnify dev` locally, then `clawnify deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \u2014 new\ntables and columns are added automatically.\n\nDestructive changes (drop column, rename) are not applied automatically;\ndo them deliberately, and only when the user explicitly asks. Renames\nare risky on production data \u2014 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- Author a `/openapi.json` handler by hand. `app.doc("/api/openapi.json", \u2026)`\n generates it from your `createRoute` definitions.\n- Let `schema.ts` and `schema.sql` drift. They describe the same\n tables \u2014 change both, every time.\n- Hand-author migration SQL files. Make schema changes in `schema.sql`\n (and mirror them in `schema.ts`); the deploy applies them.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \u2014 the OpenAPI spec is the tool surface.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw SQL API has `json()` as a helper.\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, or\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\n `caller(c)` from `@clawnify/app`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n 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`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the preview tier catches schema drift and type errors\n at build time.\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \u2014 the table\ndefinitions live in rows. Those apps fall back to the raw SQL API\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\nthe canonical example.\n\nIf you\'re building this kind of app, you still use Drizzle\'s\n`schema.ts` for the **registry** tables (content types, field\ndefinitions). Only the dynamically-spawned per-collection tables\nneed raw SQL. See open-cms\'s `src/server/schema-sync.ts` for the\nruntime DDL pattern.\n'
|
|
1422
1633
|
},
|
|
1634
|
+
{
|
|
1635
|
+
name: "build-a-clawnify-website",
|
|
1636
|
+
description: "Build and ship a Clawnify website \u2014 Astro on Cloudflare Workers, the built-in form system (never hand-roll a form), images and assets, and the draft-then-publish deploy flow. Use when creating or editing a Clawnify website, or when a site needs a contact/waitlist/signup form.",
|
|
1637
|
+
content: "# Build a Clawnify website\n\nA Clawnify website is an **Astro** project deployed to Cloudflare Workers. One\nsite per organization. You write pages; the platform owns hosting, forms and\nthe publish flow.\n\n```bash\nclawnify init --type website --name \"My Site\" website\ncd website && pnpm install && pnpm dev # http://localhost:4321\n```\n\n```\nwebsite/\n src/pages/ # one .astro file per route (index.astro \u2192 /)\n src/layouts/ # shared shell: nav, footer, <head>\n src/blocks/ # platform blocks you've adopted (see Forms below)\n public/ # images, favicons \u2014 served as-is from /\n```\n\n## Forms: use the built-in system. Do not build your own.\n\n**This is the single most common mistake.** A site needs a contact or waitlist\nform, and the obvious move is to write a `<form>` and POST it somewhere \u2014 your\nown endpoint, a third-party form service, or the platform's submit URL with the\nwebsite id pasted in. All three are wrong, and the last one looks right enough\nto survive review.\n\nClawnify has a form system. It captures submissions, stores them, can email you,\nand can hand each one to an agent or a flow. You get all of it by using the\n**Forms block** rather than writing a form yourself.\n\n### How it works\n\n- The submit target is **computed at render time** from `WEBSITE_ID` \u2014 a\n variable the platform bakes into your site's Worker \u2014 plus the form's id:\n\n ```astro\n const env = (Astro.locals as { runtime?: { env?: Record<string, string> } })?.runtime?.env;\n const websiteId = env?.WEBSITE_ID ?? \"\";\n const action = websiteId ? `https://provision.clawnify.com/forms/submit/${websiteId}/${formId}` : \"\";\n ```\n\n **Never hardcode the website id.** It is baked per Worker so a site can only\n ever submit to itself \u2014 hardcoding throws that away, and the literal goes\n stale the moment the site is recreated. An empty `action` in local `astro dev`\n is expected: there are no Worker vars locally, so the form simply no-ops.\n\n- The submit script POSTs JSON with `Content-Type: text/plain;charset=UTF-8`.\n That is not a typo \u2014 `text/plain` is CORS-safelisted, so the request needs no\n preflight, which matters because the platform can't know your site's origin in\n advance. The route parses the text body as JSON.\n\n- **Keep the Turnstile widget.** The ingest rejects a submission with no token,\n so a form without the widget fails every time with \"Verification required\".\n The sitekey shipped in the block is public and pairs with the platform's\n secret; the widget will not validate on `localhost`, only on a real hostname.\n\n### Getting the block\n\nSites are seeded with the platform's block library at creation. If yours has\n`src/blocks/Forms/Contact.astro`, import it and go. If it doesn't \u2014 an older\nsite, or one scaffolded bare by the CLI \u2014 copy it in from the website template\nand adapt it.\n\n**The design is yours; the plumbing is not.** Restyle the markup, labels and\nclasses freely. Preserve, exactly:\n\n- the computed `action` (never a prop, never a literal),\n- the Turnstile widget,\n- the `data-clawnify-form` attribute and its submit script,\n- `export const schema`,\n- destructuring only known props \u2014 never splat leftover props onto `<form>`,\n or an injected `action` becomes a way to point your form at someone else.\n\n### Fields\n\nThe stock block collects **name, email and message**. Two ways to go beyond\nthat, and the right one depends on whether your form is registered:\n\n- **Registered forms** (a tree node named `Forms/Contact`) are schema-locked:\n the ingest 422s any field it doesn't expect. Give extra inputs **no `name`\n attribute** and have the submit script fold them into `message`.\n- **Unregistered forms** \u2014 hand-built pages like this one \u2014 are not locked, so\n extra fields post as themselves and are stored verbatim in the payload. Better\n data, but if the site later moves onto the tree renderer, registration will\n start rejecting them. Leave a comment saying so.\n\n### Where submissions go\n\nEvery submission is stored and visible in the dashboard. From there it can\nnotify an email address, or fan out to an agent or a flow \u2014 which is how a\nsignup becomes a CRM record or a WhatsApp message without you writing a backend.\nSet the notification address in the dashboard, not in the site.\n\n## Images and assets\n\nPut them in `public/` and reference them with an absolute path (`/img/hero.jpg`).\nThey're served as static files. Pull in real assets at real resolution rather\nthan linking someone else's CDN from your markup.\n\n## Deploying: draft first, then publish\n\n```bash\nclawnify deploy # \u2192 the DRAFT site, visible only to your org\n```\n\nDeploying **never** changes the live site. Going live is a separate, explicit\nstep: review the draft, then **Publish to live** in the dashboard. Tell the user\nthis \u2014 a deploy that \"worked\" but didn't appear on the live site is almost\nalways someone expecting deploy to publish.\n\n## Pinning the org\n\nEvery command resolves which organization it targets, folder-first. In a linked\nfolder you get it for free; otherwise pass `--org`. If you work across several\norganizations, pass `--org` explicitly on anything that writes \u2014 the global\nactive org is shared machine-wide and another session can change it under you.\n"
|
|
1638
|
+
},
|
|
1423
1639
|
{
|
|
1424
1640
|
name: "use-the-clawnify-cli",
|
|
1425
1641
|
description: "Use the Clawnify CLI end-to-end \u2014 authenticate, scaffold, run locally, deploy apps and websites, link projects, manage orgs, and inspect deployed apps. Use when deploying to Clawnify from a terminal or wiring the CLI into scripts and coding agents.",
|
|
@@ -1947,6 +2163,9 @@ async function initApp(dir, opts) {
|
|
|
1947
2163
|
clawnify: "^0.11.3",
|
|
1948
2164
|
"drizzle-kit": "^0.31.0",
|
|
1949
2165
|
tailwindcss: "^4.0.0",
|
|
2166
|
+
// `vite build` only transpiles — it never typechecks — so without this the
|
|
2167
|
+
// scaffold ships with no way to catch a type error before deploy.
|
|
2168
|
+
typescript: "^5.0.0",
|
|
1950
2169
|
vite: "^6.0.0",
|
|
1951
2170
|
wrangler: "^4.0.0"
|
|
1952
2171
|
};
|
|
@@ -1957,6 +2176,11 @@ async function initApp(dir, opts) {
|
|
|
1957
2176
|
scripts: {
|
|
1958
2177
|
dev: "clawnify dev",
|
|
1959
2178
|
build: "vite build",
|
|
2179
|
+
// Referenced by the generated schema.ts comment and the starter UI, and
|
|
2180
|
+
// run implicitly by `clawnify deploy`. It must exist as a script or
|
|
2181
|
+
// following the app's own instructions fails with "Missing script".
|
|
2182
|
+
"db:generate": "drizzle-kit generate",
|
|
2183
|
+
typecheck: "tsc --noEmit",
|
|
1960
2184
|
deploy: "clawnify deploy"
|
|
1961
2185
|
},
|
|
1962
2186
|
dependencies: {
|
|
@@ -2139,6 +2363,53 @@ export default app;
|
|
|
2139
2363
|
`);
|
|
2140
2364
|
}
|
|
2141
2365
|
write(targetDir, "src/client/index.css", `@import "tailwindcss";
|
|
2366
|
+
|
|
2367
|
+
/* Design tokens. Rebrand by editing values here \u2014 no component file should
|
|
2368
|
+
contain a raw hex, font name, or fixed pixel value. */
|
|
2369
|
+
@theme {
|
|
2370
|
+
--color-background: #ffffff;
|
|
2371
|
+
--color-surface: #ffffff;
|
|
2372
|
+
--color-surface-sunken: #f1f5f9;
|
|
2373
|
+
--color-foreground: #1a202c;
|
|
2374
|
+
--color-muted: #475569;
|
|
2375
|
+
--color-faint: #94a3b8;
|
|
2376
|
+
--color-border: #e2e8f0;
|
|
2377
|
+
--color-ring: #2563eb;
|
|
2378
|
+
--color-primary: #dd5164;
|
|
2379
|
+
--color-primary-hover: #c53a4e;
|
|
2380
|
+
--color-on-primary: #ffffff;
|
|
2381
|
+
--color-success: #047857;
|
|
2382
|
+
--color-success-tint: #ecfdf5;
|
|
2383
|
+
--color-warning: #b45309;
|
|
2384
|
+
--color-warning-tint: #fffbeb;
|
|
2385
|
+
--color-danger: #b91c1c;
|
|
2386
|
+
--color-danger-tint: #fef2f2;
|
|
2387
|
+
--font-sans: Inter, ui-sans-serif, system-ui, sans-serif;
|
|
2388
|
+
}
|
|
2389
|
+
|
|
2390
|
+
/* Dark MUST override the custom properties in a plain rule. Tailwind v4 hoists
|
|
2391
|
+
and merges every @theme block and drops the surrounding media condition, so a
|
|
2392
|
+
nested \`@media { @theme { \u2026 } }\` silently makes dark the *unconditional*
|
|
2393
|
+
default and light never renders. Light stays the default; dark is opt-in by
|
|
2394
|
+
system preference. */
|
|
2395
|
+
@media (prefers-color-scheme: dark) {
|
|
2396
|
+
:root {
|
|
2397
|
+
--color-background: #0d1117;
|
|
2398
|
+
--color-surface: #161b22;
|
|
2399
|
+
--color-surface-sunken: #1c2128;
|
|
2400
|
+
--color-foreground: #e6edf3;
|
|
2401
|
+
--color-muted: #9ba7b3;
|
|
2402
|
+
--color-faint: #6e7681;
|
|
2403
|
+
--color-border: #30363d;
|
|
2404
|
+
--color-ring: #4493f8;
|
|
2405
|
+
--color-success: #3fb950;
|
|
2406
|
+
--color-success-tint: #12261e;
|
|
2407
|
+
--color-warning: #d29922;
|
|
2408
|
+
--color-warning-tint: #2a2210;
|
|
2409
|
+
--color-danger: #f85149;
|
|
2410
|
+
--color-danger-tint: #2d1518;
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2142
2413
|
`);
|
|
2143
2414
|
write(targetDir, "src/client/main.tsx", `import { StrictMode } from "react";
|
|
2144
2415
|
import { createRoot } from "react-dom/client";
|
|
@@ -3031,15 +3302,13 @@ async function orgListCommand() {
|
|
|
3031
3302
|
console.log("No organizations.");
|
|
3032
3303
|
return;
|
|
3033
3304
|
}
|
|
3034
|
-
const auth = loadAuth();
|
|
3035
3305
|
const nameWidth = Math.max(4, ...orgs.map((o) => o.name.length));
|
|
3036
3306
|
const slugWidth = Math.max(4, ...orgs.map((o) => o.slug.length));
|
|
3037
|
-
console.log(`${"Name".padEnd(nameWidth)} ${"Slug".padEnd(slugWidth)} Role
|
|
3038
|
-
console.log(`${"\u2500".repeat(nameWidth)} ${"\u2500".repeat(slugWidth)} \u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
3307
|
+
console.log(`${"Name".padEnd(nameWidth)} ${"Slug".padEnd(slugWidth)} Role`);
|
|
3308
|
+
console.log(`${"\u2500".repeat(nameWidth)} ${"\u2500".repeat(slugWidth)} \u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
|
|
3039
3309
|
for (const o of orgs) {
|
|
3040
|
-
const active = auth?.org_id === o.id ? " *" : "";
|
|
3041
3310
|
console.log(
|
|
3042
|
-
`${o.name.padEnd(nameWidth)} ${o.slug.padEnd(slugWidth)} ${o.role
|
|
3311
|
+
`${o.name.padEnd(nameWidth)} ${o.slug.padEnd(slugWidth)} ${o.role}`
|
|
3043
3312
|
);
|
|
3044
3313
|
}
|
|
3045
3314
|
}
|
|
@@ -3052,13 +3321,25 @@ async function orgUseCommand(slugOrId) {
|
|
|
3052
3321
|
);
|
|
3053
3322
|
process.exit(1);
|
|
3054
3323
|
}
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3324
|
+
console.error(
|
|
3325
|
+
`\`clawnify org use\` is deprecated and no longer sets anything.
|
|
3326
|
+
Org is resolved per folder, so a global default cannot redirect another
|
|
3327
|
+
session mid-task. Bind ${match.name} to this folder instead:
|
|
3328
|
+
|
|
3329
|
+
clawnify link <app> --org ${match.slug}
|
|
3330
|
+
writes .clawnify/project.json \u2014 persists for this folder
|
|
3331
|
+
|
|
3332
|
+
"workspace": { "org": "${match.slug}" } in clawnify.json
|
|
3333
|
+
for a workspace repo \u2014 persists for every folder inside it
|
|
3334
|
+
|
|
3335
|
+
--org ${match.slug}
|
|
3336
|
+
one command
|
|
3337
|
+
|
|
3338
|
+
export CLAWNIFY_ORG_ID=${match.slug}
|
|
3339
|
+
one shell
|
|
3340
|
+
`
|
|
3341
|
+
);
|
|
3342
|
+
process.exit(1);
|
|
3062
3343
|
}
|
|
3063
3344
|
|
|
3064
3345
|
// src/commands/connections.ts
|
|
@@ -3162,18 +3443,18 @@ async function resolveOrg(opts) {
|
|
|
3162
3443
|
process.exit(1);
|
|
3163
3444
|
}
|
|
3164
3445
|
if (opts?.org) {
|
|
3165
|
-
const
|
|
3166
|
-
if (!
|
|
3446
|
+
const match2 = orgs.find((o) => o.id === opts.org || o.slug === opts.org);
|
|
3447
|
+
if (!match2) {
|
|
3167
3448
|
console.error(
|
|
3168
3449
|
`No org matched "${opts.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
|
|
3169
3450
|
);
|
|
3170
3451
|
process.exit(1);
|
|
3171
3452
|
}
|
|
3172
|
-
return
|
|
3453
|
+
return match2;
|
|
3173
3454
|
}
|
|
3174
|
-
const
|
|
3175
|
-
const
|
|
3176
|
-
if (
|
|
3455
|
+
const resolved = await resolveOrgContext();
|
|
3456
|
+
const match = resolved ? orgs.find((o) => o.id === resolved) : void 0;
|
|
3457
|
+
if (match) return match;
|
|
3177
3458
|
if (orgs.length === 1) return orgs[0];
|
|
3178
3459
|
console.error(
|
|
3179
3460
|
`Multiple orgs \u2014 pick one with \`--org <slug>\` (or set a default: \`clawnify org use <slug>\`).
|
|
@@ -3310,8 +3591,7 @@ async function workspaceStatusCommand(opts) {
|
|
|
3310
3591
|
${WORKSPACE_GUIDE}`);
|
|
3311
3592
|
process.exit(1);
|
|
3312
3593
|
}
|
|
3313
|
-
const
|
|
3314
|
-
const orgId = auth?.org_id ?? process.env.CLAWNIFY_ORG_ID;
|
|
3594
|
+
const orgId = await resolveOrgContext();
|
|
3315
3595
|
const res = await api.get("/v1/github/links", orgId ? { orgId } : void 0);
|
|
3316
3596
|
if (!res.ok) {
|
|
3317
3597
|
console.error(`Failed to load workspace state (${res.status}).`);
|
|
@@ -3322,8 +3602,7 @@ ${WORKSPACE_GUIDE}`);
|
|
|
3322
3602
|
console.log(JSON.stringify({ logged_in: true, ...data, guide: WORKSPACE_GUIDE }));
|
|
3323
3603
|
return;
|
|
3324
3604
|
}
|
|
3325
|
-
|
|
3326
|
-
console.log(`Org: ${orgLabel}`);
|
|
3605
|
+
console.log(`Org: ${data.org_id}`);
|
|
3327
3606
|
if (data.links.length === 0) {
|
|
3328
3607
|
console.log(`
|
|
3329
3608
|
No GitHub repo is linked yet. Local editing works through the org's
|
|
@@ -3379,8 +3658,7 @@ async function workspaceConnectCommand(opts) {
|
|
|
3379
3658
|
then re-run \`clawnify workspace connect\`.`);
|
|
3380
3659
|
process.exit(1);
|
|
3381
3660
|
}
|
|
3382
|
-
const
|
|
3383
|
-
const orgId = auth?.org_id ?? process.env.CLAWNIFY_ORG_ID;
|
|
3661
|
+
const orgId = await resolveOrgContext();
|
|
3384
3662
|
const orgOpt = orgId ? { orgId } : void 0;
|
|
3385
3663
|
let installs = await listInstallations(orgId);
|
|
3386
3664
|
if (installs.length === 0) {
|
|
@@ -3556,15 +3834,15 @@ async function docsCommand(slug, options) {
|
|
|
3556
3834
|
process.stderr.write("Not logged in. Run `clawnify login` first.\n");
|
|
3557
3835
|
process.exit(1);
|
|
3558
3836
|
}
|
|
3559
|
-
const
|
|
3560
|
-
if (!
|
|
3837
|
+
const orgId = await resolveOrgContext();
|
|
3838
|
+
if (!orgId) {
|
|
3561
3839
|
process.stderr.write(
|
|
3562
3840
|
"No active org. Pick one with `clawnify org use <slug-or-id>` first.\n"
|
|
3563
3841
|
);
|
|
3564
3842
|
process.exit(1);
|
|
3565
3843
|
}
|
|
3566
3844
|
const caller = options.caller ?? "external";
|
|
3567
|
-
const path10 = slug ? `/docs/${
|
|
3845
|
+
const path10 = slug ? `/docs/${orgId}/${slug}.md?caller=${caller}` : `/docs/${orgId}/index.md`;
|
|
3568
3846
|
const res = await fetch(DOCS_URL + path10, {
|
|
3569
3847
|
headers: {
|
|
3570
3848
|
authorization: "Bearer " + token
|
|
@@ -3594,8 +3872,9 @@ async function mcpBridgeCommand() {
|
|
|
3594
3872
|
"content-type": "application/json",
|
|
3595
3873
|
authorization: "Bearer " + token
|
|
3596
3874
|
};
|
|
3597
|
-
|
|
3598
|
-
|
|
3875
|
+
const bridgeOrgId = await resolveOrgContext();
|
|
3876
|
+
if (bridgeOrgId) {
|
|
3877
|
+
baseHeaders["X-Clawnify-Org-Id"] = bridgeOrgId;
|
|
3599
3878
|
}
|
|
3600
3879
|
const rl = readline5.createInterface({ input: process.stdin, terminal: false });
|
|
3601
3880
|
rl.on("line", async (line) => {
|
|
@@ -4018,4 +4297,4 @@ async function runCli() {
|
|
|
4018
4297
|
export {
|
|
4019
4298
|
runCli
|
|
4020
4299
|
};
|
|
4021
|
-
//# sourceMappingURL=cli-
|
|
4300
|
+
//# sourceMappingURL=cli-G6ZBPA6D.js.map
|