agentful 0.3.0 → 0.3.2

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.
Files changed (2) hide show
  1. package/dist/index.cjs +249 -103
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -3044,7 +3044,7 @@ var VERSION, brand, useColor, wrap, paint, sym, ui;
3044
3044
  var init_branding = __esm({
3045
3045
  "src/branding.ts"() {
3046
3046
  "use strict";
3047
- VERSION = "0.3.0" ? "0.3.0" : null.version;
3047
+ VERSION = "0.3.2" ? "0.3.2" : null.version;
3048
3048
  brand = {
3049
3049
  name: "agentful",
3050
3050
  // the command users type
@@ -5873,6 +5873,135 @@ function describeBackendState(state) {
5873
5873
  return out;
5874
5874
  }
5875
5875
 
5876
+ // src/lib/backendConsent.ts
5877
+ var import_node_fs7 = require("fs");
5878
+ var import_node_path9 = require("path");
5879
+ var import_promises2 = require("readline/promises");
5880
+ function declaresManagedDatabase(decl) {
5881
+ if (!decl) return false;
5882
+ return Boolean(decl.managed_db) || (decl.collections?.length ?? 0) > 0 || authMethodsOf(decl).length > 0;
5883
+ }
5884
+ function decideConsent(input) {
5885
+ if (!declaresManagedDatabase(input.declaration)) return { kind: "not_applicable" };
5886
+ if (input.state === null) return { kind: "state_unknown" };
5887
+ if (input.state.databaseEnabled) return { kind: "already_enabled" };
5888
+ if (input.yes) return { kind: "enable", via: "flag" };
5889
+ if (input.rememberedDecline) return { kind: "skip", reason: "remembered_decline" };
5890
+ if (!input.interactive) return { kind: "skip", reason: "non_interactive" };
5891
+ return { kind: "ask" };
5892
+ }
5893
+ function consentQuestion(decl) {
5894
+ const names = (decl.collections ?? []).map((c) => c.name).filter(Boolean);
5895
+ const what = names.length ? `a managed database with ${names.length} collection(s): ${names.slice(0, 6).join(", ")}${names.length > 6 ? ", \u2026" : ""}` : "a managed database";
5896
+ return [
5897
+ `This project declares ${what}.`,
5898
+ "Enable it on the platform now? Two things change:",
5899
+ " \u2022 /api/* on your preview domain is routed to the backend \u2014 a static file under /api/ would no longer be served",
5900
+ " \u2022 the data API goes live under the declared access rules (a `public` collection is readable AND writable without login)",
5901
+ 'It is the same switch as the Backend tab; this push then applies the declaration. A "no" is remembered for this project (`agentful push --yes` or `agentful backend` enables it later).'
5902
+ ].join("\n");
5903
+ }
5904
+ var consentFile = () => (0, import_node_path9.join)(configDir(), "backend-consent.json");
5905
+ function readConsentFile() {
5906
+ try {
5907
+ const raw = JSON.parse((0, import_node_fs7.readFileSync)(consentFile(), "utf8"));
5908
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
5909
+ } catch {
5910
+ return {};
5911
+ }
5912
+ }
5913
+ function hasRememberedDecline(projectId) {
5914
+ return Boolean(readConsentFile()[projectId]);
5915
+ }
5916
+ function rememberDecline(projectId) {
5917
+ const all = readConsentFile();
5918
+ all[projectId] = { declined_at: (/* @__PURE__ */ new Date()).toISOString() };
5919
+ (0, import_node_fs7.mkdirSync)(configDir(), { recursive: true });
5920
+ (0, import_node_fs7.writeFileSync)(consentFile(), JSON.stringify(all, null, 2) + "\n", "utf8");
5921
+ }
5922
+ function forgetDecline(projectId) {
5923
+ if (!(0, import_node_fs7.existsSync)(consentFile())) return;
5924
+ const all = readConsentFile();
5925
+ if (!(projectId in all)) return;
5926
+ delete all[projectId];
5927
+ (0, import_node_fs7.writeFileSync)(consentFile(), JSON.stringify(all, null, 2) + "\n", "utf8");
5928
+ }
5929
+ async function enableManagedDatabase(auth, userId, projectId) {
5930
+ try {
5931
+ const body = await request(`${API_URL}/api/projects/${userId}/${projectId}/backend/database`, {
5932
+ method: "PUT",
5933
+ token: auth.pb_token,
5934
+ timeoutMs: 6e4,
5935
+ body: { mode: "managed", provider: "managed_document" }
5936
+ });
5937
+ const status = String(body?.data?.status ?? body?.status ?? "");
5938
+ return status === "active" ? { ok: true, status } : { ok: false, status, message: body?.error?.message || body?.message };
5939
+ } catch (err2) {
5940
+ return { ok: false, message: err2?.message || String(err2) };
5941
+ }
5942
+ }
5943
+ async function ensureDatabaseConsent(opts) {
5944
+ const lines = [];
5945
+ if (!declaresManagedDatabase(opts.declaration)) {
5946
+ return { decision: { kind: "not_applicable" }, enabled: false, lines };
5947
+ }
5948
+ const state = await fetchBackendSessionState(opts.auth, opts.userId, opts.projectId);
5949
+ const interactive = opts.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
5950
+ let decision = decideConsent({
5951
+ declaration: opts.declaration,
5952
+ state,
5953
+ yes: opts.yes,
5954
+ interactive,
5955
+ rememberedDecline: hasRememberedDecline(opts.projectId)
5956
+ });
5957
+ if (decision.kind === "ask") {
5958
+ const ask = opts.ask ?? (async (q) => {
5959
+ const rl = (0, import_promises2.createInterface)({ input: process.stdin, output: process.stdout });
5960
+ try {
5961
+ return await rl.question(`${q}
5962
+ Enable the managed database? [y/N] `);
5963
+ } finally {
5964
+ rl.close();
5965
+ }
5966
+ });
5967
+ const answer = (await ask(consentQuestion(opts.declaration))).trim().toLowerCase();
5968
+ if (answer === "y" || answer === "yes") {
5969
+ decision = { kind: "enable", via: "answer" };
5970
+ } else {
5971
+ rememberDecline(opts.projectId);
5972
+ decision = { kind: "skip", reason: "declined" };
5973
+ }
5974
+ }
5975
+ switch (decision.kind) {
5976
+ case "state_unknown":
5977
+ lines.push({ kind: "warn", text: "Could not read the backend state \u2014 the database is NOT enabled by this push; the declaration is stored and reported." });
5978
+ return { decision, enabled: false, lines };
5979
+ case "already_enabled":
5980
+ return { decision, enabled: true, lines };
5981
+ case "skip":
5982
+ if (decision.reason === "non_interactive") {
5983
+ lines.push({ kind: "info", text: "Managed database declared but not enabled \u2014 non-interactive push never enables it. Use `agentful push --yes` (CI) or enable it in the Backend tab (`agentful backend`)." });
5984
+ } else if (decision.reason === "remembered_decline") {
5985
+ lines.push({ kind: "info", text: "Managed database declared but not enabled \u2014 you declined earlier for this project. `agentful push --yes` or `agentful backend` enables it." });
5986
+ } else {
5987
+ lines.push({ kind: "info", text: "Not enabled. The declaration is stored; `agentful push --yes` or the Backend tab enables the database later." });
5988
+ }
5989
+ return { decision, enabled: false, lines };
5990
+ case "enable": {
5991
+ const result = await enableManagedDatabase(opts.auth, opts.userId, opts.projectId);
5992
+ if (result.ok) {
5993
+ forgetDecline(opts.projectId);
5994
+ lines.push({ kind: "ok", text: `Managed database enabled${decision.via === "flag" ? " (--yes)" : ""} \u2014 this push applies the declaration.` });
5995
+ return { decision, enabled: true, lines };
5996
+ }
5997
+ lines.push({ kind: "warn", text: `Could not enable the managed database${result.message ? `: ${result.message}` : ""}. The push continues; enable it in the Backend tab (\`agentful backend\`).` });
5998
+ return { decision, enabled: false, lines };
5999
+ }
6000
+ default:
6001
+ return { decision, enabled: false, lines };
6002
+ }
6003
+ }
6004
+
5876
6005
  // src/lib/buildStatus.ts
5877
6006
  init_branding();
5878
6007
  var DIAGNOSIS_MAX_AGE_MS = 15 * 60 * 1e3;
@@ -5962,8 +6091,22 @@ async function pushCommand(opts) {
5962
6091
  `Packed ${(zip.bytes / 1024 / 1024).toFixed(1)} MB compressed \u2014 the platform caps uploads at ${Math.floor(MAX_ZIP_UPLOAD_BYTES / (1024 * 1024))} MB. Remove large media or generated files from the source tree (node_modules, dist and .git are excluded automatically); large assets belong in the platform asset flow.`
5963
6092
  );
5964
6093
  }
5965
- ui.step("Uploading to your workspace\u2026");
5966
6094
  const declaration = mode === "source" ? readBackendDeclaration() : null;
6095
+ if (declaration) {
6096
+ const consent = await ensureDatabaseConsent({
6097
+ auth,
6098
+ userId,
6099
+ projectId,
6100
+ declaration,
6101
+ yes: opts.yes
6102
+ });
6103
+ for (const line of consent.lines) {
6104
+ if (line.kind === "ok") ui.ok(line.text);
6105
+ else if (line.kind === "warn") ui.warn(line.text);
6106
+ else ui.info(line.text);
6107
+ }
6108
+ }
6109
+ ui.step("Uploading to your workspace\u2026");
5967
6110
  const upload = await request(
5968
6111
  `${API_URL}/api/workspaces/${userId}/${projectId}/source-zip`,
5969
6112
  {
@@ -6150,15 +6293,15 @@ async function openCommand() {
6150
6293
 
6151
6294
  // src/commands/tui.ts
6152
6295
  var import_node_child_process5 = require("child_process");
6153
- var import_node_path17 = require("path");
6296
+ var import_node_path18 = require("path");
6154
6297
 
6155
6298
  // src/lib/binWrapper.ts
6156
- var import_node_fs7 = require("fs");
6157
- var import_node_path9 = require("path");
6299
+ var import_node_fs8 = require("fs");
6300
+ var import_node_path10 = require("path");
6158
6301
  var import_node_os3 = require("os");
6159
6302
  function ensureCliOnPath() {
6160
- const binDir = (0, import_node_path9.join)((0, import_node_os3.homedir)(), ".local", "share", "agentful", "bin");
6161
- (0, import_node_fs7.mkdirSync)(binDir, { recursive: true });
6303
+ const binDir = (0, import_node_path10.join)((0, import_node_os3.homedir)(), ".local", "share", "agentful", "bin");
6304
+ (0, import_node_fs8.mkdirSync)(binDir, { recursive: true });
6162
6305
  const entry = process.argv[1];
6163
6306
  if (!entry) return binDir;
6164
6307
  const restore = (name) => {
@@ -6167,8 +6310,8 @@ function ensureCliOnPath() {
6167
6310
  ` : `export ${name}=${JSON.stringify(original)}
6168
6311
  `;
6169
6312
  };
6170
- const wrapper = (0, import_node_path9.join)(binDir, "agentful");
6171
- (0, import_node_fs7.writeFileSync)(
6313
+ const wrapper = (0, import_node_path10.join)(binDir, "agentful");
6314
+ (0, import_node_fs8.writeFileSync)(
6172
6315
  wrapper,
6173
6316
  `#!/bin/sh
6174
6317
  # Generated by the Agentful CLI so the coding agent can run \`agentful \u2026\`.
@@ -6178,7 +6321,7 @@ function ensureCliOnPath() {
6178
6321
  "utf8"
6179
6322
  );
6180
6323
  try {
6181
- (0, import_node_fs7.chmodSync)(wrapper, 493);
6324
+ (0, import_node_fs8.chmodSync)(wrapper, 493);
6182
6325
  } catch {
6183
6326
  }
6184
6327
  return binDir;
@@ -6188,13 +6331,13 @@ function ensureCliOnPath() {
6188
6331
  init_branding();
6189
6332
 
6190
6333
  // src/lib/engine.ts
6191
- var import_node_fs8 = require("fs");
6334
+ var import_node_fs9 = require("fs");
6192
6335
  var import_node_crypto = require("crypto");
6193
- var import_node_path10 = require("path");
6336
+ var import_node_path11 = require("path");
6194
6337
  var import_node_os4 = require("os");
6195
6338
  var import_node_child_process3 = require("child_process");
6196
6339
  var import_node_stream = require("stream");
6197
- var import_promises2 = require("stream/promises");
6340
+ var import_promises3 = require("stream/promises");
6198
6341
  init_branding();
6199
6342
  var ENGINE_BINARY = "agentful-engine";
6200
6343
  var FALLBACK_ENGINE_VERSION = "v1.18.18";
@@ -6235,8 +6378,8 @@ function platformKey() {
6235
6378
  );
6236
6379
  }
6237
6380
  function cacheDir(version) {
6238
- const base = process.env.XDG_CACHE_HOME || (0, import_node_path10.join)((0, import_node_os4.homedir)(), ".cache");
6239
- return (0, import_node_path10.join)(base, "agentful", "engine", version);
6381
+ const base = process.env.XDG_CACHE_HOME || (0, import_node_path11.join)((0, import_node_os4.homedir)(), ".cache");
6382
+ return (0, import_node_path11.join)(base, "agentful", "engine", version);
6240
6383
  }
6241
6384
  async function fetchManifest() {
6242
6385
  try {
@@ -6247,7 +6390,7 @@ async function fetchManifest() {
6247
6390
  }
6248
6391
  async function sha256File(path) {
6249
6392
  const hash = (0, import_node_crypto.createHash)("sha256");
6250
- await (0, import_promises2.pipeline)((0, import_node_fs8.createReadStream)(path), hash);
6393
+ await (0, import_promises3.pipeline)((0, import_node_fs9.createReadStream)(path), hash);
6251
6394
  return hash.digest("hex");
6252
6395
  }
6253
6396
  async function ensureEngine() {
@@ -6256,12 +6399,12 @@ async function ensureEngine() {
6256
6399
  noticeIfOutdated(manifest);
6257
6400
  const version = manifest?.engine_version || FALLBACK_ENGINE_VERSION;
6258
6401
  const dir = cacheDir(version);
6259
- const binPath = (0, import_node_path10.join)(dir, ENGINE_BINARY);
6260
- if ((0, import_node_fs8.existsSync)(binPath)) return binPath;
6402
+ const binPath = (0, import_node_path11.join)(dir, ENGINE_BINARY);
6403
+ if ((0, import_node_fs9.existsSync)(binPath)) return binPath;
6261
6404
  const artifact = manifest?.artifacts?.[key];
6262
6405
  const url = artifact?.url || `${APP_URL}/cli/engine/${version}/${key}${key.startsWith("darwin") ? ".zip" : ".tar.gz"}`;
6263
- (0, import_node_fs8.mkdirSync)(dir, { recursive: true });
6264
- const archivePath = (0, import_node_path10.join)(dir, key.startsWith("darwin") ? "engine.zip" : "engine.tar.gz");
6406
+ (0, import_node_fs9.mkdirSync)(dir, { recursive: true });
6407
+ const archivePath = (0, import_node_path11.join)(dir, key.startsWith("darwin") ? "engine.zip" : "engine.tar.gz");
6265
6408
  ui.step(`Preparing the ${brand.displayName} engine (first run only)\u2026`);
6266
6409
  const resp = await fetch(url, {
6267
6410
  redirect: "follow",
@@ -6275,11 +6418,11 @@ async function ensureEngine() {
6275
6418
  `Could not download the engine (HTTP ${resp.status}). Check your connection and try again.`
6276
6419
  );
6277
6420
  }
6278
- await (0, import_promises2.pipeline)(import_node_stream.Readable.fromWeb(resp.body), (0, import_node_fs8.createWriteStream)(archivePath));
6421
+ await (0, import_promises3.pipeline)(import_node_stream.Readable.fromWeb(resp.body), (0, import_node_fs9.createWriteStream)(archivePath));
6279
6422
  if (artifact?.sha256) {
6280
6423
  const actual = await sha256File(archivePath);
6281
6424
  if (actual !== artifact.sha256) {
6282
- (0, import_node_fs8.rmSync)(archivePath, { force: true });
6425
+ (0, import_node_fs9.rmSync)(archivePath, { force: true });
6283
6426
  throw new ApiError(
6284
6427
  0,
6285
6428
  "engine_checksum_mismatch",
@@ -6288,7 +6431,7 @@ async function ensureEngine() {
6288
6431
  }
6289
6432
  }
6290
6433
  const extract = archivePath.endsWith(".zip") ? (0, import_node_child_process3.spawnSync)("unzip", ["-oq", archivePath], { cwd: dir, stdio: "ignore" }) : (0, import_node_child_process3.spawnSync)("tar", ["-xzf", archivePath], { cwd: dir, stdio: "ignore" });
6291
- (0, import_node_fs8.rmSync)(archivePath, { force: true });
6434
+ (0, import_node_fs9.rmSync)(archivePath, { force: true });
6292
6435
  if (extract.status !== 0) {
6293
6436
  throw new ApiError(
6294
6437
  0,
@@ -6296,24 +6439,24 @@ async function ensureEngine() {
6296
6439
  `Could not unpack the engine (needs ${archivePath.endsWith(".zip") ? "unzip" : "tar"} on PATH).`
6297
6440
  );
6298
6441
  }
6299
- const extracted = (0, import_node_path10.join)(dir, "opencode");
6300
- if ((0, import_node_fs8.existsSync)(extracted) && !(0, import_node_fs8.existsSync)(binPath)) (0, import_node_fs8.renameSync)(extracted, binPath);
6301
- if (!(0, import_node_fs8.existsSync)(binPath)) {
6442
+ const extracted = (0, import_node_path11.join)(dir, "opencode");
6443
+ if ((0, import_node_fs9.existsSync)(extracted) && !(0, import_node_fs9.existsSync)(binPath)) (0, import_node_fs9.renameSync)(extracted, binPath);
6444
+ if (!(0, import_node_fs9.existsSync)(binPath)) {
6302
6445
  throw new ApiError(0, "engine_extract_failed", "Engine archive did not contain the expected binary.");
6303
6446
  }
6304
- (0, import_node_fs8.chmodSync)(binPath, 493);
6447
+ (0, import_node_fs9.chmodSync)(binPath, 493);
6305
6448
  ui.ok(`Engine ready.`);
6306
6449
  console.log(paint.dim(" powered by opencode (MIT) \xB7 run `agentful licenses` for details"));
6307
6450
  return binPath;
6308
6451
  }
6309
6452
 
6310
6453
  // src/lib/gatewayToken.ts
6311
- var import_node_fs9 = require("fs");
6312
- var import_node_path11 = require("path");
6313
- var cachePath = () => (0, import_node_path11.join)(configDir(), "gateway.json");
6454
+ var import_node_fs10 = require("fs");
6455
+ var import_node_path12 = require("path");
6456
+ var cachePath = () => (0, import_node_path12.join)(configDir(), "gateway.json");
6314
6457
  async function ensureGatewaySession(auth, projectId) {
6315
6458
  try {
6316
- const cached = JSON.parse((0, import_node_fs9.readFileSync)(cachePath(), "utf8"));
6459
+ const cached = JSON.parse((0, import_node_fs10.readFileSync)(cachePath(), "utf8"));
6317
6460
  if (cached?.token && cached.expires_at - Date.now() / 1e3 > 3600) {
6318
6461
  return cached;
6319
6462
  }
@@ -6324,18 +6467,18 @@ async function ensureGatewaySession(auth, projectId) {
6324
6467
  body: projectId ? { project_id: projectId } : {},
6325
6468
  timeoutMs: 3e4
6326
6469
  });
6327
- (0, import_node_fs9.mkdirSync)(configDir(), { recursive: true });
6328
- (0, import_node_fs9.writeFileSync)(cachePath(), JSON.stringify(res, null, 2) + "\n", "utf8");
6470
+ (0, import_node_fs10.mkdirSync)(configDir(), { recursive: true });
6471
+ (0, import_node_fs10.writeFileSync)(cachePath(), JSON.stringify(res, null, 2) + "\n", "utf8");
6329
6472
  try {
6330
- (0, import_node_fs9.chmodSync)(cachePath(), 384);
6473
+ (0, import_node_fs10.chmodSync)(cachePath(), 384);
6331
6474
  } catch {
6332
6475
  }
6333
6476
  return res;
6334
6477
  }
6335
6478
 
6336
6479
  // src/lib/engineConfig.ts
6337
- var import_node_fs11 = require("fs");
6338
- var import_node_path13 = require("path");
6480
+ var import_node_fs12 = require("fs");
6481
+ var import_node_path14 = require("path");
6339
6482
  var import_node_os5 = require("os");
6340
6483
 
6341
6484
  // src/branding/agentful-theme.json
@@ -6478,22 +6621,22 @@ ${cmd.template}
6478
6621
  }
6479
6622
 
6480
6623
  // src/lib/tools.ts
6481
- var import_node_fs10 = require("fs");
6482
- var import_node_path12 = require("path");
6624
+ var import_node_fs11 = require("fs");
6625
+ var import_node_path13 = require("path");
6483
6626
  function assetsDir() {
6484
- const here = (0, import_node_path12.dirname)(process.argv[1] || "");
6485
- for (const candidate of [(0, import_node_path12.join)(here, "..", "assets"), (0, import_node_path12.join)(here, "assets")]) {
6486
- if ((0, import_node_fs10.existsSync)((0, import_node_path12.join)(candidate, "tools", "imagegen.ts"))) return candidate;
6627
+ const here = (0, import_node_path13.dirname)(process.argv[1] || "");
6628
+ for (const candidate of [(0, import_node_path13.join)(here, "..", "assets"), (0, import_node_path13.join)(here, "assets")]) {
6629
+ if ((0, import_node_fs11.existsSync)((0, import_node_path13.join)(candidate, "tools", "imagegen.ts"))) return candidate;
6487
6630
  }
6488
6631
  return null;
6489
6632
  }
6490
6633
  function installEngineTools(configDir2) {
6491
6634
  const assets = assetsDir();
6492
6635
  if (!assets) return false;
6493
- const target = (0, import_node_path12.join)(configDir2, "tools");
6494
- (0, import_node_fs10.mkdirSync)(target, { recursive: true });
6636
+ const target = (0, import_node_path13.join)(configDir2, "tools");
6637
+ (0, import_node_fs11.mkdirSync)(target, { recursive: true });
6495
6638
  try {
6496
- (0, import_node_fs10.cpSync)((0, import_node_path12.join)(assets, "tools"), target, { recursive: true });
6639
+ (0, import_node_fs11.cpSync)((0, import_node_path13.join)(assets, "tools"), target, { recursive: true });
6497
6640
  return true;
6498
6641
  } catch {
6499
6642
  return false;
@@ -6652,7 +6795,8 @@ applied.**
6652
6795
  write without login; use \`owner\`, \`authenticated\` or \`admin\` unless the data
6653
6796
  is truly public). The push is rejected without it.
6654
6797
  - Field types are exactly \`string\`, \`text\`, \`number\`, \`boolean\`, \`select\`
6655
- (with \`options\`), \`datetime\`, \`json\` \u2014 anything else is rejected. Collection
6798
+ (with \`options\`), \`date\` (calendar date \`YYYY-MM-DD\`), \`datetime\`,
6799
+ \`json\` \u2014 anything else is rejected. Collection
6656
6800
  names match \`[a-zA-Z][a-zA-Z0-9_]{0,62}\`; \`_users\`, \`_meta\`, \`_sessions\`,
6657
6801
  \`_files\`, \`_automations\` are reserved.
6658
6802
  - Secrets: \`generate\` (\`random_base64_32\` / \`random_hex_32\`) ONLY for values
@@ -6675,7 +6819,9 @@ without an address. Read \`.agentful/project.json\` and give the full URL
6675
6819
  \`https://app.agentful.dev/workspace/<userId>/<projectId>?view=backend\` \u2014 or
6676
6820
  simply the command \`agentful backend\`, which opens exactly that page and
6677
6821
  shows the live state. Declaring a backend never enables it; enabling is the
6678
- user's conscious step in that tab.
6822
+ user's conscious step \u2014 in that tab, or by answering the question
6823
+ \`agentful push\` asks once (it names both consequences; a non-interactive
6824
+ push never enables anything).
6679
6825
 
6680
6826
  ## Diagnosing failed pushes and cloud builds (hard rule)
6681
6827
 
@@ -6703,7 +6849,7 @@ var CLOUD_AGENT_PROMPT = `You are the Agentful Cloud build agent: everything you
6703
6849
  var LOCAL_AGENT_PROMPT = "You are in local-only mode: free local development with no cloud deployment target \u2014 any stack is fine. Be clear that this directory will NOT be deployable with `agentful push` unless it satisfies the platform contract in AGENTFUL_CLOUD.md (static files only). If the user asks to deploy or push, check the contract first and say honestly whether the project can ship on the platform; never claim cloud deployability without evidence.";
6704
6850
  function readAuthFile(path) {
6705
6851
  try {
6706
- return (0, import_node_fs11.readFileSync)(path, "utf8");
6852
+ return (0, import_node_fs12.readFileSync)(path, "utf8");
6707
6853
  } catch {
6708
6854
  return null;
6709
6855
  }
@@ -6768,11 +6914,11 @@ function buildEngineConfig(opts) {
6768
6914
  };
6769
6915
  }
6770
6916
  function engineXdg() {
6771
- const root = (0, import_node_path13.join)((0, import_node_os5.homedir)(), ".local", "share", "agentful");
6917
+ const root = (0, import_node_path14.join)((0, import_node_os5.homedir)(), ".local", "share", "agentful");
6772
6918
  return {
6773
- configHome: (0, import_node_path13.join)(root, "engine-config"),
6774
- dataHome: (0, import_node_path13.join)(root, "engine-data"),
6775
- stateHome: (0, import_node_path13.join)(root, "engine-state")
6919
+ configHome: (0, import_node_path14.join)(root, "engine-config"),
6920
+ dataHome: (0, import_node_path14.join)(root, "engine-data"),
6921
+ stateHome: (0, import_node_path14.join)(root, "engine-state")
6776
6922
  };
6777
6923
  }
6778
6924
  async function resolveTheme() {
@@ -6791,24 +6937,24 @@ async function resolveTheme() {
6791
6937
  }
6792
6938
  async function writeEngineSession(session, catalog, localProviders = {}, framework = "unknown", skillsInstruction = null, backendState) {
6793
6939
  const xdg = engineXdg();
6794
- const configDir2 = (0, import_node_path13.join)(xdg.configHome, "opencode");
6795
- const dataDir = (0, import_node_path13.join)(xdg.dataHome, "opencode");
6796
- const themesDir = (0, import_node_path13.join)(configDir2, "themes");
6797
- const pluginsDir = (0, import_node_path13.join)(configDir2, "plugins");
6798
- const commandsDir = (0, import_node_path13.join)(configDir2, "commands");
6799
- for (const dir of [themesDir, pluginsDir, commandsDir, dataDir, (0, import_node_path13.join)(xdg.stateHome, "opencode")]) {
6800
- (0, import_node_fs11.mkdirSync)(dir, { recursive: true });
6940
+ const configDir2 = (0, import_node_path14.join)(xdg.configHome, "opencode");
6941
+ const dataDir = (0, import_node_path14.join)(xdg.dataHome, "opencode");
6942
+ const themesDir = (0, import_node_path14.join)(configDir2, "themes");
6943
+ const pluginsDir = (0, import_node_path14.join)(configDir2, "plugins");
6944
+ const commandsDir = (0, import_node_path14.join)(configDir2, "commands");
6945
+ for (const dir of [themesDir, pluginsDir, commandsDir, dataDir, (0, import_node_path14.join)(xdg.stateHome, "opencode")]) {
6946
+ (0, import_node_fs12.mkdirSync)(dir, { recursive: true });
6801
6947
  }
6802
6948
  const imagegenAvailable = installEngineTools(configDir2) && session.img_on !== false;
6803
- const cloudInstructionsPath = (0, import_node_path13.join)(configDir2, CLOUD_INSTRUCTIONS_FILENAME);
6804
- (0, import_node_fs11.writeFileSync)(cloudInstructionsPath, renderCloudInstructions(framework, backendState));
6805
- const skillsPath = (0, import_node_path13.join)(configDir2, "AGENTFUL_SKILLS.md");
6949
+ const cloudInstructionsPath = (0, import_node_path14.join)(configDir2, CLOUD_INSTRUCTIONS_FILENAME);
6950
+ (0, import_node_fs12.writeFileSync)(cloudInstructionsPath, renderCloudInstructions(framework, backendState));
6951
+ const skillsPath = (0, import_node_path14.join)(configDir2, "AGENTFUL_SKILLS.md");
6806
6952
  const instructionPaths = [cloudInstructionsPath];
6807
6953
  if (skillsInstruction) {
6808
- (0, import_node_fs11.writeFileSync)(skillsPath, skillsInstruction);
6954
+ (0, import_node_fs12.writeFileSync)(skillsPath, skillsInstruction);
6809
6955
  instructionPaths.push(skillsPath);
6810
6956
  } else {
6811
- (0, import_node_fs11.rmSync)(skillsPath, { force: true });
6957
+ (0, import_node_fs12.rmSync)(skillsPath, { force: true });
6812
6958
  }
6813
6959
  const config = buildEngineConfig({
6814
6960
  session,
@@ -6817,23 +6963,23 @@ async function writeEngineSession(session, catalog, localProviders = {}, framewo
6817
6963
  imagegenAvailable,
6818
6964
  instructionPaths
6819
6965
  });
6820
- (0, import_node_fs11.writeFileSync)((0, import_node_path13.join)(configDir2, "config.json"), JSON.stringify(config, null, 2));
6821
- const authPath2 = (0, import_node_path13.join)(dataDir, "auth.json");
6822
- (0, import_node_fs11.writeFileSync)(authPath2, mergedAuthJson(readAuthFile(authPath2), session.token));
6966
+ (0, import_node_fs12.writeFileSync)((0, import_node_path14.join)(configDir2, "config.json"), JSON.stringify(config, null, 2));
6967
+ const authPath2 = (0, import_node_path14.join)(dataDir, "auth.json");
6968
+ (0, import_node_fs12.writeFileSync)(authPath2, mergedAuthJson(readAuthFile(authPath2), session.token));
6823
6969
  const { brandingPluginSource: brandingPluginSource2 } = await Promise.resolve().then(() => (init_plugin(), plugin_exports));
6824
- const pluginPath = (0, import_node_path13.join)(pluginsDir, "agentful-branding.tsx");
6825
- (0, import_node_fs11.writeFileSync)(pluginPath, brandingPluginSource2());
6826
- (0, import_node_fs11.writeFileSync)((0, import_node_path13.join)(configDir2, "tui.json"), JSON.stringify({
6970
+ const pluginPath = (0, import_node_path14.join)(pluginsDir, "agentful-branding.tsx");
6971
+ (0, import_node_fs12.writeFileSync)(pluginPath, brandingPluginSource2());
6972
+ (0, import_node_fs12.writeFileSync)((0, import_node_path14.join)(configDir2, "tui.json"), JSON.stringify({
6827
6973
  theme: "agentful",
6828
6974
  plugin: [`file://${pluginPath}`]
6829
6975
  }, null, 2));
6830
- (0, import_node_fs11.writeFileSync)((0, import_node_path13.join)(themesDir, "agentful.json"), JSON.stringify(await resolveTheme(), null, 2));
6976
+ (0, import_node_fs12.writeFileSync)((0, import_node_path14.join)(themesDir, "agentful.json"), JSON.stringify(await resolveTheme(), null, 2));
6831
6977
  for (const name of Object.keys(SLASH_COMMANDS)) {
6832
- (0, import_node_fs11.writeFileSync)((0, import_node_path13.join)(commandsDir, `${name}.md`), commandMarkdown(name));
6978
+ (0, import_node_fs12.writeFileSync)((0, import_node_path14.join)(commandsDir, `${name}.md`), commandMarkdown(name));
6833
6979
  }
6834
6980
  for (const legacy of ["xdg-config", "xdg-data", "xdg-state"]) {
6835
6981
  try {
6836
- (0, import_node_fs11.rmSync)((0, import_node_path13.join)((0, import_node_os5.homedir)(), ".local", "share", "agentful", legacy), { recursive: true, force: true });
6982
+ (0, import_node_fs12.rmSync)((0, import_node_path14.join)((0, import_node_os5.homedir)(), ".local", "share", "agentful", legacy), { recursive: true, force: true });
6837
6983
  } catch {
6838
6984
  }
6839
6985
  }
@@ -6841,8 +6987,8 @@ async function writeEngineSession(session, catalog, localProviders = {}, framewo
6841
6987
  }
6842
6988
 
6843
6989
  // src/lib/skills.ts
6844
- var import_node_fs12 = require("fs");
6845
- var import_node_path14 = require("path");
6990
+ var import_node_fs13 = require("fs");
6991
+ var import_node_path15 = require("path");
6846
6992
 
6847
6993
  // src/generated/skills.json
6848
6994
  var skills_default = {
@@ -6850,7 +6996,7 @@ var skills_default = {
6850
6996
  schema_version: 1,
6851
6997
  skills: {
6852
6998
  "agentful-template-contract": "---\nname: agentful-template-contract\ndescription: Agentful generated-project and template contract for static preview/publish compatibility, scaffold-safe file structure, host-agnostic assets, backend honesty, and no unsupported dependencies. Use when creating a new project, customizing a scaffold/template, editing generated app structure, or fixing preview/publish issues.\n---\n\n# Agentful Template Contract\n\n## Contract\n\nGenerate and edit projects for Agentful's existing platform:\n\n- Static preview and publish serve built files from S3/CloudFront/Cloudflare.\n- Package projects must build to `dist/`, `out/`, or `build/`.\n- Vanilla projects must work without a package install or build step.\n- Managed database and managed actions are configured in the Backend tab, not invented in code.\n\nDo not add server-first framework runtime dependencies (for example Remix / `@remix-run/*`, or a Next.js server). A referenced example repo may inform structure or styling, but this platform serves static builds and does not run those servers.\n\n## File Shape\n\n- Preserve the current stack and file layout unless the user explicitly asks for a migration.\n- For empty workspaces, follow the loaded scaffold skill exactly.\n- Put route- or feature-local UI near the feature. Create shared folders only after real reuse exists.\n- Avoid dumping grounds such as `helpers`, `misc`, or broad `lib` folders when ownership is clear.\n- Keep generated documentation short and accurate; do not describe features that do not exist.\n\n## Hosting Rules\n\n- Asset paths for project-owned files: SPAs with a client-side (history-mode)\n router use root-absolute paths (`base: '/'`, `/assets/...`); router-less or\n multi-page projects use relative paths.\n- Use `/api/...` only for platform runtime APIs.\n- Do not hardcode `mainmvp.com`, `agentful.dev`, preview domains, or user subdomains into app code.\n- Do not add a `<base>` tag.\n- For canonical, Open Graph, sitemap, and manifest URLs, use relative URLs or omit the origin.\n- For SPAs on static hosting, use history-mode routing with `base: '/'` (never\n hash routing) \u2014 the platform falls unknown deep-links back to `index.html`, so\n routes resolve on hard refresh with clean URLs (no `#`).\n\n## Backend Honesty\n\n- When a backend is configured (`status: active`), use it for real data, auth, and actions.\n- When no backend is configured, still build the requested UI from clearly-labeled sample/demo data (one replaceable module). Do not refuse or stop \u2014 surface the Backend-tab note in your final response instead.\n- Sample data must read as sample. Do NOT fake auth that \"logs in\", saves that claim to persist across reloads, or payment/webhook flows that pretend to fire \u2014 those mislead the user. Presentation data (example metrics, sample listings) is fine; a fake real-backend contract is not.\n- Never store secret keys in frontend code, templates, `.env`, or committed files.\n- Public client keys may be placeholders only when the target integration actually uses public keys.\n\n## Content Honesty\n\nDo not invent:\n\n- customer logos, testimonials, reviews, awards, revenue, user counts, certifications, compliance claims, or legal assurances\n- real prices, policies, medical/financial claims, or guarantees unless the user supplies them\n\nUse neutral placeholder copy or proof-ready sections instead.\n\n## Before Finishing\n\n- Verify imports, references, asset paths, and routes are defined.\n- Run the relevant build when a build script exists.\n- Confirm the expected output folder contains an `index.html`.\n- For UI work, include responsive behavior and basic loading, empty, error, and success states where the feature implies them.\n",
6853
- "agentful-managed-db": "---\nname: agentful-managed-db\ndescription: Managed Database protocol for `database.mode == managed`. Covers schema upsert, CRUD against `/api/p/{PROJECT_ID}/data/*` and `/api/p/{PROJECT_ID}/auth/*`, error-code remediation, and per-framework client patterns (Vue, React, Svelte, SvelteKit, Astro, Vanilla). Load when the backend preamble shows `Database: managed`.\n---\n\n## When To Use\n\nLoad this skill **only** when `agentful-backend-state` reports `database.mode: \"managed\"` with `status: \"active\"`. Do not load it for `byo` (Supabase / custom server) or when the database is not configured.\n\n## Hard Rules\n\n1. **Collections do not auto-create.** Writes to a non-existent collection return 404 with `error.code: not_found`. For every collection your code reads or writes, if it is not listed in the backend preamble's `Managed collections` block, you MUST run `agentful-managed-collections upsert <project_id> '<json>'` BEFORE writing the code that touches it.\n2. **Never wrap data-API calls in a swallow-all `try/catch`.** Swallowing masks 4xx errors and produces apps that look-fine-but-write-nothing.\n3. **Never set a `seeded` flag unless every write returned 201.** Partial-success seeds drift state silently.\n4. **Do not call this a \"server\".** It is a managed database behind a gateway. Use \"the database\" when talking to the user.\n5. **Do not target `/data/_collections`** from generated code. That's the owner-only schema endpoint; use the `agentful-managed-collections` CLI for schema work.\n6. **On 5xx, do not speculate.** Surface `error.correlation_id` to the user verbatim and stop. Do not invent internal causes (DynamoDB, operators, system collections, etc.).\n\n## Authoring Protocol \u2014 for every collection touch\n\nRun, in order:\n\n1. **Read the preamble.** The `[BACKEND STATUS]` block lists existing `Managed collections` with their fields and access rules. If your target collection is there with the right shape, skip to step 3.\n2. **Upsert if missing or schema mismatch:**\n ```\n agentful-managed-collections upsert <project_id> '{\"name\":\"todos\",\"access_rule\":\"owner\",\"schema\":{\"fields\":[{\"name\":\"title\",\"type\":\"string\",\"required\":true},{\"name\":\"done\",\"type\":\"boolean\"}]}}'\n ```\n Field types: `string`, `text`, `number`, `boolean`, `select` (with `options`), `datetime` (ISO 8601 string), `json` (object or array).\n Access rules: `public` (anyone), `authenticated` (any logged-in end-user), `owner` (only `created_by` user), `admin` (only end-users whose `_users.role` is `admin`).\n3. **Write the client code** using the patterns below. Use the EXACT field names from the schema. Do not invent fields.\n4. **Test the happy path** by inspecting the response. Real 201 / 200, not a swallowed error.\n\n## Choosing An Access Rule\n\n`access_rule` is set per collection at upsert time and enforced on every end-user\n(`/data/*`) request. There are exactly four rules \u2014 pick by use case:\n\n| Use case | Rule | Why |\n|---|---|---|\n| Content anyone may read/write without login (public poll, guestbook) | `public` | No JWT required. |\n| Public content the app seeds once and the UI only reads | `public` | Seed at build time; clients read only. |\n| Shared data **every** logged-in user may read AND edit (team wiki, shared catalog) | `authenticated` | Any valid end-user JWT passes. **No per-row owner check.** |\n| Per-user private data (todos, drafts, a user's own orders) | `owner` | Only the `created_by` end-user can read/update/delete each doc. |\n| Data only the app's admins may read/write (moderation queues, settings) | `admin` | Only end-users whose `_users.role` is `admin` (owner-set, see First Admin below). |\n| Per-user data an **admin must also access** (invoices, tickets, client records) | `owner` + admin via Action | `owner` protects the client; admin reads/writes through a Managed Action. See RBAC below. |\n| A field only the server may set (`role`, `plan`, `verified`, `balance`) | `owner`, with that field written **only** via an Action | No field-level rules exist \u2014 gate the whole mutation behind an Action. |\n\n**Two traps to design around:**\n\n1. **`authenticated` is NOT per-user isolation.** It means *every* logged-in\n user can read and write *all* documents in the collection. For \"each user\n sees only their own\", use `owner`.\n2. **There is no combined `owner_or_admin` rule and no role concept in the data\n layer.** A multi-role portal (admin / member / client) cannot be expressed by\n `access_rule` alone. The supported pattern is `owner` + a Managed Action that\n verifies the caller \u2014 see **RBAC & Secure Role Assignment** under Managed\n Actions. (Requires `server.mode == managed`.)\n\n## API Surface\n\nBase: `/api/p/{PROJECT_ID}/`\n\n**Auth (end-user):**\n- `POST auth/register` \u2014 `{email, password, display_name?}`. Two response shapes:\n - Verification pipeline ACTIVE (project has `config.auth`, default): `201 {verification_required:true, user:{...}}` \u2014 **NO token yet**; the user must confirm their email first (mail is sent automatically).\n - Legacy project (no `config.auth`) or `require_verified_login:false`: `201 {token, verification_required:false, user:{...}}`.\n- `POST auth/login` \u2014 `{email, password}` \u2192 `{token, user:{...}}`. Blocks with `403 email_unverified` when the project requires verified logins and the account is not verified yet \u2192 show a \"check your inbox\" state with a resend button.\n- `GET auth/me` \u2014 Bearer token \u2192 `{user:{...}}`\n- `POST auth/verify` \u2014 `{uid, token}` (from the mail link) \u2192 `{token, user}` (auto-login after verification).\n- `POST auth/resend-verification` \u2014 `{email}` \u2192 always `200 {sent:true}` (no user enumeration).\n- `POST auth/request-password-reset` \u2014 `{email}` \u2192 always `200 {sent:true}` (no user enumeration).\n- `POST auth/reset-password` \u2014 `{uid, token, password}` \u2192 `200 {reset:true}`. Also marks the mailbox verified.\n\n`user` shape: `{id, email, display_name, role, verified, provider, created_at}`.\n\n**Auth mail links:** verification/reset mails link to the deployed app as\n`{app_url}/?ta_action=verify&uid=\u2026&token=\u2026` and `{app_url}/?ta_action=reset&uid=\u2026&token=\u2026`.\n**Every generated app with auth MUST handle these two query params on load**\n(see Client Patterns).\n\n**Login methods governance:** offer ONLY the login methods the project's\n`config.auth.methods` allows (check with `agentful-auth-config get`;\ndefault `[\"email\"]`). Do NOT generate \"Sign in with Google\"/SSO buttons unless\n`google`/`oidc` is listed \u2014 the platform refuses unlisted methods server-side.\n\n**Google login (when `google` IS listed):** a \"Continue with Google\" button\ncalls `googleAuth.start()` (see Client Patterns) \u2192 central broker\n`api.agentful.dev/auth/oauth/google/start` \u2192 Google \u2192 back to the app with the\nJWT in the URL fragment; call `handleGoogleReturn()` at startup to complete\nthe login. Google users arrive `verified: true` (Google verified the mailbox),\nexisting email accounts with the same address are linked automatically, and\nthe `admin_email` bootstrap applies. Show `auth_error` codes as a friendly\nmessage (`auth_method_not_allowed` \u2192 \"Google login is not available for this\napp\"); never retry in a loop.\n\n**Data:**\n- `GET data/{collection}` \u2014 list (paginated; `?limit=`, `?cursor=`)\n- `GET data/{collection}/{docId}` \u2014 single doc\n- `POST data/{collection}` \u2014 body `{data: {...}}` \u2192 `{ok:true, data:{doc_id, collection, data, created_at}}`\n- `PUT data/{collection}/{docId}` \u2014 body `{data: {...}}` \u2192 updated doc\n- `DELETE data/{collection}/{docId}` \u2192 `{ok:true, data:{deleted, collection}}`\n\nEnd-user routes (above) require `Authorization: Bearer <token>` from `auth/register` or `auth/login`. The collection's `access_rule` enforces what each token may read/write.\n\n## Response Shapes\n\n**Success:** `{ \"ok\": true, \"data\": {...} }` \u2014 `data` for lists has `{documents:[...], count, cursor}`.\n\n**Error:** `{ \"ok\": false, \"error\": { \"code\": \"...\", \"message\": \"...\", \"correlation_id\"?: \"...\" } }`\n\nStatus codes are HTTP-conventional (201 on create, 200 on read/update/delete, 4xx for client errors, 5xx for platform).\n\n## Error Code \u2192 Remediation\n\n| `error.code` | HTTP | What it means | What to do |\n|---|---|---|---|\n| `not_found` | 404 | Collection doesn't exist, OR doc id doesn't exist | If collection: run `agentful-managed-collections upsert` then retry. If doc: surface to user. |\n| `email_unverified` | 403 | Login blocked until the user confirms their email | Show \"confirm your email\" state + resend button (`auth/resend-verification`). |\n| `invalid_token` | 400 | Verification/reset link invalid, expired, or already used | Offer resend (`resend-verification`) or a new reset request. |\n| `too_many_attempts` | 429 | Auth rate limit hit (failed logins / mail requests) | Tell the user to wait a few minutes; do not auto-retry. |\n| `email_infra_unconfigured` | 409 | Project has no email infrastructure selected | Tell the BUILDER (not the end-user): choose \"Agentful Email\" or BYO in project settings \u2192 Email infrastructure. |\n| `email_send_failed` | 502 | Mail transport failed transiently | Tell the user to try again later. |\n| `schema_validation_failed` | 400 | Payload doesn't match the collection's schema | Re-read the schema in the preamble; fix field names/types/required-ness; do not retry blindly. |\n| `readonly_collection` | 403 | Collection or doc is system-protected (e.g. `_users` via end-user route) | Use the correct route (e.g. `auth/register` for `_users`); do not retry. |\n| `forbidden` | 403 | Access rule denied this end-user | Tell the user they need to log in / lack permission. |\n| `already_exists` | 409 | `doc_id` collision or conditional check failed | Let `doc_id` auto-generate (omit it). |\n| `too_large` | 413 | Document > 256 KB | Split or trim payload. |\n| `quota_exceeded` | 429 | DDB throttling / request-limit spillover (transient) | The doctor returns `action: retry_with_backoff`. Sleep + retry up to 3 times per `details.backoff_ms`. **Surface `correlation_id` to the user ONLY after all attempts exhaust.** |\n| `transient_storage_error` | 503 | DDB internal / service-unavailable (transient) | Same as `quota_exceeded`: doctor returns `retry_with_backoff`; engine handles silently until budget exhausts. |\n| `internal_storage_error` / `write_failed` / `delete_failed` | 500 | Platform-side error, NOT classified retryable | Delegate to `@agentful-managed-db-doctor` with `correlation_id`. Surface its `user_message` verbatim. Do NOT retry in a loop. Do NOT invent a root cause. |\n\n## Client Patterns\n\nA tiny client used everywhere. Define once per project; reuse for all collections.\n\n### Vanilla / shared base\n\n```js\n// src/lib/data.js\nconst BASE = `/api/p/${PROJECT_ID}`; // set PROJECT_ID at build time\nconst tokenKey = 'mm_auth_token';\n\nfunction authHeader() {\n const t = localStorage.getItem(tokenKey);\n return t ? { Authorization: `Bearer ${t}` } : {};\n}\n\nasync function jsonOrThrow(res) {\n const body = await res.json().catch(() => ({}));\n if (!res.ok || !body.ok) {\n const err = new Error(body.error?.message || `HTTP ${res.status}`);\n err.code = body.error?.code;\n err.correlation_id = body.error?.correlation_id;\n err.status = res.status;\n throw err;\n }\n return body.data;\n}\n\nexport const auth = {\n async register(email, password, display_name) {\n const data = await jsonOrThrow(await fetch(`${BASE}/auth/register`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password, display_name }),\n }));\n // verification_required \u2192 NO token yet; caller must show \"check your inbox\".\n if (data.token) localStorage.setItem(tokenKey, data.token);\n return data; // {verification_required, user, token?}\n },\n async login(email, password) {\n const data = await jsonOrThrow(await fetch(`${BASE}/auth/login`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password }),\n }));\n localStorage.setItem(tokenKey, data.token);\n return data.user;\n },\n async verify(uid, token) {\n const data = await jsonOrThrow(await fetch(`${BASE}/auth/verify`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ uid, token }),\n }));\n localStorage.setItem(tokenKey, data.token); // auto-login after verify\n return data.user;\n },\n async resendVerification(email) {\n return jsonOrThrow(await fetch(`${BASE}/auth/resend-verification`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n }));\n },\n async requestPasswordReset(email) {\n return jsonOrThrow(await fetch(`${BASE}/auth/request-password-reset`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n }));\n },\n async resetPassword(uid, token, password) {\n return jsonOrThrow(await fetch(`${BASE}/auth/reset-password`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ uid, token, password }),\n }));\n },\n logout() { localStorage.removeItem(tokenKey); },\n token() { return localStorage.getItem(tokenKey); },\n};\n\n// Google login (ONLY when 'google' \u2208 config.auth.methods \u2014 never generate\n// this button otherwise; the platform refuses unlisted methods server-side).\n// Redirects to the central Agentful OAuth broker; after Google consent the\n// broker 302s back to `redirect` with the app JWT in the URL FRAGMENT:\n// https://<your-app>/#token=<jwt>&provider=google (or #auth_error=<code>)\nexport const googleAuth = {\n start(redirect = location.origin + '/') {\n const url = new URL('https://api.agentful.dev/auth/oauth/google/start');\n url.searchParams.set('project_id', PROJECT_ID);\n url.searchParams.set('redirect', redirect); // must be THIS app's https origin\n location.href = url.toString();\n },\n};\n\n// REQUIRED whenever the Google button is generated: pick up the broker return\n// on app load (fragment token \u2192 login; auth_error \u2192 user-visible message).\nexport function handleGoogleReturn() {\n const h = new URLSearchParams(location.hash.slice(1));\n const token = h.get('token'), err = h.get('auth_error');\n if (!token && !err) return null;\n history.replaceState(null, '', location.pathname + location.search); // strip token from URL\n if (err) return { ok: false, error: err }; // e.g. auth_method_not_allowed, oauth_failed\n localStorage.setItem(tokenKey, token);\n return { ok: true, provider: h.get('provider') || 'google' };\n}\n\n// REQUIRED in every app with auth: handle the mail links on app load.\n// Call once at startup (before router init is fine).\nexport async function handleAuthMailAction() {\n const p = new URLSearchParams(location.search);\n const action = p.get('ta_action'), uid = p.get('uid'), token = p.get('token');\n if (!action || !uid || !token) return null;\n history.replaceState(null, '', location.pathname); // strip token from URL\n if (action === 'verify') {\n try { const user = await auth.verify(uid, token); return { action, ok: true, user }; }\n catch (e) { return { action, ok: false, error: e.code || 'invalid_token' }; }\n }\n if (action === 'reset') return { action, ok: true, uid, token }; // show new-password form, then auth.resetPassword(uid, token, pw)\n return null;\n}\n\nexport const data = {\n async list(collection, opts = {}) {\n const qs = new URLSearchParams(opts).toString();\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}${qs ? '?' + qs : ''}`, {\n headers: { ...authHeader() },\n }));\n },\n async get(collection, docId) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}/${docId}`, {\n headers: { ...authHeader() },\n }));\n },\n async create(collection, data) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...authHeader() },\n body: JSON.stringify({ data }),\n }));\n },\n async update(collection, docId, data) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}/${docId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json', ...authHeader() },\n body: JSON.stringify({ data }),\n }));\n },\n async remove(collection, docId) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}/${docId}`, {\n method: 'DELETE',\n headers: { ...authHeader() },\n }));\n },\n};\n```\n\n### React / Vue / Svelte\n\nUse the same `data.js` / `data.ts` module above; wrap in framework-native state primitives.\n\n- **React:** call from `useEffect` for reads, `useState` for results; surface `err.code`/`err.correlation_id` to the user when caught. Do not put data calls in render bodies.\n- **Vue:** use `onMounted` for reads and a `ref()` for results; same error surfacing.\n- **Svelte / SvelteKit:** call from `onMount` (or a `load` function in SvelteKit); SvelteKit static-adapter projects must NOT use server `load` (no Node runtime in static deploy).\n- **Astro:** call only from client-side islands; no server fetch (static-only build).\n\n### TypeScript types\n\nGenerate the per-collection type from the preamble's field list:\n\n```ts\n// Example for a collection with fields: title:string*, done:boolean\ntype Todo = { title: string; done?: boolean };\n\n// And response wrappers:\ntype DataDoc<T> = { doc_id: string; collection: string; data: T; created_at: string };\ntype DataList<T> = { documents: DataDoc<T>[]; count: number; cursor?: string };\n```\n\n## Anti-patterns\n\n- \u274C `try { await data.create(...) } catch { /* ignore */ }` \u2014 masks failures.\n- \u274C Hardcoding `doc_id` for \"convenience\" \u2014 causes `already_exists` 409 on retry.\n- \u274C Writing to a collection name that doesn't appear in the preamble \u2014 `not_found` 404.\n- \u274C Using the schema endpoint `/data/_collections` from client code \u2014 owner-only, end-users get 403.\n- \u274C Storing the JWT anywhere other than `localStorage` under a project-scoped key; do not put it in cookies (CORS) or in `sessionStorage` (lost on tab close).\n- \u274C Telling the user \"the database is down\" because of a 5xx. Surface the `correlation_id` and stop.\n- \u274C Surfacing `correlation_id` on transient errors (`quota_exceeded`, `transient_storage_error`) before the doctor's `retry_with_backoff` budget is exhausted. The whole point is the user sees nothing while the retry loop is in play; only escalate after all `max_attempts` fail.\n\n## Diagnostic delegation\n\nIf you hit a 5xx that doesn't map to a retry-able 4xx in the table above, do not diagnose yourself. Delegate to `@agentful-managed-db-doctor` (added in PR 1.3) with the `correlation_id` from the response. The doctor has constrained tools and cannot fabricate platform internals.\n\n---\n\n## Managed Actions (only when `server.mode == managed`)\n\nManaged Actions are small Node.js functions the platform runs for the project at `/api/p/{PROJECT_ID}/actions/{name}`. Use them when a frontend operation needs (a) a secret API key, (b) a non-public/secured external API, or (c) server-enforced trust (price computation, signature verification, admin actions). For pure CRUD against the managed DB, use the data API directly; do NOT route everything through an action.\n\n### Hard rules (Managed Actions)\n\n1. **Upsert FIRST, fetch SECOND.** If your generated code calls `fetch('/api/p/.../actions/{name}')`, you MUST upsert the action via the CLI BEFORE writing the fetch call. An undeployed action returns `404 action_not_found`; the preamble's `Managed actions` list is the ground truth for what exists.\n2. **Only `ctx.fetch`, `ctx.data`, `ctx.secrets`, `ctx.user`, `ctx.body` and approved npm packages.** No `require('fs')`, `require('child_process')`, `require('http')`, `require('https')`, `require('net')`, `require('os')`, `require('path')`, `require('process')`, `require('vm')`, `require('cluster')`, `require('worker_threads')`. The validator rejects these at upload time with `{code: 'action_validation_failed', reason: 'disallowed_require'}`.\n3. **Secrets are read with `await ctx.secrets.get('<name>')` \u2014 never property access.** `ctx.secrets` has exactly one method, `get(key)`. `ctx.secrets.SOME_KEY` is silently `undefined`. Secret names must match `^(database|server)\\.[a-z][a-z0-9_]{0,126}$` \u2014 use `server.stripe_secret_key`, not `STRIPE_SECRET_KEY` (uppercase, unprefixed names cannot even be stored in Backend \u2192 Secrets).\n4. **Actions are publicly invokable \u2014 authorize the caller yourself.** `ctx.user` is the JWT-verified end-user (`{ id, email, pid }`) or `null`. Any action that touches a secret, writes data, or returns non-public information must start with a `ctx.user` check; nothing else gates who can call it.\n5. **Outbound calls from inside an action must use `ctx.fetch`**, not a bare `fetch`. `ctx.fetch` injects `X-Action-Depth` on self-action URLs so the platform's loop detector can break runaway recursion. External URLs are passed through unchanged.\n6. **Cost shape.** 5 s timeout, 256 MB RAM, 1 MB request body, per-project concurrent invocations capped at 10. Plan for `429 concurrency_exceeded` under load and surface it to the user gracefully (e.g. retry with backoff or \"try again in a moment\").\n\n### Action shape\n\n```js\n// .server/actions/checkout.js\nmodule.exports = async function (ctx) {\n // ctx.body \u2014 parsed JSON request body\n // ctx.user \u2014 JWT-verified end-user { id, email, pid }, or null if not logged in\n // ctx.data \u2014 same CRUD surface as the public data API, scoped to this project\n // ctx.secrets \u2014 async accessor for Backend \u2192 Secrets: await ctx.secrets.get('server.stripe_secret_key')\n // ctx.fetch \u2014 depth-aware fetch wrapper\n if (!ctx.user) return { error: 'auth_required' };\n const apiKey = await ctx.secrets.get('server.stripe_secret_key');\n if (!apiKey) return { error: 'missing_server_secret' };\n const stripeRes = await ctx.fetch('https://api.stripe.com/v1/checkout/sessions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ /* \u2026 */ }).toString(),\n });\n const session = await stripeRes.json();\n return { url: session.url };\n};\n```\n\n### Authoring protocol (engine flow)\n\n1. Read the preamble's `Managed actions` block. If your target name is already deployed with the right shape, skip to step 3.\n2. **Upsert:** write the action source to a local temp file, then `agentful-managed-actions upsert <project_id> <name> <file_path>`. The validator runs on both the public PUT-files path and this CLI; same rejection rules.\n3. Write the frontend `fetch('/api/p/<project_id>/actions/<name>', { method: 'POST', body: JSON.stringify(payload) })`. Include `Content-Type: application/json` on POSTs.\n4. Test once with `agentful-managed-actions invoke <project_id> <name> --body '{\"\u2026\":\"\u2026\"}'` to confirm the deployment landed.\n\n### Action-invocation error codes (response body)\n\n| `error.code` | HTTP | What it means | What to do |\n|---|---|---|---|\n| `action_not_found` | 404 | The action with that name doesn't exist | Upsert it first. |\n| `action_validation_failed` | 400 | Validator rejected the source (size, filename, disallowed require) | Fix per `reason` field; do not retry. |\n| `concurrency_exceeded` | 429 | Per-project cap reached | Backoff + retry, or surface to user. |\n| `action_loop_detected` | 508 | `X-Action-Depth >= 5` \u2014 too many self-calls in a chain | Refactor; you cannot self-recurse beyond depth 5. |\n| `timeout` | 408 | Action exceeded 5 s | Move heavy work out of the action or break into smaller calls. |\n| `body_too_large` | 413 | Request body > 1 MB | Trim the payload. |\n| `action_too_large` | 413 | Action source file > 256 KB | Split into multiple actions. |\n| `runtime_error` | 500 | Action threw at runtime | Read the message; common causes are unhandled rejections, missing `await`, or accessing undefined ctx fields. |\n\n### Anti-patterns\n\n- \u274C Putting a Stripe / OpenAI / Resend API key in frontend code. It must live in `ctx.secrets`.\n- \u274C `ctx.secrets.STRIPE_SECRET_KEY` (property access). The secrets API is `await ctx.secrets.get('server.stripe_secret_key')`; property access is silently `undefined`, and uppercase/unprefixed names cannot be stored at all.\n- \u274C `ctx.user.sub`. The verified user object is `{ id, email, pid }` \u2014 the JWT `sub` claim arrives as `ctx.user.id`.\n- \u274C An action that reads secrets or writes data without checking `ctx.user` first. Actions are publicly invokable; your check is the only authorization.\n- \u274C Calling `fetch('/api/p/.../actions/foo')` without first running `agentful-managed-actions upsert`. Will return 404.\n- \u274C Recursive actions calling themselves to \"spread work\". Will trip the depth guard at 5.\n- \u274C Using bare `fetch` instead of `ctx.fetch` from inside an action. The depth header won't propagate; you bypass the loop guard.\n- \u274C Naming actions `Hello.js`, `_internal.js`, or `actions/sub/foo.js`. The validator rejects (uppercase, leading underscore, subdirectory).\n- \u274C Hardcoding the API base URL into the action's `ctx.fetch` calls to other actions. Use a relative path or the project's own API origin.\n\n### `ctx.data` Is Privileged \u2014 It Bypasses `access_rule`\n\n`ctx.data` inside an action talks to the database **directly, with no\n`access_rule` enforcement**. It is a project-scoped, owner-level surface \u2014 the\nopposite of the `/data/*` end-user route:\n\n- It reads and writes **every** document in **every** collection, regardless of\n whether that collection is `owner`, `authenticated`, or `public`.\n- It does **not** check `created_by`. An action can read one user's `owner`\n docs and write into another user's.\n- Documents created via `ctx.data.create` are attributed `created_by: \"action\"`,\n never to an end-user. If you need owner attribution, store the owner's id in\n the document `data` yourself (e.g. `{ user_id: ctx.user.id, ... }`) and\n filter on it.\n- `ctx.data.list(collection, { limit })` returns a **plain array** of docs\n (`[{ doc_id, data, created_by, created_at }]`, NOT `{ documents: [...] }`),\n caps at 100, and does **no server-side filtering** \u2014 you filter in JS. For\n data sets that can exceed 100 rows, store an explicit owner/lookup field and\n design around the cap; do not assume `list` returns everything.\n\nThis is the intended mechanism for trusted/admin work. The trade-off: an action\nis only as safe as its own checks. **Always verify `ctx.user` before any\ncross-user read or write.**\n\n### RBAC & Secure Role Assignment (`owner` + Action)\n\nThe managed DB has **no role concept and no field-level validation**. On the\nend-user `/data/*` route the client controls the entire document body \u2014\nincluding any `role` field. Design around two facts:\n\n1. **Privilege escalation is possible by default.** If a `profiles` collection\n is `authenticated` or `owner`, a client can register and POST\n `{ role: \"admin\" }` for themselves. `owner` does NOT stop this \u2014 the user\n owns their own profile.\n2. **`owner` blocks admins too.** An `owner` collection correctly hides a\n client's data from other clients, but an admin also cannot read it over\n `/data/*`. Admin access must go through an action using `ctx.data`.\n\nSecure pattern \u2014 keep `role` server-owned and gate every change behind an\naction that verifies the **caller** is already an admin:\n\n```js\n// .server/actions/set-role.js \u2014 upsert BEFORE calling it from the client\nmodule.exports = async function (ctx) {\n if (!ctx.user) return { error: 'auth_required' };\n // 1. Verify the CALLER is an admin (ctx.data ignores access_rule, so this\n // works even though `profiles` is `owner`).\n const all = await ctx.data.list('profiles', { limit: 100 });\n const me = all.find(d => d.data.user_id === ctx.user.id);\n if (!me || me.data.role !== 'admin') return { error: 'forbidden' };\n // 2. Validate input, then apply to the target.\n const { target_user_id, role } = ctx.body || {};\n if (!['admin', 'member', 'client'].includes(role)) return { error: 'bad_role' };\n const target = all.find(d => d.data.user_id === target_user_id);\n if (!target) return { error: 'not_found' };\n await ctx.data.update('profiles', target.doc_id, { ...target.data, role });\n return { ok: true };\n};\n```\n\nRules for this pattern:\n\n- The client UI must **never** write the `role` field over `/data/*`. On\n self-registration, create the profile without `role` (or force a non-privileged\n default in the action) \u2014 never trust a client-sent role.\n- \"Owner OR admin\" **reads** (an admin viewing any client's invoices) use the\n same shape: keep the collection `owner`, expose admin access through an action\n that verifies `ctx.user` is an admin, then uses `ctx.data` to fetch across users.\n- **Bootstrapping the first admin:** see **First Admin \u2014 mode-correct\n protocol** below. Never invent a client-reachable route for it.\n- The 100-row `ctx.data.list` cap applies: if `profiles` can exceed 100 rows,\n this scan-in-JS lookup is unreliable. Until server-side filtering exists,\n store role lookups in a bounded collection or key admins by a known id set.\n\n## First Admin \u2014 mode-correct protocol\n\nWhen the app needs an admin (dashboard, moderation, `admin`-ruled collections),\nask the builder **\"How should the first admin account be created?\"** and offer\nONLY these options \u2014 they map to the platform's `_users.role` system\n(`user`/`admin`), which is what the `admin` access rule checks:\n\n1. **Fixed admin email (recommended).** Ask the builder for the address, then\n run:\n ```\n agentful-auth-config set $PROJECT_ID '{\"admin_email\":\"chef@firma.de\"}'\n ```\n Whoever registers (or later logs in) with exactly that address is promoted\n to `role: admin` **server-side, only after email verification** \u2014 no code\n needed in the app.\n2. **Manual via Data Manager.** The builder opens **Backend \u2192 Data Manager \u2192\n `_users` tab**, selects the registered user and sets the `role` dropdown to\n `admin` (the `verified` flag can also be set there if a mail never arrived).\n\n### `agentful-auth-config` CLI\n\n- `agentful-auth-config get $PROJECT_ID` \u2014 current `config.auth` state\n (`auth: null` = hardened pipeline not activated yet \u2192 registering works\n legacy-style without verification) plus `email_infrastructure`\n (`\"\"` = builder has not chosen one; verification mails will fail with\n `email_infra_unconfigured` until they pick one in project settings).\n- `agentful-auth-config set $PROJECT_ID '<json>'` \u2014 merge into `config.auth`.\n Keys: `methods` (subset of `email|google|oidc`; the server clamps against\n the org allowlist \u2014 verify the result in the response), `require_verified_login`\n (bool; default true once auth is configured), `admin_email`, `language`\n (`de`|`en`, auth-mail language).\n- Setting ANY key activates the hardened pipeline (verification mails +\n verified-login gate). Before activating it, run `get` and make sure\n `email_infrastructure` is not empty \u2014 otherwise tell the builder to choose\n Agentful Email or BYO in project settings first.\n- Email infrastructure is NOT settable via this CLI by design (audited\n builder decision, DE-data-region notice).\n\n**NEVER offer \"run SQL\" / \"insert into the database manually\" for\n`database.mode == managed` \u2014 there is no SQL surface; the managed DB is not a\nSQL database.** SQL-based instructions apply only to BYO-Supabase projects\n(different skill, different mode).\n\nPrefer the platform `_users.role` + `admin` access rule over inventing an\napp-level `profiles.role` system when the requirement is just \"one admin can\nsee/manage everything\" \u2014 the profiles-RBAC pattern above is for MULTI-role\napps (admin/member/client) that need roles beyond `user`/`admin`.\n",
6999
+ "agentful-managed-db": "---\nname: agentful-managed-db\ndescription: Managed Database protocol for `database.mode == managed`. Covers schema upsert, CRUD against `/api/p/{PROJECT_ID}/data/*` and `/api/p/{PROJECT_ID}/auth/*`, error-code remediation, and per-framework client patterns (Vue, React, Svelte, SvelteKit, Astro, Vanilla). Load when the backend preamble shows `Database: managed`.\n---\n\n## When To Use\n\nLoad this skill **only** when `agentful-backend-state` reports `database.mode: \"managed\"` with `status: \"active\"`. Do not load it for `byo` (Supabase / custom server) or when the database is not configured.\n\n## Hard Rules\n\n1. **Collections do not auto-create.** Writes to a non-existent collection return 404 with `error.code: not_found`. For every collection your code reads or writes, if it is not listed in the backend preamble's `Managed collections` block, you MUST run `agentful-managed-collections upsert <project_id> '<json>'` BEFORE writing the code that touches it.\n2. **Never wrap data-API calls in a swallow-all `try/catch`.** Swallowing masks 4xx errors and produces apps that look-fine-but-write-nothing.\n3. **Never set a `seeded` flag unless every write returned 201.** Partial-success seeds drift state silently.\n4. **Do not call this a \"server\".** It is a managed database behind a gateway. Use \"the database\" when talking to the user.\n5. **Do not target `/data/_collections`** from generated code. That's the owner-only schema endpoint; use the `agentful-managed-collections` CLI for schema work.\n6. **On 5xx, do not speculate.** Surface `error.correlation_id` to the user verbatim and stop. Do not invent internal causes (DynamoDB, operators, system collections, etc.).\n\n## Authoring Protocol \u2014 for every collection touch\n\nRun, in order:\n\n1. **Read the preamble.** The `[BACKEND STATUS]` block lists existing `Managed collections` with their fields and access rules. If your target collection is there with the right shape, skip to step 3.\n2. **Upsert if missing or schema mismatch:**\n ```\n agentful-managed-collections upsert <project_id> '{\"name\":\"todos\",\"access_rule\":\"owner\",\"schema\":{\"fields\":[{\"name\":\"title\",\"type\":\"string\",\"required\":true},{\"name\":\"done\",\"type\":\"boolean\"}]}}'\n ```\n Field types: `string`, `text`, `number`, `boolean`, `select` (with `options`), `date` (ISO 8601 calendar date `YYYY-MM-DD`), `datetime` (ISO 8601 string), `json` (object or array). Any other type is rejected by the platform (400 with the allowed list).\n Access rules: `public` (anyone), `authenticated` (any logged-in end-user), `owner` (only `created_by` user), `admin` (only end-users whose `_users.role` is `admin`).\n Every successful upsert is also DECLARED: the command mirrors the collection (as the platform stored it) into `.agentful/backend.json` in the workspace and answers `\"declaration\": \".agentful/backend.json\"`. That file is the project's backend declaration \u2014 it travels with the code (a local `agentful push` applies it again, idempotently) and the Backend tab shows it. Do not edit it to claim a collection exists; the upsert output is the only confirmation. Never commit it to `.gitignore`.\n3. **Write the client code** using the patterns below. Use the EXACT field names from the schema. Do not invent fields.\n4. **Test the happy path** by inspecting the response. Real 201 / 200, not a swallowed error.\n\n## Choosing An Access Rule\n\n`access_rule` is set per collection at upsert time and enforced on every end-user\n(`/data/*`) request. There are exactly four rules \u2014 pick by use case:\n\n| Use case | Rule | Why |\n|---|---|---|\n| Content anyone may read/write without login (public poll, guestbook) | `public` | No JWT required. |\n| Public content the app seeds once and the UI only reads | `public` | Seed at build time; clients read only. |\n| Shared data **every** logged-in user may read AND edit (team wiki, shared catalog) | `authenticated` | Any valid end-user JWT passes. **No per-row owner check.** |\n| Per-user private data (todos, drafts, a user's own orders) | `owner` | Only the `created_by` end-user can read/update/delete each doc. |\n| Data only the app's admins may read/write (moderation queues, settings) | `admin` | Only end-users whose `_users.role` is `admin` (owner-set, see First Admin below). |\n| Per-user data an **admin must also access** (invoices, tickets, client records) | `owner` + admin via Action | `owner` protects the client; admin reads/writes through a Managed Action. See RBAC below. |\n| A field only the server may set (`role`, `plan`, `verified`, `balance`) | `owner`, with that field written **only** via an Action | No field-level rules exist \u2014 gate the whole mutation behind an Action. |\n\n**Two traps to design around:**\n\n1. **`authenticated` is NOT per-user isolation.** It means *every* logged-in\n user can read and write *all* documents in the collection. For \"each user\n sees only their own\", use `owner`.\n2. **There is no combined `owner_or_admin` rule and no role concept in the data\n layer.** A multi-role portal (admin / member / client) cannot be expressed by\n `access_rule` alone. The supported pattern is `owner` + a Managed Action that\n verifies the caller \u2014 see **RBAC & Secure Role Assignment** under Managed\n Actions. (Requires `server.mode == managed`.)\n\n## API Surface\n\nBase: `/api/p/{PROJECT_ID}/`\n\n**Auth (end-user):**\n- `POST auth/register` \u2014 `{email, password, display_name?}`. Two response shapes:\n - Verification pipeline ACTIVE (project has `config.auth`, default): `201 {verification_required:true, user:{...}}` \u2014 **NO token yet**; the user must confirm their email first (mail is sent automatically).\n - Legacy project (no `config.auth`) or `require_verified_login:false`: `201 {token, verification_required:false, user:{...}}`.\n- `POST auth/login` \u2014 `{email, password}` \u2192 `{token, user:{...}}`. Blocks with `403 email_unverified` when the project requires verified logins and the account is not verified yet \u2192 show a \"check your inbox\" state with a resend button.\n- `GET auth/me` \u2014 Bearer token \u2192 `{user:{...}}`\n- `POST auth/verify` \u2014 `{uid, token}` (from the mail link) \u2192 `{token, user}` (auto-login after verification).\n- `POST auth/resend-verification` \u2014 `{email}` \u2192 always `200 {sent:true}` (no user enumeration).\n- `POST auth/request-password-reset` \u2014 `{email}` \u2192 always `200 {sent:true}` (no user enumeration).\n- `POST auth/reset-password` \u2014 `{uid, token, password}` \u2192 `200 {reset:true}`. Also marks the mailbox verified.\n\n`user` shape: `{id, email, display_name, role, verified, provider, created_at}`.\n\n**Auth mail links:** verification/reset mails link to the deployed app as\n`{app_url}/?ta_action=verify&uid=\u2026&token=\u2026` and `{app_url}/?ta_action=reset&uid=\u2026&token=\u2026`.\n**Every generated app with auth MUST handle these two query params on load**\n(see Client Patterns).\n\n**Login methods governance:** offer ONLY the login methods the project's\n`config.auth.methods` allows (check with `agentful-auth-config get`;\ndefault `[\"email\"]`). Do NOT generate \"Sign in with Google\"/SSO buttons unless\n`google`/`oidc` is listed \u2014 the platform refuses unlisted methods server-side.\n\n**Google login (when `google` IS listed):** a \"Continue with Google\" button\ncalls `googleAuth.start()` (see Client Patterns) \u2192 central broker\n`api.agentful.dev/auth/oauth/google/start` \u2192 Google \u2192 back to the app with the\nJWT in the URL fragment; call `handleGoogleReturn()` at startup to complete\nthe login. Google users arrive `verified: true` (Google verified the mailbox),\nexisting email accounts with the same address are linked automatically, and\nthe `admin_email` bootstrap applies. Show `auth_error` codes as a friendly\nmessage (`auth_method_not_allowed` \u2192 \"Google login is not available for this\napp\"); never retry in a loop.\n\n**Data:**\n- `GET data/{collection}` \u2014 list (paginated; `?limit=`, `?cursor=`)\n- `GET data/{collection}/{docId}` \u2014 single doc\n- `POST data/{collection}` \u2014 body `{data: {...}}` \u2192 `{ok:true, data:{doc_id, collection, data, created_at}}`\n- `PUT data/{collection}/{docId}` \u2014 body `{data: {...}}` \u2192 updated doc\n- `DELETE data/{collection}/{docId}` \u2192 `{ok:true, data:{deleted, collection}}`\n\nEnd-user routes (above) require `Authorization: Bearer <token>` from `auth/register` or `auth/login`. The collection's `access_rule` enforces what each token may read/write.\n\n## Response Shapes\n\n**Success:** `{ \"ok\": true, \"data\": {...} }` \u2014 `data` for lists has `{documents:[...], count, cursor}`.\n\n**Error:** `{ \"ok\": false, \"error\": { \"code\": \"...\", \"message\": \"...\", \"correlation_id\"?: \"...\" } }`\n\nStatus codes are HTTP-conventional (201 on create, 200 on read/update/delete, 4xx for client errors, 5xx for platform).\n\n## Error Code \u2192 Remediation\n\n| `error.code` | HTTP | What it means | What to do |\n|---|---|---|---|\n| `not_found` | 404 | Collection doesn't exist, OR doc id doesn't exist | If collection: run `agentful-managed-collections upsert` then retry. If doc: surface to user. |\n| `email_unverified` | 403 | Login blocked until the user confirms their email | Show \"confirm your email\" state + resend button (`auth/resend-verification`). |\n| `invalid_token` | 400 | Verification/reset link invalid, expired, or already used | Offer resend (`resend-verification`) or a new reset request. |\n| `too_many_attempts` | 429 | Auth rate limit hit (failed logins / mail requests) | Tell the user to wait a few minutes; do not auto-retry. |\n| `email_infra_unconfigured` | 409 | Project has no email infrastructure selected | Tell the BUILDER (not the end-user): choose \"Agentful Email\" or BYO in project settings \u2192 Email infrastructure. |\n| `email_send_failed` | 502 | Mail transport failed transiently | Tell the user to try again later. |\n| `schema_validation_failed` | 400 | Payload doesn't match the collection's schema | Re-read the schema in the preamble; fix field names/types/required-ness; do not retry blindly. |\n| `readonly_collection` | 403 | Collection or doc is system-protected (e.g. `_users` via end-user route) | Use the correct route (e.g. `auth/register` for `_users`); do not retry. |\n| `forbidden` | 403 | Access rule denied this end-user | Tell the user they need to log in / lack permission. |\n| `already_exists` | 409 | `doc_id` collision or conditional check failed | Let `doc_id` auto-generate (omit it). |\n| `too_large` | 413 | Document > 256 KB | Split or trim payload. |\n| `quota_exceeded` | 429 | DDB throttling / request-limit spillover (transient) | The doctor returns `action: retry_with_backoff`. Sleep + retry up to 3 times per `details.backoff_ms`. **Surface `correlation_id` to the user ONLY after all attempts exhaust.** |\n| `transient_storage_error` | 503 | DDB internal / service-unavailable (transient) | Same as `quota_exceeded`: doctor returns `retry_with_backoff`; engine handles silently until budget exhausts. |\n| `internal_storage_error` / `write_failed` / `delete_failed` | 500 | Platform-side error, NOT classified retryable | Delegate to `@agentful-managed-db-doctor` with `correlation_id`. Surface its `user_message` verbatim. Do NOT retry in a loop. Do NOT invent a root cause. |\n\n## Client Patterns\n\nA tiny client used everywhere. Define once per project; reuse for all collections.\n\n### Vanilla / shared base\n\n```js\n// src/lib/data.js\nconst BASE = `/api/p/${PROJECT_ID}`; // set PROJECT_ID at build time\nconst tokenKey = 'mm_auth_token';\n\nfunction authHeader() {\n const t = localStorage.getItem(tokenKey);\n return t ? { Authorization: `Bearer ${t}` } : {};\n}\n\nasync function jsonOrThrow(res) {\n const body = await res.json().catch(() => ({}));\n if (!res.ok || !body.ok) {\n const err = new Error(body.error?.message || `HTTP ${res.status}`);\n err.code = body.error?.code;\n err.correlation_id = body.error?.correlation_id;\n err.status = res.status;\n throw err;\n }\n return body.data;\n}\n\nexport const auth = {\n async register(email, password, display_name) {\n const data = await jsonOrThrow(await fetch(`${BASE}/auth/register`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password, display_name }),\n }));\n // verification_required \u2192 NO token yet; caller must show \"check your inbox\".\n if (data.token) localStorage.setItem(tokenKey, data.token);\n return data; // {verification_required, user, token?}\n },\n async login(email, password) {\n const data = await jsonOrThrow(await fetch(`${BASE}/auth/login`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password }),\n }));\n localStorage.setItem(tokenKey, data.token);\n return data.user;\n },\n async verify(uid, token) {\n const data = await jsonOrThrow(await fetch(`${BASE}/auth/verify`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ uid, token }),\n }));\n localStorage.setItem(tokenKey, data.token); // auto-login after verify\n return data.user;\n },\n async resendVerification(email) {\n return jsonOrThrow(await fetch(`${BASE}/auth/resend-verification`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n }));\n },\n async requestPasswordReset(email) {\n return jsonOrThrow(await fetch(`${BASE}/auth/request-password-reset`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n }));\n },\n async resetPassword(uid, token, password) {\n return jsonOrThrow(await fetch(`${BASE}/auth/reset-password`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ uid, token, password }),\n }));\n },\n logout() { localStorage.removeItem(tokenKey); },\n token() { return localStorage.getItem(tokenKey); },\n};\n\n// Google login (ONLY when 'google' \u2208 config.auth.methods \u2014 never generate\n// this button otherwise; the platform refuses unlisted methods server-side).\n// Redirects to the central Agentful OAuth broker; after Google consent the\n// broker 302s back to `redirect` with the app JWT in the URL FRAGMENT:\n// https://<your-app>/#token=<jwt>&provider=google (or #auth_error=<code>)\nexport const googleAuth = {\n start(redirect = location.origin + '/') {\n const url = new URL('https://api.agentful.dev/auth/oauth/google/start');\n url.searchParams.set('project_id', PROJECT_ID);\n url.searchParams.set('redirect', redirect); // must be THIS app's https origin\n location.href = url.toString();\n },\n};\n\n// REQUIRED whenever the Google button is generated: pick up the broker return\n// on app load (fragment token \u2192 login; auth_error \u2192 user-visible message).\nexport function handleGoogleReturn() {\n const h = new URLSearchParams(location.hash.slice(1));\n const token = h.get('token'), err = h.get('auth_error');\n if (!token && !err) return null;\n history.replaceState(null, '', location.pathname + location.search); // strip token from URL\n if (err) return { ok: false, error: err }; // e.g. auth_method_not_allowed, oauth_failed\n localStorage.setItem(tokenKey, token);\n return { ok: true, provider: h.get('provider') || 'google' };\n}\n\n// REQUIRED in every app with auth: handle the mail links on app load.\n// Call once at startup (before router init is fine).\nexport async function handleAuthMailAction() {\n const p = new URLSearchParams(location.search);\n const action = p.get('ta_action'), uid = p.get('uid'), token = p.get('token');\n if (!action || !uid || !token) return null;\n history.replaceState(null, '', location.pathname); // strip token from URL\n if (action === 'verify') {\n try { const user = await auth.verify(uid, token); return { action, ok: true, user }; }\n catch (e) { return { action, ok: false, error: e.code || 'invalid_token' }; }\n }\n if (action === 'reset') return { action, ok: true, uid, token }; // show new-password form, then auth.resetPassword(uid, token, pw)\n return null;\n}\n\nexport const data = {\n async list(collection, opts = {}) {\n const qs = new URLSearchParams(opts).toString();\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}${qs ? '?' + qs : ''}`, {\n headers: { ...authHeader() },\n }));\n },\n async get(collection, docId) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}/${docId}`, {\n headers: { ...authHeader() },\n }));\n },\n async create(collection, data) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...authHeader() },\n body: JSON.stringify({ data }),\n }));\n },\n async update(collection, docId, data) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}/${docId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json', ...authHeader() },\n body: JSON.stringify({ data }),\n }));\n },\n async remove(collection, docId) {\n return jsonOrThrow(await fetch(`${BASE}/data/${collection}/${docId}`, {\n method: 'DELETE',\n headers: { ...authHeader() },\n }));\n },\n};\n```\n\n### React / Vue / Svelte\n\nUse the same `data.js` / `data.ts` module above; wrap in framework-native state primitives.\n\n- **React:** call from `useEffect` for reads, `useState` for results; surface `err.code`/`err.correlation_id` to the user when caught. Do not put data calls in render bodies.\n- **Vue:** use `onMounted` for reads and a `ref()` for results; same error surfacing.\n- **Svelte / SvelteKit:** call from `onMount` (or a `load` function in SvelteKit); SvelteKit static-adapter projects must NOT use server `load` (no Node runtime in static deploy).\n- **Astro:** call only from client-side islands; no server fetch (static-only build).\n\n### TypeScript types\n\nGenerate the per-collection type from the preamble's field list:\n\n```ts\n// Example for a collection with fields: title:string*, done:boolean\ntype Todo = { title: string; done?: boolean };\n\n// And response wrappers:\ntype DataDoc<T> = { doc_id: string; collection: string; data: T; created_at: string };\ntype DataList<T> = { documents: DataDoc<T>[]; count: number; cursor?: string };\n```\n\n## Anti-patterns\n\n- \u274C `try { await data.create(...) } catch { /* ignore */ }` \u2014 masks failures.\n- \u274C Hardcoding `doc_id` for \"convenience\" \u2014 causes `already_exists` 409 on retry.\n- \u274C Writing to a collection name that doesn't appear in the preamble \u2014 `not_found` 404.\n- \u274C Using the schema endpoint `/data/_collections` from client code \u2014 owner-only, end-users get 403.\n- \u274C Storing the JWT anywhere other than `localStorage` under a project-scoped key; do not put it in cookies (CORS) or in `sessionStorage` (lost on tab close).\n- \u274C Telling the user \"the database is down\" because of a 5xx. Surface the `correlation_id` and stop.\n- \u274C Surfacing `correlation_id` on transient errors (`quota_exceeded`, `transient_storage_error`) before the doctor's `retry_with_backoff` budget is exhausted. The whole point is the user sees nothing while the retry loop is in play; only escalate after all `max_attempts` fail.\n\n## Diagnostic delegation\n\nIf you hit a 5xx that doesn't map to a retry-able 4xx in the table above, do not diagnose yourself. Delegate to `@agentful-managed-db-doctor` (added in PR 1.3) with the `correlation_id` from the response. The doctor has constrained tools and cannot fabricate platform internals.\n\n---\n\n## Managed Actions (only when `server.mode == managed`)\n\nManaged Actions are small Node.js functions the platform runs for the project at `/api/p/{PROJECT_ID}/actions/{name}`. Use them when a frontend operation needs (a) a secret API key, (b) a non-public/secured external API, or (c) server-enforced trust (price computation, signature verification, admin actions). For pure CRUD against the managed DB, use the data API directly; do NOT route everything through an action.\n\n### Hard rules (Managed Actions)\n\n1. **Upsert FIRST, fetch SECOND.** If your generated code calls `fetch('/api/p/.../actions/{name}')`, you MUST upsert the action via the CLI BEFORE writing the fetch call. An undeployed action returns `404 action_not_found`; the preamble's `Managed actions` list is the ground truth for what exists.\n2. **Only `ctx.fetch`, `ctx.data`, `ctx.secrets`, `ctx.user`, `ctx.body` and approved npm packages.** No `require('fs')`, `require('child_process')`, `require('http')`, `require('https')`, `require('net')`, `require('os')`, `require('path')`, `require('process')`, `require('vm')`, `require('cluster')`, `require('worker_threads')`. The validator rejects these at upload time with `{code: 'action_validation_failed', reason: 'disallowed_require'}`.\n3. **Secrets are read with `await ctx.secrets.get('<name>')` \u2014 never property access.** `ctx.secrets` has exactly one method, `get(key)`. `ctx.secrets.SOME_KEY` is silently `undefined`. Secret names must match `^(database|server)\\.[a-z][a-z0-9_]{0,126}$` \u2014 use `server.stripe_secret_key`, not `STRIPE_SECRET_KEY` (uppercase, unprefixed names cannot even be stored in Backend \u2192 Secrets).\n4. **Actions are publicly invokable \u2014 authorize the caller yourself.** `ctx.user` is the JWT-verified end-user (`{ id, email, pid }`) or `null`. Any action that touches a secret, writes data, or returns non-public information must start with a `ctx.user` check; nothing else gates who can call it.\n5. **Outbound calls from inside an action must use `ctx.fetch`**, not a bare `fetch`. `ctx.fetch` injects `X-Action-Depth` on self-action URLs so the platform's loop detector can break runaway recursion. External URLs are passed through unchanged.\n6. **Cost shape.** 5 s timeout, 256 MB RAM, 1 MB request body, per-project concurrent invocations capped at 10. Plan for `429 concurrency_exceeded` under load and surface it to the user gracefully (e.g. retry with backoff or \"try again in a moment\").\n\n### Action shape\n\n```js\n// .server/actions/checkout.js\nmodule.exports = async function (ctx) {\n // ctx.body \u2014 parsed JSON request body\n // ctx.user \u2014 JWT-verified end-user { id, email, pid }, or null if not logged in\n // ctx.data \u2014 same CRUD surface as the public data API, scoped to this project\n // ctx.secrets \u2014 async accessor for Backend \u2192 Secrets: await ctx.secrets.get('server.stripe_secret_key')\n // ctx.fetch \u2014 depth-aware fetch wrapper\n if (!ctx.user) return { error: 'auth_required' };\n const apiKey = await ctx.secrets.get('server.stripe_secret_key');\n if (!apiKey) return { error: 'missing_server_secret' };\n const stripeRes = await ctx.fetch('https://api.stripe.com/v1/checkout/sessions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ /* \u2026 */ }).toString(),\n });\n const session = await stripeRes.json();\n return { url: session.url };\n};\n```\n\n### Authoring protocol (engine flow)\n\n1. Read the preamble's `Managed actions` block. If your target name is already deployed with the right shape, skip to step 3.\n2. **Upsert:** write the action source to a local temp file, then `agentful-managed-actions upsert <project_id> <name> <file_path>`. The validator runs on both the public PUT-files path and this CLI; same rejection rules.\n3. Write the frontend `fetch('/api/p/<project_id>/actions/<name>', { method: 'POST', body: JSON.stringify(payload) })`. Include `Content-Type: application/json` on POSTs.\n4. Test once with `agentful-managed-actions invoke <project_id> <name> --body '{\"\u2026\":\"\u2026\"}'` to confirm the deployment landed.\n\n### Action-invocation error codes (response body)\n\n| `error.code` | HTTP | What it means | What to do |\n|---|---|---|---|\n| `action_not_found` | 404 | The action with that name doesn't exist | Upsert it first. |\n| `action_validation_failed` | 400 | Validator rejected the source (size, filename, disallowed require) | Fix per `reason` field; do not retry. |\n| `concurrency_exceeded` | 429 | Per-project cap reached | Backoff + retry, or surface to user. |\n| `action_loop_detected` | 508 | `X-Action-Depth >= 5` \u2014 too many self-calls in a chain | Refactor; you cannot self-recurse beyond depth 5. |\n| `timeout` | 408 | Action exceeded 5 s | Move heavy work out of the action or break into smaller calls. |\n| `body_too_large` | 413 | Request body > 1 MB | Trim the payload. |\n| `action_too_large` | 413 | Action source file > 256 KB | Split into multiple actions. |\n| `runtime_error` | 500 | Action threw at runtime | Read the message; common causes are unhandled rejections, missing `await`, or accessing undefined ctx fields. |\n\n### Anti-patterns\n\n- \u274C Putting a Stripe / OpenAI / Resend API key in frontend code. It must live in `ctx.secrets`.\n- \u274C `ctx.secrets.STRIPE_SECRET_KEY` (property access). The secrets API is `await ctx.secrets.get('server.stripe_secret_key')`; property access is silently `undefined`, and uppercase/unprefixed names cannot be stored at all.\n- \u274C `ctx.user.sub`. The verified user object is `{ id, email, pid }` \u2014 the JWT `sub` claim arrives as `ctx.user.id`.\n- \u274C An action that reads secrets or writes data without checking `ctx.user` first. Actions are publicly invokable; your check is the only authorization.\n- \u274C Calling `fetch('/api/p/.../actions/foo')` without first running `agentful-managed-actions upsert`. Will return 404.\n- \u274C Recursive actions calling themselves to \"spread work\". Will trip the depth guard at 5.\n- \u274C Using bare `fetch` instead of `ctx.fetch` from inside an action. The depth header won't propagate; you bypass the loop guard.\n- \u274C Naming actions `Hello.js`, `_internal.js`, or `actions/sub/foo.js`. The validator rejects (uppercase, leading underscore, subdirectory).\n- \u274C Hardcoding the API base URL into the action's `ctx.fetch` calls to other actions. Use a relative path or the project's own API origin.\n\n### `ctx.data` Is Privileged \u2014 It Bypasses `access_rule`\n\n`ctx.data` inside an action talks to the database **directly, with no\n`access_rule` enforcement**. It is a project-scoped, owner-level surface \u2014 the\nopposite of the `/data/*` end-user route:\n\n- It reads and writes **every** document in **every** collection, regardless of\n whether that collection is `owner`, `authenticated`, or `public`.\n- It does **not** check `created_by`. An action can read one user's `owner`\n docs and write into another user's.\n- Documents created via `ctx.data.create` are attributed `created_by: \"action\"`,\n never to an end-user. If you need owner attribution, store the owner's id in\n the document `data` yourself (e.g. `{ user_id: ctx.user.id, ... }`) and\n filter on it.\n- `ctx.data.list(collection, { limit })` returns a **plain array** of docs\n (`[{ doc_id, data, created_by, created_at }]`, NOT `{ documents: [...] }`),\n caps at 100, and does **no server-side filtering** \u2014 you filter in JS. For\n data sets that can exceed 100 rows, store an explicit owner/lookup field and\n design around the cap; do not assume `list` returns everything.\n\nThis is the intended mechanism for trusted/admin work. The trade-off: an action\nis only as safe as its own checks. **Always verify `ctx.user` before any\ncross-user read or write.**\n\n### RBAC & Secure Role Assignment (`owner` + Action)\n\nThe managed DB has **no role concept and no field-level validation**. On the\nend-user `/data/*` route the client controls the entire document body \u2014\nincluding any `role` field. Design around two facts:\n\n1. **Privilege escalation is possible by default.** If a `profiles` collection\n is `authenticated` or `owner`, a client can register and POST\n `{ role: \"admin\" }` for themselves. `owner` does NOT stop this \u2014 the user\n owns their own profile.\n2. **`owner` blocks admins too.** An `owner` collection correctly hides a\n client's data from other clients, but an admin also cannot read it over\n `/data/*`. Admin access must go through an action using `ctx.data`.\n\nSecure pattern \u2014 keep `role` server-owned and gate every change behind an\naction that verifies the **caller** is already an admin:\n\n```js\n// .server/actions/set-role.js \u2014 upsert BEFORE calling it from the client\nmodule.exports = async function (ctx) {\n if (!ctx.user) return { error: 'auth_required' };\n // 1. Verify the CALLER is an admin (ctx.data ignores access_rule, so this\n // works even though `profiles` is `owner`).\n const all = await ctx.data.list('profiles', { limit: 100 });\n const me = all.find(d => d.data.user_id === ctx.user.id);\n if (!me || me.data.role !== 'admin') return { error: 'forbidden' };\n // 2. Validate input, then apply to the target.\n const { target_user_id, role } = ctx.body || {};\n if (!['admin', 'member', 'client'].includes(role)) return { error: 'bad_role' };\n const target = all.find(d => d.data.user_id === target_user_id);\n if (!target) return { error: 'not_found' };\n await ctx.data.update('profiles', target.doc_id, { ...target.data, role });\n return { ok: true };\n};\n```\n\nRules for this pattern:\n\n- The client UI must **never** write the `role` field over `/data/*`. On\n self-registration, create the profile without `role` (or force a non-privileged\n default in the action) \u2014 never trust a client-sent role.\n- \"Owner OR admin\" **reads** (an admin viewing any client's invoices) use the\n same shape: keep the collection `owner`, expose admin access through an action\n that verifies `ctx.user` is an admin, then uses `ctx.data` to fetch across users.\n- **Bootstrapping the first admin:** see **First Admin \u2014 mode-correct\n protocol** below. Never invent a client-reachable route for it.\n- The 100-row `ctx.data.list` cap applies: if `profiles` can exceed 100 rows,\n this scan-in-JS lookup is unreliable. Until server-side filtering exists,\n store role lookups in a bounded collection or key admins by a known id set.\n\n## First Admin \u2014 mode-correct protocol\n\nWhen the app needs an admin (dashboard, moderation, `admin`-ruled collections),\nask the builder **\"How should the first admin account be created?\"** and offer\nONLY these options \u2014 they map to the platform's `_users.role` system\n(`user`/`admin`), which is what the `admin` access rule checks:\n\n1. **Fixed admin email (recommended).** Ask the builder for the address, then\n run:\n ```\n agentful-auth-config set $PROJECT_ID '{\"admin_email\":\"chef@firma.de\"}'\n ```\n Whoever registers (or later logs in) with exactly that address is promoted\n to `role: admin` **server-side, only after email verification** \u2014 no code\n needed in the app.\n2. **Manual via Data Manager.** The builder opens **Backend \u2192 Data Manager \u2192\n `_users` tab**, selects the registered user and sets the `role` dropdown to\n `admin` (the `verified` flag can also be set there if a mail never arrived).\n\n### `agentful-auth-config` CLI\n\n- `agentful-auth-config get $PROJECT_ID` \u2014 current `config.auth` state\n (`auth: null` = hardened pipeline not activated yet \u2192 registering works\n legacy-style without verification) plus `email_infrastructure`\n (`\"\"` = builder has not chosen one; verification mails will fail with\n `email_infra_unconfigured` until they pick one in project settings).\n- `agentful-auth-config set $PROJECT_ID '<json>'` \u2014 merge into `config.auth`.\n Keys: `methods` (subset of `email|google|oidc`; the server clamps against\n the org allowlist \u2014 verify the result in the response), `require_verified_login`\n (bool; default true once auth is configured), `admin_email`, `language`\n (`de`|`en`, auth-mail language).\n- Setting ANY key activates the hardened pipeline (verification mails +\n verified-login gate). Before activating it, run `get` and make sure\n `email_infrastructure` is not empty \u2014 otherwise tell the builder to choose\n Agentful Email or BYO in project settings first.\n- Email infrastructure is NOT settable via this CLI by design (audited\n builder decision, DE-data-region notice).\n\n**NEVER offer \"run SQL\" / \"insert into the database manually\" for\n`database.mode == managed` \u2014 there is no SQL surface; the managed DB is not a\nSQL database.** SQL-based instructions apply only to BYO-Supabase projects\n(different skill, different mode).\n\nPrefer the platform `_users.role` + `admin` access rule over inventing an\napp-level `profiles.role` system when the requirement is just \"one admin can\nsee/manage everything\" \u2014 the profiles-RBAC pattern above is for MULTI-role\napps (admin/member/client) that need roles beyond `user`/`admin`.\n",
6854
7000
  "nextjs-scaffold": '---\nname: nextjs-scaffold\ndescription: Next.js 15 static export scaffold with React 19, TypeScript, and Tailwind CSS v4 generated manually without create-next-app. Use only for explicit Next.js requests or justified static export app needs.\n---\n\n# Next.js Scaffold\n\n## Stack Briefing\n\nNext.js 15 **static export** (`output: \'export\'`) + React 19 + TypeScript +\nTailwind v4, written manually (never `create-next-app`). Static export only \u2014\nno server actions, API routes, dynamic server rendering, or image optimization\ndependency. Build produces `out/` (not `dist/`). Use only for explicit Next or\njustified static multi-page React needs.\n\n## When To Use\n\nUse this skill when `selected_stack` is Next.js. Prefer Next.js only when the user explicitly asks for Next.js, asks for Next-specific features, or needs a React app architecture with static export and file-based routing.\n\nDo not use Next.js for a simple landing page or portfolio unless requested.\n\n## When Not To Use\n\n- Simple landing pages/portfolios \u2192 `vanilla-scaffold`.\n- General React app UI without Next-specific needs \u2192 `react-scaffold`.\n- Anything needing server actions, API routes, or SSR \u2014 unsupported here.\n\n## HARD STOP: Never Re-Scaffold An Existing App\n\nBefore writing ANY scaffold file, check the workspace. If `package.json` (or\nan existing `index.html` app shell for vanilla projects) and source files\nalready exist, this project already has an app \u2014 scaffolding is DONE and this\nskill must not overwrite it. Read the existing entry points and source tree\nfirst, then build ON TOP of the existing files: keep the entry points,\nrouting, and dependency choices already in place. Overwriting the scaffold\nfiles on an existing project destroys the user\'s app (this happened in\nproduction). If the existing code seems inconsistent with the request, ask\nthe user \u2014 never replace silently.\n\n## Required File Shape\n\nThis is the shape a Next.js project has here. Depending on how the project\nstarted, these files may already exist in the workspace \u2014 check first:\n\n```text\npackage.json build = `next build`; `npm run verify` runs the full gate\nnext.config.ts output: \'export\', trailingSlash, images.unoptimized\ntsconfig.json paths "@/*" -> ./src/*\neslint.config.mjs the only ESLint config in the project\npostcss.config.mjs\nnext-env.d.ts\npublic/\n favicon.svg keep it \u2014 without a favicon every page logs a 404\nsrc/\n app/\n layout.tsx owns <html>/<body> and the metadata\n page.tsx the root route: this IS the landing page\n globals.css THE global stylesheet \u2014 Tailwind by default\n.gitignore\n```\n\n**Empty workspace** \u2014 create exactly this shape.\n\n**Files already present** \u2014 **edit them, do not recreate them.** A project\nfrom `create-next-app` is close to this already; the usual gaps are the\n`Create Next App` metadata in `layout.tsx`, the demo SVGs in `public/`, and\nan `app/` directory at the root instead of under `src/`.\n\nThe build output is `out/`, not `dist/` \u2014 that is expected and the platform\naccepts it. Do not rename it.\n\nDo not use `next/font/google` by default because it can add build-time network dependency. Use system fonts unless the user explicitly requests custom fonts.\n\n## package.json\n\n```json\n{\n "name": "project-name",\n "private": true,\n "version": "0.1.0",\n "scripts": {\n "dev": "next dev",\n "build": "next build",\n "start": "next start",\n "verify": "tsc --noEmit && eslint . --max-warnings 0 && next build"\n },\n "dependencies": {\n "next": "16.2.9",\n "react": "19.2.4",\n "react-dom": "19.2.4"\n },\n "devDependencies": {\n "@tailwindcss/postcss": "^4",\n "@types/node": "^20",\n "@types/react": "^19",\n "@types/react-dom": "^19",\n "eslint": "^9",\n "eslint-config-next": "16.2.9",\n "tailwindcss": "^4",\n "typescript": "^5"\n }\n}\n```\n\n## next.config.ts\n\n```ts\nimport type { NextConfig } from \'next\'\n\nconst nextConfig: NextConfig = {\n // Static export \u2014 the platform serves files, there is no Next.js server.\n output: \'export\',\n // Emits `about/index.html` instead of `about.html`, which a plain static\n // host can resolve without rewrite rules.\n trailingSlash: true,\n // next/image needs a server to optimise; without this the export fails.\n images: {\n unoptimized: true,\n },\n}\n\nexport default nextConfig\n```\n\n## postcss.config.mjs\n\n```js\nconst config = {\n plugins: {\n \'@tailwindcss/postcss\': {},\n },\n}\n\nexport default config\n```\n\n## App Files\n\n`src/app/layout.tsx`:\n\n```tsx\nimport type { Metadata } from \'next\'\nimport \'./globals.css\'\n\nexport const metadata: Metadata = {\n title: \'Replace this title\',\n description: \'Replace this with a one-sentence description of the site.\',\n icons: { icon: \'/favicon.svg\' },\n}\n\nexport default function RootLayout({\n children,\n}: Readonly<{\n children: React.ReactNode\n}>) {\n return (\n <html lang="en" className="h-full antialiased">\n <body className="min-h-full flex flex-col">{children}</body>\n </html>\n )\n}\n```\n\n`src/app/globals.css`:\n\n```css\n@import "tailwindcss";\n\n/* Design tokens. Tailwind v4 turns every entry here into a utility\n (--color-brand -> bg-brand/text-brand), so restyle the project by editing\n these values rather than sprinkling hex codes through the components. */\n@theme {\n --color-brand: #0070f3;\n --color-brand-contrast: #ffffff;\n --color-surface: #ffffff;\n --color-surface-muted: #f5f5f7;\n --color-ink: #111827;\n --color-ink-muted: #6b7280;\n --radius-card: 0.75rem;\n}\n\n:root {\n color-scheme: light;\n font-family: Inter, ui-sans-serif, system-ui, sans-serif;\n --app-bg: #ffffff;\n --app-fg: #111827;\n}\n\n/* An opaque background on html, body is mandatory \u2014 the page is never\n transparent. Keep this rule when you restyle. */\nhtml, body {\n margin: 0;\n min-height: 100%;\n min-width: 320px;\n background: var(--app-bg);\n color: var(--app-fg);\n}\n\n/* Keyboard focus baseline. Components may override it, but never remove it:\n the platform appends a generic fallback to any project whose CSS contains\n no `:focus` rule at all, and a real one belongs here. */\n:focus-visible {\n outline: 2px solid var(--color-brand, currentColor);\n outline-offset: 2px;\n}\n```\n\n## TypeScript Config\n\n`tsconfig.json`:\n\n```json\n{\n "compilerOptions": {\n "target": "ES2017",\n "lib": ["dom", "dom.iterable", "esnext"],\n "allowJs": true,\n "skipLibCheck": true,\n "strict": true,\n "noEmit": true,\n "esModuleInterop": true,\n "module": "esnext",\n "moduleResolution": "bundler",\n "resolveJsonModule": true,\n "isolatedModules": true,\n "jsx": "react-jsx",\n "incremental": true,\n "plugins": [{ "name": "next" }],\n "paths": { "@/*": ["./src/*"] }\n },\n "include": [\n "next-env.d.ts",\n "**/*.ts",\n "**/*.tsx",\n "**/*.mts",\n ".next/types/**/*.ts",\n ".next/dev/types/**/*.ts"\n ],\n "exclude": ["node_modules"]\n}\n```\n\n`next-env.d.ts`:\n\n```ts\n/// <reference types="next" />\n/// <reference types="next/image-types/global" />\n```\n\n## Routing Rules\n\nUse file-based routing under `src/app/` with static export. Do not add\n`middleware`, dynamic server routes, or `generateStaticParams` that depend on a\nserver. All routes must be statically renderable.\n\n## Data And Backend Rules\n\n- No API routes or server actions (static export forbids them). For data/auth,\n use the platform backend via client `fetch()` \u2014 respect the STOP gate.\n- `images.unoptimized: true` is required; do not add the image optimization\n server dependency.\n\n## Asset Path Rules\n\n- Keep output host-agnostic; reference the project\'s own assets/routes\n relatively. Do not set an absolute `assetPrefix`/`basePath`. No `<base>` tag.\n\n## Common Failure Modes\n\n- Adding server actions/API routes \u2192 static export build fails.\n- Using `next/font/google` \u2192 build-time network dependency.\n- Renaming `out/` to `dist/` or adding postbuild move scripts.\n- Optimized `<Image>` without `unoptimized: true`.\n\n## ESLint Config\n\nEvery scaffold ships `eslint.config.mjs` (flat config) so the platform lint\ngate and the live ESLint diagnostics work from the very first turn. Next uses\n`eslint-config-next` rather than the hand-rolled rule set of `react-scaffold`\n\u2014 measured 2026-08-04, it covers strictly more:\n\n| canary | `eslint-config-next` |\n| --- | --- |\n| `useEffect(() => setV(item), [item])` | error \u2014 *"Calling setState synchronously within an effect"* (the react-scaffold class) |\n| `<img src="/x.png">` | error \u2014 `@next/next/no-img-element` (which the hand-rolled config never sees) |\n\n`eslint.config.mjs`:\n\n```js\nimport { defineConfig, globalIgnores } from "eslint/config";\nimport nextVitals from "eslint-config-next/core-web-vitals";\nimport nextTs from "eslint-config-next/typescript";\n\nconst eslintConfig = defineConfig([\n ...nextVitals,\n ...nextTs,\n // Override default ignores of eslint-config-next.\n globalIgnores([\n // Default ignores of eslint-config-next:\n ".next/**",\n "out/**",\n "build/**",\n "next-env.d.ts",\n ]),\n]);\n\nexport default eslintConfig;\n```\n\nThe platform runs `npx eslint . --max-warnings 0` before every build, so any\nviolation blocks the build. Do not add or remove rules, and never "fix" a\nviolation with `eslint-disable` or config edits \u2014 fix the code.\n\n## Verification\n\nRun install, then the full platform verification contract (see the build\nagent\'s "Build And Preview Rules"): typecheck, `npx eslint . --max-warnings 0`\n(the scaffold ships `eslint.config.mjs`, so this check ALWAYS applies and\ndecides acceptance), `npm run\nbuild`, and finally verify that `out/index.html` exists. Do not rename `out/`\nto `dist/`. `npm run build` alone is not what the platform gate checks \u2014 and\nNext\'s own build only surfaces lint when configured to. Never make the lint\nstep pass by disabling rules.\n',
6855
7001
  "react-scaffold": '---\nname: react-scaffold\ndescription: React 19 with Vite, TypeScript, and Tailwind CSS v4 scaffold generated manually without npm create. Use for app UIs, dashboards, auth flows, CRUD interfaces, or explicit React requests.\n---\n\n# React Scaffold\n\n## Stack Briefing\n\nReact 19 + Vite + TypeScript, written manually (never `npm create`), with\nTailwind v4 as the default styling layer. Use it for app-like UIs where\ncomponent state and interaction justify a framework. Output must stay\nstatic-hostable: `base: \'/\'`, history routing (clean URLs, no `#`), build to\n`dist/`. Do not over-split into dozens of trivial components \u2014 keep the tree\npragmatic and typed.\n\n## When To Use\n\nUse this skill when `selected_stack` is React. React is appropriate for app-like interfaces, dashboard/admin UIs, authenticated user flows, complex client state, CRUD screens, and explicit React requests.\n\nDo not use React just because the workspace is empty. Static marketing/content sites should usually use `vanilla-scaffold`.\n\n## When Not To Use\n\n- Static marketing/content/portfolio sites \u2192 `vanilla-scaffold`.\n- Content-heavy multi-page sites better served by Astro \u2192 `astro-scaffold`.\n- Anything requiring SSR/server rendering \u2014 output here is static export only.\n\n## HARD STOP: Never Re-Scaffold An Existing App\n\nBefore writing ANY scaffold file, check the workspace. If `package.json` and\n`src/` already exist, this project already has an app \u2014 scaffolding is DONE\nand this skill must not overwrite it. Read the existing `package.json`,\n`src/App.tsx` and the `src/` tree first, then build ON TOP of the existing\nfiles: keep the entry points, routing, and dependency choices already in\nplace. Overwriting `package.json`/`App.tsx`/`main.tsx` on an existing project\ndestroys the user\'s app (this happened in production). If the existing code\nseems inconsistent with the request, ask the user \u2014 never replace silently.\n\n**Rewriting a file must never drop an `import "./x.css"` it carried.** Nothing\ncatches it: tsc/eslint do not read CSS, an unimported stylesheet is legal so\nthe bundler is silent, and the page renders unstyled (prod 2026-08-01: 38 of\n85 class names left the bundle, all gates green). Prefer `edit` over a full\n`write`; if you rewrite, carry the original import block over.\n\n## Required File Shape\n\nThis is the shape a React project has here. Depending on how the project\nstarted, these files may already exist in the workspace \u2014 check first:\n\n```text\nindex.html entry: favicon link, #root, module script\npackage.json build = `vite build`; `npm run verify` runs the full gate\nvite.config.ts base: \'/\', tailwindcss() + react()\ntsconfig.json ONE flat config, include: ["src"]\neslint.config.mjs the only ESLint config in the project\npublic/\n favicon.svg keep it \u2014 without a favicon every page logs a 404\nsrc/\n App.tsx placeholder shell: header/nav, hero, cards, footer\n main.tsx entry, imports ./index.css\n index.css THE stylesheet \u2014 Tailwind by default, see Styling\n vite-env.d.ts\n.gitignore\n```\n\n**Empty workspace** \u2014 create exactly this shape.\n\n**Files already present** \u2014 **edit them, do not recreate them.** Rewrite the\ncopy, restyle the `@theme` tokens, add components and routes, but keep the\nshape. Each part of it prevents a defect that has shipped to real users.\n\n**A project that came from an older `create-vite` starter** carries config\nthat silently disables checks the platform believes it ran. Repair config\nonly \u2014 never a full-file `write` of `App.tsx`, `main.tsx` or `package.json`,\nand never as a pretext to re-scaffold:\n\n| found | do |\n| --- | --- |\n| `tsconfig.json` with `"files": []` + `references` | always replace with the one flat config below and delete `tsconfig.app.json`/`tsconfig.node.json` \u2014 otherwise nothing is type-checked at all |\n| `eslint.config.js` | leave it alone if it is the only config. If you need the rule set below, move its contents into `eslint.config.mjs` and **delete the `.js`** \u2014 never let both exist |\n| `src/App.css` | leave a working import alone. If you rewrite `App.tsx`, carry `import \'./App.css\'` over, or fold the rules into `index.css` in the same edit \u2014 never drop it silently |\n\nSay in your summary which of these you changed and why.\n\n### One Stylesheet, Not Two\n\n`src/index.css` is the only stylesheet. Do **not** add `src/App.css`.\n\nA second stylesheet has to be imported from a component, and that import is\nthe single most fragile line in the project: one full-file `write` of\n`App.tsx` drops it, and nothing notices (prod `0njsblk0lye2vsx`, 2026-08-01 \u2014\nthe layout stylesheet left the bundle, every gate stayed green). With one\nstylesheet imported once from `main.tsx`, the failure has nowhere to happen.\n\nPut component styles wherever the chosen approach puts them \u2014 Tailwind\nclasses by default \u2014 and shared values in `index.css`.\n\n## package.json\n\n```json\n{\n "name": "project-name",\n "private": true,\n "version": "0.1.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vite build",\n "preview": "vite preview",\n "verify": "tsc --noEmit && eslint . --max-warnings 0 && vite build"\n },\n "dependencies": {\n "react": "^19.0.0",\n "react-dom": "^19.0.0"\n },\n "devDependencies": {\n "@tailwindcss/vite": "^4.0.0",\n "@types/react": "^19.0.0",\n "@types/react-dom": "^19.0.0",\n "@vitejs/plugin-react": "^4.3.4",\n "eslint": "^9.0.0",\n "eslint-plugin-react-hooks": "^6.0.0",\n "tailwindcss": "^4.0.0",\n "typescript": "^5.0.0",\n "typescript-eslint": "^8.0.0",\n "vite": "^6.0.0"\n }\n}\n```\n\n`build` is `vite build` alone \u2014 no `tsc` in front of it. The platform runs the\ntype check itself before the build, and a `tsc` inside the build script also\nblocks the one-time build that runs when a starter is imported. `verify` is\nthe gate in one command; run it, not just `npm run build`.\n\n## vite.config.ts\n\n```ts\nimport { defineConfig } from \'vite\'\nimport react from \'@vitejs/plugin-react\'\nimport tailwindcss from \'@tailwindcss/vite\'\n\nexport default defineConfig({\n base: \'/\',\n plugins: [tailwindcss(), react()],\n})\n```\n\n## Entry Files\n\n`index.html`:\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <meta name="description" content="Replace this with a one-sentence description of the app." />\n <link rel="icon" type="image/svg+xml" href="/favicon.svg" />\n <title>Replace this title</title>\n </head>\n <body>\n <div id="root"></div>\n <script type="module" src="./src/main.tsx"></script>\n </body>\n</html>\n```\n\nKeep the favicon link and keep `public/favicon.svg`. Without them the browser\nrequests `/favicon.ico` on every page load and the render check records a\nfailed request on an otherwise healthy project.\n\n`src/main.tsx`:\n\n```tsx\nimport React from \'react\'\nimport ReactDOM from \'react-dom/client\'\nimport App from \'./App\'\nimport \'./index.css\'\n\nReactDOM.createRoot(document.getElementById(\'root\')!).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n)\n```\n\n`src/index.css` as the starter ships it \u2014 Tailwind first, then tokens, then\nthe opaque page baseline:\n\n```css\n@import "tailwindcss";\n\n/* Design tokens. Tailwind v4 turns every entry here into a utility\n (--color-brand -> bg-brand/text-brand), so restyle the project by editing\n these values rather than sprinkling hex codes through the components. */\n@theme {\n --color-brand: #4f46e5;\n --color-brand-contrast: #ffffff;\n --color-surface: #ffffff;\n --color-surface-muted: #f5f5f7;\n --color-ink: #111827;\n --color-ink-muted: #6b7280;\n --radius-card: 0.75rem;\n}\n\n:root {\n color-scheme: light;\n font-family: Inter, ui-sans-serif, system-ui, sans-serif;\n --app-bg: #ffffff;\n --app-fg: #111827;\n}\n\n/* An opaque background on html, body is mandatory \u2014 the page is never\n transparent. Keep this rule when you restyle. */\nhtml, body {\n margin: 0;\n min-height: 100%;\n min-width: 320px;\n background: var(--app-bg);\n color: var(--app-fg);\n}\n\n/* Keyboard focus baseline. Components may override it, but never remove it:\n the platform appends a generic fallback to any project whose CSS contains\n no `:focus` rule at all, and a real one belongs here. */\n:focus-visible {\n outline: 2px solid var(--color-brand, currentColor);\n outline-offset: 2px;\n}\n```\n\nEvery `@theme` entry becomes a utility (`--color-brand` \u2192 `bg-brand`), so\nrestyle by editing tokens instead of scattering hex codes through components.\nIf the user chose a non-Tailwind approach, keep `:root` and the `html, body`\nrule and replace the rest \u2014 the opaque background is not optional.\n\n`src/vite-env.d.ts`:\n\n```ts\n/// <reference types="vite/client" />\n```\n\n## TypeScript Config\n\nOne flat `tsconfig.json` with `include`, no project references and no\n`tsconfig.app.json`/`tsconfig.node.json`.\n\nThis is not a style preference. The platform gate runs `tsc --noEmit` against\nthe root `tsconfig.json`. A `create-vite`-style root \u2014 `"files": []` plus\n`references` \u2014 makes that command compile **zero files**: it exits 0 on a\nproject full of type errors, and the gate reports a pass it never performed.\nMeasured 2026-08-04: a deliberate type error passes the referenced shape and\nfails the flat one. `vite.config.ts` is deliberately not type-checked.\n\n`tsconfig.json`:\n\n```json\n{\n "compilerOptions": {\n "target": "ES2020",\n "useDefineForClassFields": true,\n "lib": ["ES2020", "DOM", "DOM.Iterable"],\n "module": "ESNext",\n "skipLibCheck": true,\n "moduleResolution": "bundler",\n "allowImportingTsExtensions": true,\n "resolveJsonModule": true,\n "isolatedModules": true,\n "noEmit": true,\n "jsx": "react-jsx",\n "strict": true\n },\n "include": ["src"]\n}\n```\n\n## ESLint Config\n\nEvery scaffold ships **exactly one** ESLint config, `eslint.config.mjs` (flat\nconfig), so the platform lint gate and the live ESLint diagnostics work from\nthe first turn. Keep it exactly this minimal \u2014 correctness rules only, no\nstylistic rules, nothing that fights Prettier:\n\n`eslint.config.mjs`:\n\n```js\nimport tseslint from \'typescript-eslint\'\nimport reactHooks from \'eslint-plugin-react-hooks\'\n\nexport default tseslint.config(\n { ignores: [\'dist\'] },\n {\n files: [\'**/*.{ts,tsx}\'],\n extends: [tseslint.configs.base],\n plugins: { \'react-hooks\': reactHooks },\n rules: {\n \'react-hooks/rules-of-hooks\': \'error\',\n \'react-hooks/exhaustive-deps\': \'error\',\n \'react-hooks/set-state-in-effect\': \'error\',\n \'react-hooks/no-deriving-state-in-effects\': \'error\',\n \'@typescript-eslint/no-unused-vars\': [\n \'error\',\n { argsIgnorePattern: \'^_\', varsIgnorePattern: \'^_\' },\n ],\n },\n },\n)\n```\n\n**Never add a second config file.** ESLint resolves `eslint.config.js` before\n`eslint.config.mjs` and uses only the first one it finds, silently. A stray\n`.js` next to the `.mjs` therefore disables every rule above without a\nwarning \u2014 measured on ESLint 9: a violation that fails with the `.mjs` alone\npasses when both files exist. So in an existing project, either keep its\n`eslint.config.js` as the single config, or migrate it into\n`eslint.config.mjs` and delete the `.js` \u2014 never leave both behind.\n\nThe platform runs `npx eslint . --max-warnings 0` before every build, so any\nviolation blocks the build. Do not add rules, do not remove rules, and never\n"fix" a violation with `eslint-disable` or config edits \u2014 fix the code (see\nthe hooks patterns below).\n\n## Allowed Complexity\n\n- Add `src/components/`, `src/pages/`, `src/lib/`, `src/hooks/` only when a\n feature needs them \u2014 do not scaffold empty folders.\n- Introduce state libraries or data-fetching only when real shared state or\n server data exists; local `useState`/`useReducer` covers most cases.\n- Keep components typed (props/return types); avoid `any`.\n\n## CSS And Styling Expectations\n\nThe starter ships Tailwind v4 via `@tailwindcss/vite`, and that is the\ndefault: keep it and tokenize theme values in `@theme`.\n\n**The user\'s request wins.** If they ask for a different styling approach,\nfollow them and adjust the setup in the same turn:\n\n- **shadcn/ui** \u2014 is built ON Tailwind. Keep Tailwind, add the components.\n Never remove Tailwind to "make room" for it.\n- **A CSS-in-JS library** (Chakra, MUI, styled-components, Emotion) \u2014 add it\n and build with it. Leaving Tailwind installed is harmless (v4 emits only\n the classes you use), so remove it only if the user asks.\n- **Plain CSS / CSS Modules** \u2014 drop `@tailwindcss/vite` and `tailwindcss`\n from `package.json`, remove the plugin from `vite.config.ts`, and replace\n `@import "tailwindcss"` in `index.css` with your own base styles. Keep the\n `:root` tokens and the opaque `html, body` rule.\n\nWhatever the approach, these hold:\n\n- **One stylesheet** \u2014 the rule below is about losing an import, not about\n Tailwind. It applies to plain CSS just as much.\n- Mobile-first, responsive layouts; visible focus states; WCAG AA contrast.\n- The loaded `style-*` skill governs the visual language \u2014 apply its recipe.\n It is written to be independent of the styling technology.\n\n## Routing Rules\n\nIf adding React Router, use `BrowserRouter` (history mode) with `base: \'/\'` in\n`vite.config.ts`. The platform serves at the domain root and falls unknown\ndeep-links back to `index.html`, so routes resolve on hard refresh with clean\nURLs (no `#`). Never use `HashRouter`. Add `react-router-dom` only when routing\nis actually needed.\n\n## Data And Backend Rules\n\n- No database/server calls unless a backend is configured (respect the build\n agent\'s STOP gate). Do not invent mock backends or fake data arrays.\n- Keep secrets out of client code; only public keys via `.env.local`.\n\n## Asset Path Rules\n\n- Set `base: \'/\'` in `vite.config.ts`. The platform serves the project at the\n domain root, and history-mode routes need root-absolute assets.\n- Reference the project\'s own assets/routes with root-absolute paths (`/assets/...`);\n no `<base>` tag, no hardcoded platform URLs.\n\n## Verification\n\nRun install, then the full platform verification contract (see the build\nagent\'s "Build And Preview Rules"), not just `npm run build`:\n\n1. `npx tsc --noEmit`\n2. `npx eslint . --max-warnings 0` \u2014 a project scaffolded from this skill\n ships `eslint.config.mjs`, so this check ALWAYS applies and decides\n acceptance.\n3. `npm run build`\n4. `dist/index.html` exists\n\n`npm run verify` runs 1\u20133 in order. Never make step 2 pass by disabling rules\nor adding `eslint-disable`.\n\n## React Hooks Rules That Fail The Gate\n\nThe scaffold\'s `eslint.config.mjs` enables `eslint-plugin-react-hooks` rules\nthat reject patterns which compile and build fine. These are the ones that\nactually show up \u2014 avoid them while writing, not after:\n\n- **Never sync props into state inside an effect**\n (`useEffect(() => setForm(props.item), [props.item])` \u2192 `set-state-in-effect`).\n Derive the value during render, lift the state up, or remount the subtree\n with a `key` when the edited record changes \u2014 that is usually the intended\n "reset the form" semantic anyway.\n- **Do not open dialogs/editors from an effect that watches the URL.** Derive\n the open state from the route during render, or set it in the event handler\n that triggered the navigation.\n- **Do not bootstrap an external store from a render-time side effect.** Read\n it with `useSyncExternalStore`, or initialize it in the store module itself.\n- **Async loads:** only update state after an await when the effect has not\n been cleaned up (cancellation flag or `AbortController`).\n- **No impure render calls** \u2014 no `Math.random()`, `Date.now()`, or mutation\n during render. Move them into a lazy initializer or an event handler.\n- **Fast Refresh:** a module that exports a component must not also export\n unrelated non-component values (`react-refresh/only-export-components`).\n\nA `setTimeout`/microtask wrapper that only hides the violation from the linter\nis not a fix \u2014 it hides the same bug behind a race.\n\n## Common Failure Modes\n\n- Recreating the starter\'s files instead of editing them.\n- Adding `src/App.css` (or any second stylesheet) \u2014 see "One Stylesheet".\n- Adding `eslint.config.js` beside `eslint.config.mjs`, which silently\n disables the rule set.\n- Restoring the `create-vite` tsconfig trio, which makes the type check inert.\n- Putting `tsc` back into the `build` script.\n- Deleting `public/favicon.svg` or its `<link rel="icon">`.\n- Using `HashRouter` \u2192 ugly `#` URLs; use `BrowserRouter` (history mode).\n- Keeping relative `base: \'./\'` with history routing \u2192 assets 404 on a deep-link\n hard refresh; use `base: \'/\'`.\n- Leaving the starter\'s placeholder copy ("Replace this headline", "Brand",\n "First point") in the shipped page.\n- Over-splitting into trivial components; untyped `any` props.\n- Treating pre-install JSX type errors as source bugs (install deps first).\n',
6856
7002
  "vue-scaffold": '---\nname: vue-scaffold\ndescription: Vue 3.5 with Vite, TypeScript, and Tailwind CSS v4 scaffold generated manually without npm create. Use for explicit Vue requests or existing Vue projects.\n---\n\n# Vue Scaffold\n\n## Stack Briefing\n\nVue 3.5 + Vite + TypeScript + Tailwind v4, written manually (never `npm create`).\nUse it for app-like Vue UIs. Output must stay static-hostable: `base: \'/\'`,\nhistory mode (clean URLs, no `#`), build to `dist/`. Use the Composition API; add Pinia or Vue Router\nonly when real shared state or routing actually exists.\n\n## When To Use\n\nUse this skill when `selected_stack` is Vue. Prefer Vue only when requested, when the existing project uses Vue, or when the user clearly wants a Vue-style app.\n\n## When Not To Use\n\n- Static marketing/content/portfolio sites \u2192 `vanilla-scaffold`.\n- Content-heavy multi-page sites \u2192 `astro-scaffold`.\n- Anything needing SSR \u2014 output here is static only.\n\n## HARD STOP: Never Re-Scaffold An Existing App\n\nBefore writing ANY scaffold file, check the workspace. If `package.json` (or\nan existing `index.html` app shell for vanilla projects) and source files\nalready exist, this project already has an app \u2014 scaffolding is DONE and this\nskill must not overwrite it. Read the existing entry points and source tree\nfirst, then build ON TOP of the existing files: keep the entry points,\nrouting, and dependency choices already in place. Overwriting the scaffold\nfiles on an existing project destroys the user\'s app (this happened in\nproduction). If the existing code seems inconsistent with the request, ask\nthe user \u2014 never replace silently.\n\n## Required File Shape\n\nThis is the shape a Vue project has here. Depending on how the project\nstarted, these files may already exist in the workspace \u2014 check first:\n\n```text\nindex.html entry: favicon link, #app, module script\npackage.json build = `vite build`; `npm run verify` runs the full gate\nvite.config.ts base: \'/\', tailwindcss() + vue()\ntsconfig.json ONE flat config, no references\neslint.config.mjs the only ESLint config in the project\npublic/\n favicon.svg keep it \u2014 without a favicon every page logs a 404\nsrc/\n App.vue placeholder shell: header/nav, hero, cards, footer\n main.ts entry, imports ./style.css\n style.css THE stylesheet \u2014 Tailwind by default\n env.d.ts vite/client types (inside src/, so the include glob covers it)\n shims-vue.d.ts lets plain `tsc` resolve *.vue \u2014 see below, load-bearing\n.gitignore\n```\n\n**Empty workspace** \u2014 create exactly this shape.\n\n**Files already present** \u2014 **edit them, do not recreate them.** Rewrite the\ncopy, restyle the `@theme` tokens, add components and routes, but keep the\nshape.\n\n**A project from an older `create-vue` starter** ships config that silently\ndisables checks the platform believes it ran. Repair config only \u2014 never a\nfull-file `write` of `App.vue`, `main.ts` or `package.json`:\n\n| found | do |\n| --- | --- |\n| `tsconfig.json` with `"files": []` + `references` | replace with the flat config below, delete `tsconfig.app.json`/`tsconfig.node.json`, and add `src/shims-vue.d.ts` \u2014 the trio makes the type check inert, but removing it without the shim makes it fail |\n| no ESLint config at all | add `eslint.config.mjs` below \u2014 without it the lint gate is inert and never sees a template bug |\n| `src/router/index.ts` with `routes: []`, an unused store | delete them, or give them real routes/state |\n\nCreate `src/components/`, `src/views/`, `src/router/`, or `src/stores/` only when needed.\n\n## package.json\n\n```json\n{\n "name": "project-name",\n "private": true,\n "version": "0.1.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vite build",\n "preview": "vite preview",\n "verify": "vue-tsc --noEmit && eslint . --max-warnings 0 && vite build"\n },\n "dependencies": {\n "vue": "^3.5.0"\n },\n "devDependencies": {\n "@tailwindcss/vite": "^4.0.0",\n "@vitejs/plugin-vue": "^6.0.0",\n "eslint": "^9.0.0",\n "eslint-plugin-vue": "^10.0.0",\n "tailwindcss": "^4.0.0",\n "typescript": "^5.0.0",\n "typescript-eslint": "^8.0.0",\n "vite": "^6.0.0",\n "vue-tsc": "^2.2.0"\n }\n}\n```\n\n## vite.config.ts\n\n```ts\nimport { defineConfig } from \'vite\'\nimport vue from \'@vitejs/plugin-vue\'\nimport tailwindcss from \'@tailwindcss/vite\'\n\nexport default defineConfig({\n base: \'/\',\n plugins: [tailwindcss(), vue()],\n})\n```\n\n## Entry Files\n\n`index.html`:\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <meta name="description" content="Replace this with a one-sentence description of the app." />\n <link rel="icon" type="image/svg+xml" href="/favicon.svg" />\n <title>Replace this title</title>\n </head>\n <body>\n <div id="app"></div>\n <script type="module" src="./src/main.ts"></script>\n </body>\n</html>\n```\n\n`src/main.ts`:\n\n```ts\nimport { createApp } from \'vue\'\nimport App from \'./App.vue\'\nimport \'./style.css\'\n\ncreateApp(App).mount(\'#app\')\n```\n\n`src/style.css`:\n\n```css\n@import "tailwindcss";\n\n/* Design tokens. Tailwind v4 turns every entry here into a utility\n (--color-brand -> bg-brand/text-brand), so restyle the project by editing\n these values rather than sprinkling hex codes through the components. */\n@theme {\n --color-brand: #41b883;\n --color-brand-contrast: #ffffff;\n --color-surface: #ffffff;\n --color-surface-muted: #f5f5f7;\n --color-ink: #111827;\n --color-ink-muted: #6b7280;\n --radius-card: 0.75rem;\n}\n\n:root {\n color-scheme: light;\n font-family: Inter, ui-sans-serif, system-ui, sans-serif;\n --app-bg: #ffffff;\n --app-fg: #111827;\n}\n\n/* An opaque background on html, body is mandatory \u2014 the page is never\n transparent. Keep this rule when you restyle. */\nhtml, body {\n margin: 0;\n min-height: 100%;\n min-width: 320px;\n background: var(--app-bg);\n color: var(--app-fg);\n}\n\n/* Keyboard focus baseline. Components may override it, but never remove it:\n the platform appends a generic fallback to any project whose CSS contains\n no `:focus` rule at all, and a real one belongs here. */\n:focus-visible {\n outline: 2px solid var(--color-brand, currentColor);\n outline-offset: 2px;\n}\n```\n\nTailwind is the **default**, not a mandate \u2014 the same rule as elsewhere: if\nthe user asks for a different styling approach, follow them and adjust the\nsetup in the same turn. Vue SFC `<style scoped>` blocks are idiomatic and fine\nalongside it; the thing to avoid is a second global stylesheet imported from a\ncomponent, because one full-file rewrite drops that import silently.\n\n## TypeScript Config\n\nOne flat `tsconfig.json` with `include`, no project references and no\n`tsconfig.app.json`/`tsconfig.node.json`.\n\nThis is not a style preference. The platform gate runs `tsc --noEmit` against\nthe root `tsconfig.json`. A `create-vue`-style root \u2014 `"files": []` plus\n`references` \u2014 makes that command compile **zero files**: it exits 0 on a\nproject full of type errors and the gate reports a pass it never performed.\n\n`vite.config.ts` is deliberately not type-checked.\n\n### `src/shims-vue.d.ts` Is Load-Bearing\n\nThe gate runs `tsc`, **never `vue-tsc`** \u2014 and plain `tsc` cannot resolve an\nimport of a `.vue` file. Without the shim the very first line of `main.ts`\nfails the gate on a phantom error (measured 2026-08-04):\n\n```text\nsrc/main.ts(2,17): error TS2307: Cannot find module \'./App.vue\'\n```\n\nSo the flat tsconfig and the shim are one change: applying either alone is\nworse than the broken state it replaces. Ship both.\n\n`src/shims-vue.d.ts`:\n\n```ts\n/* Lets plain `tsc` resolve `*.vue` imports.\n *\n * Load-bearing: the platform\'s prebuild gate runs `tsc --noEmit`, never\n * `vue-tsc`. Without this shim it stops at\n * src/main.ts: error TS2307: Cannot find module \'./App.vue\'\n * and every build fails on a phantom error.\n *\n * The shim types an SFC as a generic component, so `tsc` checks all `.ts`\n * files properly but not the internals of a `.vue` file. `npm run verify`\n * runs `vue-tsc --noEmit`, which does check those \u2014 use it before finishing.\n */\ndeclare module \'*.vue\' {\n import type { DefineComponent } from \'vue\'\n const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>\n export default component\n}\n```\n\nWhat this buys and what it does not \u2014 all three measured:\n\n| | `tsc` (the gate) | `vue-tsc` (`npm run verify`) |\n| --- | --- | --- |\n| type error in a `.ts` file | caught | caught |\n| type error inside a `.vue` SFC | **missed** \u2014 the shim types it generically | caught |\n\nThat is why `verify` runs `vue-tsc` and why passing the gate is not the same\nas being done.\n\n`tsconfig.json`:\n\n```json\n{\n "compilerOptions": {\n "target": "ES2020",\n "useDefineForClassFields": true,\n "module": "ESNext",\n "lib": ["ES2020", "DOM", "DOM.Iterable"],\n "skipLibCheck": true,\n "moduleResolution": "bundler",\n "allowImportingTsExtensions": true,\n "resolveJsonModule": true,\n "isolatedModules": true,\n "noEmit": true,\n "jsx": "preserve",\n "strict": true\n },\n "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]\n}\n```\n\n## Routing Rules\n\nIf adding Vue Router, use `createWebHistory()` (history mode) with `base: \'/\'` in\n`vite.config.ts`. The platform serves at the domain root and falls unknown\ndeep-links back to `index.html`, so routes resolve on hard refresh with clean\nURLs (no `#`). Never use `createWebHashHistory()`. Add `vue-router` only when\nrouting is needed.\n\n## Data And Backend Rules\n\n- No database/server calls unless a backend is configured (respect the build\n agent\'s STOP gate). Do not invent mock backends or fake data arrays.\n- Keep secrets out of client code; only public keys via `.env.local`.\n\n## Asset Path Rules\n\n- Set `base: \'/\'`. The platform serves the project at the domain root, and\n history-mode routes need root-absolute assets. Reference the project\'s own\n assets/routes with root-absolute paths. No `<base>` tag, no hardcoded platform URLs.\n\n## Common Failure Modes\n\n- Using `createWebHashHistory()` \u2192 ugly `#` URLs; use `createWebHistory()`.\n- Keeping relative `base: \'./\'` with history routing \u2192 assets 404 on a deep-link\n hard refresh; use `base: \'/\'`.\n- Leaving starter boilerplate in `App.vue`.\n- Adding Pinia/Router with no real need.\n\n## ESLint Config\n\nEvery scaffold ships `eslint.config.mjs` (flat config) so the platform lint\ngate and the live ESLint diagnostics work from the very first turn. Verified\nempirically 2026-08-02: `flat/essential` catches real template bugs\n(`vue/require-v-for-key` etc.); `vue/multi-word-component-names` is switched\nOFF because with `--max-warnings 0` it would block every `Hero.vue`-style\nsingle-word component \u2014 a naming convention, not a correctness rule:\n\n`eslint.config.mjs`:\n\n```js\nimport tseslint from \'typescript-eslint\'\nimport vue from \'eslint-plugin-vue\'\n\nexport default tseslint.config(\n { ignores: [\'dist\'] },\n {\n files: [\'**/*.ts\'],\n extends: [tseslint.configs.base],\n rules: {\n \'@typescript-eslint/no-unused-vars\': [\n \'error\',\n { argsIgnorePattern: \'^_\', varsIgnorePattern: \'^_\' },\n ],\n },\n },\n ...vue.configs[\'flat/essential\'],\n {\n files: [\'**/*.vue\'],\n languageOptions: { parserOptions: { parser: tseslint.parser } },\n rules: {\n \'vue/multi-word-component-names\': \'off\',\n },\n },\n)\n```\n\nThe platform runs `npx eslint . --max-warnings 0` before every build, so any\nviolation blocks the build. Do not add or remove rules, and never "fix" a\nviolation with `eslint-disable` or config edits \u2014 fix the code.\n\n## Verification\n\nRun install, then the full platform verification contract (see the build\nagent\'s "Build And Preview Rules"): typecheck, `npx eslint . --max-warnings 0`\n(the scaffold ships `eslint.config.mjs`, so this check ALWAYS applies and\ndecides acceptance), `npm run build`, and finally verify that\n`dist/index.html` exists. `npm run build` alone is not what the platform gate\nchecks. Never make the lint step pass by disabling rules.\n',
@@ -6878,8 +7024,8 @@ targets the managed backend, with these local rules:
6878
7024
  - **Collections/schema:** you cannot run \`agentful-managed-collections\`
6879
7025
  here \u2014 DECLARE every collection in \`.agentful/backend.json\` instead
6880
7026
  (\`"schema_version": 2\`, \`"collections": [...]\`; \`access_rule\` is
6881
- required, field types exactly string/text/number/boolean/select/datetime/
6882
- json \u2014 see AGENTFUL_CLOUD.md for the shape). The normal \`agentful push\`
7027
+ required, field types exactly string/text/number/boolean/select/date/
7028
+ datetime/json \u2014 see AGENTFUL_CLOUD.md for the shape). The normal \`agentful push\`
6883
7029
  applies the declaration on the platform once the owner has enabled the
6884
7030
  database (additive: new collections/fields are created or updated, removed
6885
7031
  fields are reported, never deleted). The push output is the ONLY
@@ -6911,7 +7057,7 @@ var SCAFFOLD_BY_FRAMEWORK = {
6911
7057
  };
6912
7058
  function hasVueDependency(rootDir) {
6913
7059
  try {
6914
- const pkg = JSON.parse((0, import_node_fs12.readFileSync)((0, import_node_path14.join)(rootDir, "package.json"), "utf8"));
7060
+ const pkg = JSON.parse((0, import_node_fs13.readFileSync)((0, import_node_path15.join)(rootDir, "package.json"), "utf8"));
6915
7061
  return Boolean({ ...pkg.dependencies, ...pkg.devDependencies }["vue"]);
6916
7062
  } catch {
6917
7063
  return false;
@@ -6941,7 +7087,7 @@ function renderSkillsInstruction(names) {
6941
7087
  return "# Platform deployment skills (mandatory)\n\nThese are the same skills the cloud build agent loads for this stack.\nFollow them when scaffolding or editing \u2014 they are not optional hints.\n\n" + sections.join("\n\n---\n\n") + "\n";
6942
7088
  }
6943
7089
  function skillsInstructionFor(framework, rootDir) {
6944
- if (!(0, import_node_fs12.existsSync)(rootDir)) return null;
7090
+ if (!(0, import_node_fs13.existsSync)(rootDir)) return null;
6945
7091
  return renderSkillsInstruction(selectSkills(framework, rootDir));
6946
7092
  }
6947
7093
 
@@ -7056,15 +7202,15 @@ function decideLocalProviders(policy) {
7056
7202
  }
7057
7203
 
7058
7204
  // src/lib/localProviders.ts
7059
- var import_node_fs13 = require("fs");
7060
- var import_node_path15 = require("path");
7205
+ var import_node_fs14 = require("fs");
7206
+ var import_node_path16 = require("path");
7061
7207
  var LOCAL_PROVIDERS_FILE = "local-providers.json";
7062
7208
  function localProvidersPath() {
7063
- return (0, import_node_path15.join)(configDir(), LOCAL_PROVIDERS_FILE);
7209
+ return (0, import_node_path16.join)(configDir(), LOCAL_PROVIDERS_FILE);
7064
7210
  }
7065
7211
  function readLocalProviders() {
7066
7212
  try {
7067
- const raw = JSON.parse((0, import_node_fs13.readFileSync)(localProvidersPath(), "utf8"));
7213
+ const raw = JSON.parse((0, import_node_fs14.readFileSync)(localProvidersPath(), "utf8"));
7068
7214
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
7069
7215
  const map = raw.providers && typeof raw.providers === "object" ? raw.providers : raw;
7070
7216
  const usable = {};
@@ -7099,8 +7245,8 @@ function resolveLocalProviders(policy) {
7099
7245
  }
7100
7246
  function writeLocalProvidersExample() {
7101
7247
  const path = localProvidersPath();
7102
- if ((0, import_node_fs13.existsSync)(path)) return path;
7103
- (0, import_node_fs13.mkdirSync)(configDir(), { recursive: true });
7248
+ if ((0, import_node_fs14.existsSync)(path)) return path;
7249
+ (0, import_node_fs14.mkdirSync)(configDir(), { recursive: true });
7104
7250
  const example = {
7105
7251
  _comment: 'Providers with your own API key, running locally. Requests go directly to the provider \u2014 no Agentful credits, no platform region guarantee. Remove the leading underscore from "_anthropic" and fill in your key to enable it.',
7106
7252
  _anthropic: {
@@ -7110,21 +7256,21 @@ function writeLocalProvidersExample() {
7110
7256
  models: { "claude-sonnet-4-5": { name: "Claude Sonnet 4.5 (my key)" } }
7111
7257
  }
7112
7258
  };
7113
- (0, import_node_fs13.writeFileSync)(path, JSON.stringify(example, null, 2) + "\n", "utf8");
7259
+ (0, import_node_fs14.writeFileSync)(path, JSON.stringify(example, null, 2) + "\n", "utf8");
7114
7260
  try {
7115
- (0, import_node_fs13.chmodSync)(path, 384);
7261
+ (0, import_node_fs14.chmodSync)(path, 384);
7116
7262
  } catch {
7117
7263
  }
7118
7264
  return path;
7119
7265
  }
7120
7266
 
7121
7267
  // src/lib/sessions.ts
7122
- var import_node_fs14 = require("fs");
7123
- var import_node_path16 = require("path");
7268
+ var import_node_fs15 = require("fs");
7269
+ var import_node_path17 = require("path");
7124
7270
  var import_node_child_process4 = require("child_process");
7125
7271
  function lastSessionForDirectory(cwd = process.cwd()) {
7126
- const dbPath = (0, import_node_path16.join)(engineXdg().dataHome, "opencode", "opencode.db");
7127
- if (!(0, import_node_fs14.existsSync)(dbPath)) return null;
7272
+ const dbPath = (0, import_node_path17.join)(engineXdg().dataHome, "opencode", "opencode.db");
7273
+ if (!(0, import_node_fs15.existsSync)(dbPath)) return null;
7128
7274
  const escaped = cwd.replace(/'/g, "''");
7129
7275
  const res = (0, import_node_child_process4.spawnSync)(
7130
7276
  "sqlite3",
@@ -7216,7 +7362,7 @@ async function tuiCommand(opts = {}) {
7216
7362
  ...process.env,
7217
7363
  // Slash commands run `agentful …` through the agent's bash tool, which
7218
7364
  // has no access to the user's shell aliases.
7219
- PATH: `${binDir}${import_node_path17.delimiter}${process.env.PATH || ""}`,
7365
+ PATH: `${binDir}${import_node_path18.delimiter}${process.env.PATH || ""}`,
7220
7366
  XDG_CONFIG_HOME: xdg.configHome,
7221
7367
  XDG_DATA_HOME: xdg.dataHome,
7222
7368
  XDG_STATE_HOME: xdg.stateHome,
@@ -7321,28 +7467,28 @@ async function shareCommand(opts) {
7321
7467
  }
7322
7468
 
7323
7469
  // src/commands/pull.ts
7324
- var import_node_fs15 = require("fs");
7325
- var import_node_path18 = require("path");
7470
+ var import_node_fs16 = require("fs");
7471
+ var import_node_path19 = require("path");
7326
7472
  init_branding();
7327
7473
  init_branding();
7328
7474
  function isProbablyBase64Binary(path) {
7329
7475
  return /\.(png|jpe?g|gif|webp|ico|woff2?|ttf|otf|eot|pdf|zip|mp[34]|webm|avif)$/i.test(path);
7330
7476
  }
7331
7477
  function writeEntry(root, rel, value) {
7332
- const target = (0, import_node_path18.join)(root, rel);
7333
- (0, import_node_fs15.mkdirSync)((0, import_node_path18.dirname)(target), { recursive: true });
7478
+ const target = (0, import_node_path19.join)(root, rel);
7479
+ (0, import_node_fs16.mkdirSync)((0, import_node_path19.dirname)(target), { recursive: true });
7334
7480
  const content = typeof value === "object" && value !== null && "content" in value ? String(value.content) : String(value ?? "");
7335
7481
  if (isProbablyBase64Binary(rel)) {
7336
- (0, import_node_fs15.writeFileSync)(target, Buffer.from(content, "base64"));
7482
+ (0, import_node_fs16.writeFileSync)(target, Buffer.from(content, "base64"));
7337
7483
  } else {
7338
- (0, import_node_fs15.writeFileSync)(target, content, "utf8");
7484
+ (0, import_node_fs16.writeFileSync)(target, content, "utf8");
7339
7485
  }
7340
7486
  }
7341
7487
  async function pullCommand(opts) {
7342
7488
  console.log(banner());
7343
7489
  const auth = await ensureAuth();
7344
7490
  const project = requireProject();
7345
- const nonHidden = (0, import_node_fs15.readdirSync)(process.cwd()).filter((n) => n !== ".agentful" && !n.startsWith("."));
7491
+ const nonHidden = (0, import_node_fs16.readdirSync)(process.cwd()).filter((n) => n !== ".agentful" && !n.startsWith("."));
7346
7492
  if (nonHidden.length > 0 && !opts.force) {
7347
7493
  throw new ApiError(
7348
7494
  0,
@@ -7366,9 +7512,9 @@ async function pullCommand(opts) {
7366
7512
  ui.warn(`Skipped ${rel} (HTTP ${resp.status})`);
7367
7513
  continue;
7368
7514
  }
7369
- const target = (0, import_node_path18.join)(process.cwd(), rel);
7370
- (0, import_node_fs15.mkdirSync)((0, import_node_path18.dirname)(target), { recursive: true });
7371
- (0, import_node_fs15.writeFileSync)(target, Buffer.from(await resp.arrayBuffer()));
7515
+ const target = (0, import_node_path19.join)(process.cwd(), rel);
7516
+ (0, import_node_fs16.mkdirSync)((0, import_node_path19.dirname)(target), { recursive: true });
7517
+ (0, import_node_fs16.writeFileSync)(target, Buffer.from(await resp.arrayBuffer()));
7372
7518
  written++;
7373
7519
  }
7374
7520
  } else if (data.files) {
@@ -7522,7 +7668,7 @@ program2.command("login").description("Sign in to your Agentful account (device
7522
7668
  program2.command("logout").description("Remove the stored credentials").action(run(logoutCommand));
7523
7669
  program2.command("whoami").description("Show the signed-in account").action(run(whoamiCommand));
7524
7670
  program2.command("init").description("Create (or link) the Agentful cloud project for this directory").argument("[directory]", "with --template: new folder to scaffold into (created for you)").option("--link <projectId>", "link an existing project instead of creating one").option("--title <title>", "project title (skips the prompt)").option("--template <framework>", "scaffold from a platform starter (nextjs, react, vue, vanilla)").action(run((directory, opts) => initCommand(opts, directory)));
7525
- program2.command("push").description("Upload this project and get a live preview URL").option("--prebuilt", "upload a locally built output instead of building in the cloud").option("--dir <path>", "built-output directory for --prebuilt (default: auto-detect)").option("--force", "push even when the pre-upload compatibility check finds blocking issues").action(run((opts) => pushCommand(opts)));
7671
+ program2.command("push").description("Upload this project and get a live preview URL").option("--prebuilt", "upload a locally built output instead of building in the cloud").option("--dir <path>", "built-output directory for --prebuilt (default: auto-detect)").option("--force", "push even when the pre-upload compatibility check finds blocking issues").option("-y, --yes", "enable the declared managed database without asking (CI); a non-interactive push never enables it").action(run((opts) => pushCommand(opts)));
7526
7672
  program2.command("build-status").description("Show the cloud's record of the last build (the real error on failures)").action(run(buildStatusCommand));
7527
7673
  program2.command("backend").description("Open this project's Backend tab (managed DB + server actions) in the browser").action(run(backendCommand));
7528
7674
  program2.command("open").description("Open the live preview in the browser").action(run(openCommand));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentful",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Agentful in your terminal — local development with push-to-cloud previews",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://agentful.dev",