clivly 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -3,7 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const require_entity_config = require("./entity-config-D87rV-tE.cjs");
4
4
  require("./mapping-score-CaB3F4Uu.cjs");
5
5
  const require_internal_entity_heuristics = require("./internal-entity-heuristics.cjs");
6
- const require_sdk = require("./sdk-iqOXeWIp.cjs");
6
+ const require_sdk = require("./sdk-Bj-ZDf4u.cjs");
7
7
  let node_child_process = require("node:child_process");
8
8
  let node_fs = require("node:fs");
9
9
  let node_module = require("node:module");
@@ -12,6 +12,72 @@ let node_path = require("node:path");
12
12
  let node_readline_promises = require("node:readline/promises");
13
13
  let jiti = require("jiti");
14
14
  let node_url = require("node:url");
15
+ //#region ../core/src/env-file.ts
16
+ const ENV_FILES = {
17
+ next: ".env.local",
18
+ "tanstack-start": ".env",
19
+ sveltekit: ".env",
20
+ remix: ".env",
21
+ nuxt: ".env",
22
+ "hono-workers": ".dev.vars"
23
+ };
24
+ /** The conventional env file for a framework. `.env` when we do not know. */
25
+ function envFileFor(framework) {
26
+ return ENV_FILES[normalizeFramework(framework)] ?? ".env";
27
+ }
28
+ const ALIASES = {
29
+ next: "next",
30
+ nextjs: "next",
31
+ "next.js": "next",
32
+ "tanstack-start": "tanstack-start",
33
+ tanstack: "tanstack-start",
34
+ sveltekit: "sveltekit",
35
+ remix: "remix",
36
+ nuxt: "nuxt",
37
+ "hono-workers": "hono-workers",
38
+ hono: "hono-workers",
39
+ workers: "hono-workers"
40
+ };
41
+ /** The canonical id for a framework name, or null when unrecognised. */
42
+ function normalizeFramework(framework) {
43
+ if (!framework) return null;
44
+ return ALIASES[framework.toLowerCase()] ?? null;
45
+ }
46
+ /**
47
+ * Which env file to actually write to.
48
+ *
49
+ * Prefers a file that already holds the key over the conventional one: a
50
+ * project that has been running with credentials in `.env` must not suddenly
51
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
52
+ * stale one still loading. Convention applies to new setups, not to a working
53
+ * one someone already has.
54
+ */
55
+ function resolveEnvFile(input) {
56
+ const conventional = envFileFor(input.framework);
57
+ if (input.existing.includes(conventional)) return conventional;
58
+ return input.existing[0] ?? conventional;
59
+ }
60
+ //#endregion
61
+ //#region src/app-layout.ts
62
+ function resolveAppLayout(cwd, fileExists = node_fs.existsSync) {
63
+ if (fileExists((0, node_path.join)(cwd, "src", "app"))) return "src/app";
64
+ if (fileExists((0, node_path.join)(cwd, "app"))) return "app";
65
+ return fileExists((0, node_path.join)(cwd, "src")) ? "src/app" : "app";
66
+ }
67
+ function shadowedAppDirError(cwd, framework, plannedPaths, fileExists = node_fs.existsSync) {
68
+ if (framework !== "nextjs") return null;
69
+ if (!plannedPaths.some((path) => path.startsWith("app/"))) return null;
70
+ if (!fileExists((0, node_path.join)(cwd, "src", "app"))) return null;
71
+ return `This project has a src/app directory, so writing routes to app/ would shadow it.
72
+
73
+ Next.js reads either app/ or src/app/, never both. A root app/ directory wins,
74
+ and every route under src/app/ disappears from the build.
75
+
76
+ Nothing was written. Please report this at https://github.com/amani-joseph/clivly/issues
77
+ — Clivly should have detected the src/app layout automatically.
78
+ `;
79
+ }
80
+ //#endregion
15
81
  //#region src/load-config.ts
16
82
  const CONFIG_HINT = "Expected clivly.config.ts at your app root exporting `createClivlySDK({...})`.";
17
83
  function resolveConfigPath(cwd, configPath) {
@@ -109,6 +175,14 @@ async function loadCliConfig(cwd) {
109
175
  return envFiles ? { envFiles } : {};
110
176
  }
111
177
  //#endregion
178
+ //#region src/dashboard-locations.ts
179
+ /** Secret + publishable keys. The Connect dialog mints them and shows the secret once. */
180
+ const CREDENTIALS_LOCATION = "Clivly dashboard → Connect app (or Settings → API keys)";
181
+ /** The signing secret Clivly Cloud uses on sync-trigger callbacks. */
182
+ const SYNC_SECRET_LOCATION = "Clivly dashboard → Integrations → Remote sync";
183
+ /** Chat widget records and their allowed origins. */
184
+ const WIDGET_LOCATION = "Clivly dashboard → Settings → Chat widget";
185
+ //#endregion
112
186
  //#region src/detect.ts
113
187
  const FRAMEWORK_MARKERS = [
114
188
  {
@@ -254,8 +328,19 @@ const OVERRIDE_FAILURE_CAUSES = {
254
328
  not_enabled: "The target backend does not have the feature-flagged trigger-url endpoint enabled (likely the wrong backend, or the flag is off).",
255
329
  unreachable: "Could not reach Clivly at the selected API base URL."
256
330
  };
257
- function overrideFailureMessage(kind) {
258
- return `Warning: could not register the tunnel URL — ${OVERRIDE_FAILURE_CAUSES[kind]} Dashboard-triggered sync is unavailable this session. Your app is still running.`;
331
+ /**
332
+ * `status` is required in practice for `unexpected_response` and meaningless
333
+ * for the others.
334
+ *
335
+ * Every non-401/404 status used to collapse into `unreachable`, so the CLI told
336
+ * developers it "could not reach Clivly" while Clivly was answering. That is
337
+ * not a wording nit: when neon-http broke these endpoints in production the CLI
338
+ * discarded the one honest signal it had (HTTP 500) and sent people to check
339
+ * their network and API URL, where nothing was wrong. A response is proof of
340
+ * reachability — so say what came back.
341
+ */
342
+ function overrideFailureMessage(kind, status) {
343
+ return `Warning: could not register the tunnel URL — ${kind === "unexpected_response" ? `Clivly answered HTTP ${status ?? "an error"} — the request reached Clivly but was rejected, so this is a Clivly-side or request problem rather than a network one.` : OVERRIDE_FAILURE_CAUSES[kind]} Dashboard-triggered sync is unavailable this session. Your app is still running.`;
259
344
  }
260
345
  function cloudflaredMissingMessage() {
261
346
  return [
@@ -310,12 +395,16 @@ async function runDev(options) {
310
395
  deps.out(`Tunnel: ${triggerUrl}`);
311
396
  const result = await deps.register(triggerUrl).catch(() => UNREACHABLE_RESULT);
312
397
  if (result.ok) deps.out("Dashboard-triggered sync now points at this local session.");
313
- else deps.out(overrideFailureMessage(result.kind));
398
+ else deps.out(overrideFailureMessage(result.kind, result.status));
314
399
  });
400
+ const stopWatching = deps.watchConfig?.(options.cwd, () => {
401
+ deps.out("clivly.config.ts changed — restart your app for it to take effect.");
402
+ }) ?? null;
315
403
  return await new Promise((resolve) => {
316
404
  const shutdown = async (code) => {
317
405
  if (shuttingDown) return;
318
406
  shuttingDown = true;
407
+ stopWatching?.();
319
408
  tunnel.kill();
320
409
  app?.kill();
321
410
  if (!(await deps.clear().catch(() => UNREACHABLE_RESULT)).ok) deps.out("Warning: could not clear the tunnel override on exit.");
@@ -337,7 +426,18 @@ const HTTP_NOT_FOUND = 404;
337
426
  function kindForStatus(status) {
338
427
  if (status === HTTP_UNAUTHORIZED) return "unauthorized";
339
428
  if (status === HTTP_NOT_FOUND) return "not_enabled";
340
- return "unreachable";
429
+ return "unexpected_response";
430
+ }
431
+ function failureFor(status) {
432
+ const kind = kindForStatus(status);
433
+ return kind === "unexpected_response" ? {
434
+ ok: false,
435
+ kind,
436
+ status
437
+ } : {
438
+ ok: false,
439
+ kind
440
+ };
341
441
  }
342
442
  async function registerTunnelOverride(deps) {
343
443
  const res = await (deps.fetchImpl ?? globalThis.fetch)(`${deps.apiUrl}${TRIGGER_URL_PATH}`, {
@@ -349,10 +449,7 @@ async function registerTunnelOverride(deps) {
349
449
  body: JSON.stringify({ url: deps.triggerUrl })
350
450
  });
351
451
  if (res.ok) return { ok: true };
352
- return {
353
- ok: false,
354
- kind: kindForStatus(res.status)
355
- };
452
+ return failureFor(res.status);
356
453
  }
357
454
  async function clearTunnelOverride(deps) {
358
455
  const res = await (deps.fetchImpl ?? globalThis.fetch)(`${deps.apiUrl}${TRIGGER_URL_PATH}`, {
@@ -360,10 +457,7 @@ async function clearTunnelOverride(deps) {
360
457
  headers: { authorization: `Bearer ${deps.apiKey}` }
361
458
  });
362
459
  if (res.ok) return { ok: true };
363
- return {
364
- ok: false,
365
- kind: kindForStatus(res.status)
366
- };
460
+ return failureFor(res.status);
367
461
  }
368
462
  //#endregion
369
463
  //#region src/probe-module.ts
@@ -768,6 +862,29 @@ async function discoverSchema(opts) {
768
862
  };
769
863
  }
770
864
  //#endregion
865
+ //#region src/engine-check.ts
866
+ const MAJOR = /^v?(\d+)/;
867
+ const FIRST_NUMBER = /(\d+)/;
868
+ function currentMajor(version) {
869
+ const match = MAJOR.exec(version);
870
+ return match ? Number(match[1]) : null;
871
+ }
872
+ function requiredMajor(range) {
873
+ if (!range) return null;
874
+ const match = FIRST_NUMBER.exec(range);
875
+ return match ? Number(match[1]) : null;
876
+ }
877
+ function engineError(currentVersion, enginesRange) {
878
+ const have = currentMajor(currentVersion);
879
+ const need = requiredMajor(enginesRange);
880
+ if (have === null || need === null || have >= need) return null;
881
+ return `Clivly requires Node.js ${need} or newer. You are running ${currentVersion}.
882
+
883
+ Upgrade with \`nvm install ${need}\` (or your version manager of choice), then re-run.
884
+ Set CLIVLY_SKIP_ENGINE_CHECK=1 to run anyway — expect unrelated-looking failures.
885
+ `;
886
+ }
887
+ //#endregion
771
888
  //#region src/env-file.ts
772
889
  const REGEX_METACHARACTERS = /[.*+?^${}()|[\]\\]/g;
773
890
  function escapeForRegExp(key) {
@@ -852,6 +969,123 @@ function upsertEnvValues(existing, entries, options = {}) {
852
969
  };
853
970
  }
854
971
  //#endregion
972
+ //#region src/help.ts
973
+ const ROOT_HELP = `clivly — embed a CRM in your app
974
+
975
+ Usage:
976
+ clivly init [options] Scaffold Clivly (config, routes, env file) for your app
977
+ clivly add widget [options] Scaffold the chat-session route
978
+ clivly status [options] Check your setup, step by step
979
+ clivly push-schema [options] Report your schema to Clivly without deploying
980
+ clivly dev [options] Tunnel localhost so remote sync can reach you
981
+ clivly login [options] Pair this machine and write credentials to your env file
982
+ clivly --version Print the installed clivly version
983
+
984
+ Deprecated aliases — each runs part of \`clivly status\` and still works:
985
+ clivly ping credential + reachability
986
+ clivly connect the above, plus config and trigger URL
987
+ clivly doctor config, setup checks and edge safety
988
+
989
+ Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
990
+ are on. The aliases are kept because output and docs have recommended them.
991
+
992
+ Run \`clivly <command> --help\` for details on a command.
993
+ `;
994
+ const COMMAND_HELP = {
995
+ init: `clivly init — scaffold Clivly into this app
996
+
997
+ Usage:
998
+ clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
999
+ [--schema <path|package>] [--db-import <specifier>]
1000
+ [--auth-import <specifier>] [--contact-table <table>]
1001
+ [--company-table <table>]
1002
+
1003
+ Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
1004
+ Detects your framework, ORM, auth adapter and app layout from the project.
1005
+
1006
+ Options:
1007
+ --dry-run Show what would be written; write nothing
1008
+ --diff Show a diff for files that already exist
1009
+ --force Overwrite files Clivly owns
1010
+ --yes Skip prompts
1011
+ --no-login Skip browser pairing
1012
+ --schema <p> Path or package holding your ORM schema
1013
+ --db-import <s> Module specifier exporting your database instance
1014
+ --auth-import <s> Module specifier exporting your auth instance
1015
+ --contact-table <t> Table to map as contacts
1016
+ --company-table <t> Table to map as companies
1017
+ `,
1018
+ add: `clivly add widget — scaffold the chat-session route
1019
+
1020
+ Usage:
1021
+ clivly add widget [--force] [--dry-run]
1022
+
1023
+ Writes the route that mints chat-widget sessions. Creates no widget record —
1024
+ that lives in the Clivly dashboard.
1025
+
1026
+ Options:
1027
+ --dry-run Show what would be written; write nothing
1028
+ --force Overwrite the route if it already exists
1029
+ `,
1030
+ status: `clivly status — check your setup, step by step
1031
+
1032
+ Usage:
1033
+ clivly status [--verbose] [--config <path>] [--env-file <path>]
1034
+
1035
+ Runs the setup ladder: credential, reachability, config load, edge-safety,
1036
+ setup checks, sync trigger. Read-only — writes nothing.
1037
+
1038
+ Options:
1039
+ --verbose Show every check, including those that passed
1040
+ --config <path> Path to clivly.config.ts
1041
+ --env-file <path> Extra env file to load
1042
+ `,
1043
+ "push-schema": `clivly push-schema — report your schema without deploying
1044
+
1045
+ Usage:
1046
+ clivly push-schema [--config <path>]
1047
+
1048
+ Sends your discovered tables to Clivly so the dashboard can offer them for
1049
+ mapping. Reads your config; writes nothing locally.
1050
+ `,
1051
+ dev: `clivly dev — tunnel localhost so remote sync can reach you
1052
+
1053
+ Usage:
1054
+ clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>]
1055
+
1056
+ Opens a tunnel to your local app and points Clivly's sync trigger at it.
1057
+ Everything after \`--\` runs as your app's dev command.
1058
+
1059
+ Options:
1060
+ --port <n> Local port your app listens on
1061
+ --route-path <path> Path to your mounted tick route
1062
+ `,
1063
+ login: `clivly login — pair this machine with Clivly
1064
+
1065
+ Usage:
1066
+ clivly login [--force] [--rotate] [--api-url <url>] [--no-browser]
1067
+
1068
+ Opens a browser to approve this machine, then writes CLIVLY_SECRET_KEY and
1069
+ CLIVLY_SYNC_TRIGGER_SECRET to .env.
1070
+
1071
+ Options:
1072
+ --force Re-pair even if credentials already exist
1073
+ --rotate Replace the existing credentials
1074
+ --no-browser Print the URL instead of opening a browser
1075
+ `
1076
+ };
1077
+ function isHelpRequest(argv) {
1078
+ for (const arg of argv) {
1079
+ if (arg === "--") return false;
1080
+ if (arg === "--help" || arg === "-h") return true;
1081
+ }
1082
+ return false;
1083
+ }
1084
+ function helpFor(command) {
1085
+ if (!command) return ROOT_HELP;
1086
+ return COMMAND_HELP[command] ?? ROOT_HELP;
1087
+ }
1088
+ //#endregion
855
1089
  //#region src/install.ts
856
1090
  const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
857
1091
  const child = (0, node_child_process.spawn)(command, args, {
@@ -1091,11 +1325,11 @@ function credentialEntries(credentials) {
1091
1325
  return [{
1092
1326
  key: SECRET_KEY_ENV,
1093
1327
  value: credentials.apiKey,
1094
- comment: "Org secret key — Settings → API keys"
1328
+ comment: `Org secret key — ${CREDENTIALS_LOCATION}`
1095
1329
  }, {
1096
1330
  key: "CLIVLY_SYNC_TRIGGER_SECRET",
1097
1331
  value: credentials.triggerSecret,
1098
- comment: "Signing secret — Integrations → Remote sync"
1332
+ comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
1099
1333
  }];
1100
1334
  }
1101
1335
  function writeCredentials(options, credentials) {
@@ -1182,12 +1416,19 @@ function chooseSyncFields(table, todos) {
1182
1416
  idField
1183
1417
  };
1184
1418
  }
1419
+ const SPLIT_NAME_COLUMNS = /* @__PURE__ */ new Set([
1420
+ "first_name",
1421
+ "firstname",
1422
+ "given_name"
1423
+ ]);
1185
1424
  function buildEntity(table, concept, todos) {
1186
1425
  const canonical = require_entity_config.CANONICAL_FIELDS[concept];
1187
1426
  const suggested = require_internal_entity_heuristics.toFieldMap(require_internal_entity_heuristics.scoreFieldMap(concept, toScoredTable(table)));
1188
1427
  const fields = {};
1189
1428
  for (const [key, column] of Object.entries(suggested)) if (canonical.includes(key)) fields[key] = column;
1190
1429
  for (const required of require_internal_entity_heuristics.requiredFieldsFor(concept)) if (!fields[required]) todos.push(`Could not map required ${concept} field "${required}" on "${table.tableName}" — add it manually.`);
1430
+ const nameColumn = fields.name?.toLowerCase();
1431
+ if (nameColumn && SPLIT_NAME_COLUMNS.has(nameColumn)) todos.push(`Mapped ${concept} "name" to "${fields.name}" on "${table.tableName}" — that is the given name only. Clivly mirrors one column per field, so add a full-name column if you want surnames.`);
1191
1432
  const { cursorField, idField } = chooseSyncFields(table, todos);
1192
1433
  return {
1193
1434
  moduleKey: table.moduleKey,
@@ -1258,15 +1499,99 @@ function planInit(schema, overrides = {}) {
1258
1499
  contact,
1259
1500
  company,
1260
1501
  tableNames: schema.tables.map((table) => table.tableName),
1502
+ contactCandidates: rankContactCandidates(schema.tables),
1261
1503
  todos
1262
1504
  };
1263
1505
  }
1506
+ const CONTACT_COLUMN_EVIDENCE = [
1507
+ {
1508
+ label: "email",
1509
+ names: ["email", "email_address"],
1510
+ weight: 3
1511
+ },
1512
+ {
1513
+ label: "phone",
1514
+ names: [
1515
+ "phone",
1516
+ "phone_number",
1517
+ "mobile"
1518
+ ],
1519
+ weight: 2
1520
+ },
1521
+ {
1522
+ label: "first name",
1523
+ names: [
1524
+ "first_name",
1525
+ "firstname",
1526
+ "given_name"
1527
+ ],
1528
+ weight: 2
1529
+ },
1530
+ {
1531
+ label: "last name",
1532
+ names: [
1533
+ "last_name",
1534
+ "lastname",
1535
+ "surname",
1536
+ "family_name"
1537
+ ],
1538
+ weight: 2
1539
+ },
1540
+ {
1541
+ label: "name",
1542
+ names: [
1543
+ "name",
1544
+ "full_name",
1545
+ "display_name"
1546
+ ],
1547
+ weight: 1
1548
+ }
1549
+ ];
1550
+ const NAME_MATCH_WEIGHT = 4;
1551
+ /**
1552
+ * Rank the schema's tables by how much they look like people, best first.
1553
+ *
1554
+ * Used only on the failure path, where detection found nothing mappable and the
1555
+ * developer has to choose. `init` previously suggested `tableNames[0]` — the
1556
+ * first table in schema order — so a rental app was told to map its `lease`
1557
+ * table as contacts. Wrong guidance is worse than none: it is confident, and
1558
+ * the developer has no way to see it is wrong.
1559
+ *
1560
+ * Deliberately evidence-based rather than name-based alone, so a table whose
1561
+ * name Clivly has never heard of still surfaces on the strength of its columns.
1562
+ */
1563
+ function rankContactCandidates(tables) {
1564
+ return tables.map((table) => {
1565
+ const columns = new Set(table.columns.flatMap((c) => [c.dbName.toLowerCase(), c.key.toLowerCase()]));
1566
+ const reasons = [];
1567
+ let score = 0;
1568
+ if (require_internal_entity_heuristics.matchesConcept(table.tableName, "contact")) {
1569
+ score += NAME_MATCH_WEIGHT;
1570
+ reasons.push("the name looks like a people table");
1571
+ }
1572
+ for (const evidence of CONTACT_COLUMN_EVIDENCE) {
1573
+ const hit = evidence.names.find((name) => columns.has(name));
1574
+ if (hit) {
1575
+ score += evidence.weight;
1576
+ reasons.push(hit);
1577
+ }
1578
+ }
1579
+ return {
1580
+ reasons,
1581
+ score,
1582
+ table: table.tableName
1583
+ };
1584
+ }).filter((candidate) => candidate.score > 0).sort((a, b) => b.score - a.score || a.table.localeCompare(b.table)).map(({ reasons, table }) => ({
1585
+ reasons,
1586
+ table
1587
+ }));
1588
+ }
1264
1589
  //#endregion
1265
1590
  //#region src/render-config.ts
1266
1591
  const CLIVLY_ENV_KEYS = [
1267
1592
  {
1268
1593
  key: "CLIVLY_SECRET_KEY",
1269
- comment: "Org secret key — Settings → API keys"
1594
+ comment: `Org secret key — ${CREDENTIALS_LOCATION}`
1270
1595
  },
1271
1596
  {
1272
1597
  key: "CLIVLY_SYNC_TRIGGER_URL",
@@ -1274,7 +1599,7 @@ const CLIVLY_ENV_KEYS = [
1274
1599
  },
1275
1600
  {
1276
1601
  key: "CLIVLY_SYNC_TRIGGER_SECRET",
1277
- comment: "Signing secret — Integrations → Remote sync"
1602
+ comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
1278
1603
  }
1279
1604
  ];
1280
1605
  function renderFields(fields) {
@@ -1303,6 +1628,28 @@ function renderDbExpr(plan) {
1303
1628
  if (!plan.db) return "db";
1304
1629
  return dbIsInSchemaModule(plan) ? `schema.${plan.db.moduleKey}` : plan.db.moduleKey;
1305
1630
  }
1631
+ const TRAILING_SCHEMA_SEGMENT = /\/schema(\/index)?$/;
1632
+ /**
1633
+ * Where the `db` instance most likely lives, given where the schema was found.
1634
+ *
1635
+ * Only reached when discovery could not confirm one. Discovery *evaluates* a
1636
+ * candidate module and duck-types its exports for `.select`, which is the right
1637
+ * check but fails for the most common real-world db module: `drizzle(process.
1638
+ * env.DATABASE_URL!)` throws at import time when the env var is absent, and it
1639
+ * is absent precisely when a developer is running `clivly init` for the first
1640
+ * time. So the probe misses, through no fault of the project.
1641
+ *
1642
+ * The old fallback emitted `<YOUR_DB_MODULE>` — not a module specifier, not
1643
+ * valid TypeScript, and invisible until the config failed to load at runtime.
1644
+ * A best-guess relative path is strictly better: right for the conventional
1645
+ * layout (`lib/db/schema.ts` beside `lib/db/index.ts`), and when it is wrong it
1646
+ * is a module-not-found error at build time, naming a real path the developer
1647
+ * can correct.
1648
+ */
1649
+ function guessDbImportPath(schemaImportPath) {
1650
+ const trimmed = schemaImportPath.replace(TRAILING_SCHEMA_SEGMENT, "");
1651
+ return trimmed === schemaImportPath || trimmed === "." || trimmed === "" ? "./db" : trimmed;
1652
+ }
1306
1653
  function renderImports(plan) {
1307
1654
  const lines = [
1308
1655
  "import { createClivlySDK, defineClivlyConfig } from \"clivly/sdk\";",
@@ -1310,8 +1657,10 @@ function renderImports(plan) {
1310
1657
  "import { discoverFromDrizzle } from \"clivly/drizzle\";",
1311
1658
  `import * as schema from "${plan.importPath}";`
1312
1659
  ];
1313
- if (!plan.db) lines.push("import { db } from \"<YOUR_DB_MODULE>\"; // TODO(clivly): replace with the path to your Drizzle `db` instance — NOT your schema file");
1314
- else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
1660
+ if (plan.db === null) {
1661
+ const guess = guessDbImportPath(plan.importPath);
1662
+ lines.push(`import { db } from "${guess}"; // TODO(clivly): verify this path points at your Drizzle \`db\` instance — NOT your schema file`);
1663
+ } else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
1315
1664
  return lines.join("\n");
1316
1665
  }
1317
1666
  function renderTodoHeader(todos) {
@@ -1429,6 +1778,83 @@ function renderAuthWiring(auth, authInstance = null) {
1429
1778
  }
1430
1779
  }
1431
1780
  //#endregion
1781
+ //#region src/tsconfig-alias.ts
1782
+ const LEADING_DOT_SLASH$1 = /^\.\//;
1783
+ const TRAILING_WILDCARD = /\/?\*$/;
1784
+ const TRAILING_SLASH = /\/$/;
1785
+ const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
1786
+ const LINE_COMMENT = /(^|[^:])\/\/.*$/gm;
1787
+ const TRAILING_COMMA = /,(\s*[}\]])/g;
1788
+ /**
1789
+ * `compilerOptions` from a tsconfig's text, or null when it cannot be read.
1790
+ *
1791
+ * tsconfig is JSONC — comments and trailing commas are legal and common, and
1792
+ * `JSON.parse` rejects both. Stripping them is enough here: this only ever reads
1793
+ * two string-valued fields, so the cost of being wrong is falling back to a
1794
+ * relative import, which already works.
1795
+ */
1796
+ function parseTsconfig(source) {
1797
+ try {
1798
+ const stripped = source.replace(BLOCK_COMMENT, "").replace(LINE_COMMENT, "$1").replace(TRAILING_COMMA, "$1");
1799
+ return JSON.parse(stripped).compilerOptions ?? null;
1800
+ } catch {
1801
+ return null;
1802
+ }
1803
+ }
1804
+ /**
1805
+ * Strip a leading "./" and any trailing wildcard so two paths can be compared.
1806
+ *
1807
+ * `"./*"` — an alias rooted at the app itself — must reduce to the empty string,
1808
+ * not to a stray `"*"`; that is the mapping which makes a root-level
1809
+ * clivly.config alias-reachable.
1810
+ */
1811
+ function normalize(value) {
1812
+ return value.replace(LEADING_DOT_SLASH$1, "").replace(TRAILING_WILDCARD, "").replace(TRAILING_SLASH, "");
1813
+ }
1814
+ /**
1815
+ * The alias specifier that reaches `target`, or null when none does.
1816
+ *
1817
+ * `target` is app-root-relative and extensionless, e.g. `lib/auth` or
1818
+ * `clivly.config`. Only wildcard patterns are considered — an exact mapping
1819
+ * names one module and is not a prefix anything else can be rebased onto.
1820
+ *
1821
+ * Longest prefix wins, so `"@components/*": ["./src/components/*"]` beats
1822
+ * `"@/*": ["./src/*"]` for a module under `src/components`, matching how
1823
+ * TypeScript itself resolves.
1824
+ */
1825
+ function aliasFor(input) {
1826
+ if (!input.paths) return null;
1827
+ const target = normalize(input.target);
1828
+ let best = null;
1829
+ for (const [pattern, targets] of Object.entries(input.paths)) {
1830
+ if (!pattern.endsWith("/*")) continue;
1831
+ const prefix = pattern.slice(0, -2);
1832
+ for (const mapped of targets) {
1833
+ const base = baseReaching(mapped, target);
1834
+ if (base === null) continue;
1835
+ const rest = base === "" ? target : target.slice(base.length + 1);
1836
+ if (!best || base.length > best.length) best = {
1837
+ alias: `${prefix}/${rest}`,
1838
+ length: base.length
1839
+ };
1840
+ }
1841
+ }
1842
+ return best?.alias ?? null;
1843
+ }
1844
+ /**
1845
+ * The normalized base of `mapped` when it contains `target`, else null.
1846
+ *
1847
+ * A prefix must end at a segment boundary — `src` must not match `srcinternal`,
1848
+ * a different directory — and the target must be strictly inside the base, since
1849
+ * a wildcard needs a remainder to substitute.
1850
+ */
1851
+ function baseReaching(mapped, target) {
1852
+ if (!mapped.endsWith("/*")) return null;
1853
+ const base = normalize(mapped);
1854
+ if (base === "") return target === "" ? null : "";
1855
+ return target.startsWith(`${base}/`) ? base : null;
1856
+ }
1857
+ //#endregion
1432
1858
  //#region src/scaffold.ts
1433
1859
  const TANSTACK_ROUTE_PREFIX = /^src\/routes\//;
1434
1860
  const TS_EXTENSION = /\.ts$/;
@@ -1460,10 +1886,14 @@ const ROUTE_PATHS = {
1460
1886
  },
1461
1887
  unknown: null
1462
1888
  };
1463
- function routePath(framework, kind) {
1889
+ function applyLayout(framework, path, layout) {
1890
+ if (framework !== "nextjs" || layout === "app") return path;
1891
+ return `src/${path}`;
1892
+ }
1893
+ function routePath(framework, kind, layout = "app") {
1464
1894
  const paths = ROUTE_PATHS[framework];
1465
1895
  if (!paths) throw new Error(`No route path for framework: ${framework}`);
1466
- return paths[kind];
1896
+ return applyLayout(framework, paths[kind], layout);
1467
1897
  }
1468
1898
  const WINDOWS_SEP = /\\/g;
1469
1899
  const LEADING_DOT_SLASH = /^\.\//;
@@ -1471,22 +1901,27 @@ function configImport(routeFilePath) {
1471
1901
  const rel = (0, node_path.relative)((0, node_path.dirname)(routeFilePath), "clivly.config").replace(WINDOWS_SEP, "/");
1472
1902
  return rel.startsWith(".") ? rel : `./${rel}`;
1473
1903
  }
1474
- function hostImportPath(routeFilePath, appRelative) {
1904
+ function hostImportPath(routeFilePath, appRelative, paths) {
1475
1905
  const fromRoot = appRelative.replace(LEADING_DOT_SLASH, "");
1906
+ const alias = aliasFor({
1907
+ paths,
1908
+ target: fromRoot
1909
+ });
1910
+ if (alias) return alias;
1476
1911
  const rel = (0, node_path.relative)((0, node_path.dirname)(routeFilePath), fromRoot).replace(WINDOWS_SEP, "/");
1477
1912
  return rel.startsWith(".") ? rel : `./${rel}`;
1478
1913
  }
1479
- function renderAuthPreamble(routeFilePath, auth) {
1914
+ function renderAuthPreamble(routeFilePath, auth, paths) {
1480
1915
  const lines = [...auth.imports];
1481
1916
  if (auth.hostImport) {
1482
1917
  if (auth.hostImport.todo) lines.push(`// ${auth.hostImport.todo}`);
1483
- const path = hostImportPath(routeFilePath, auth.hostImport.path);
1918
+ const path = hostImportPath(routeFilePath, auth.hostImport.path, paths);
1484
1919
  lines.push(`import { ${auth.hostImport.binding} } from "${path}";`);
1485
1920
  }
1486
1921
  lines.push("", auth.body);
1487
1922
  return lines.join("\n");
1488
1923
  }
1489
- function renderPreamble(kind, importPath, auth, routeFilePath) {
1924
+ function renderPreamble(kind, importPath, auth, paths, routeFilePath) {
1490
1925
  if (kind === "session") return `import { createChatSessionHandler } from "clivly/sdk";
1491
1926
 
1492
1927
  const handler = createChatSessionHandler({
@@ -1497,7 +1932,7 @@ const handler = createChatSessionHandler({
1497
1932
  });
1498
1933
  `;
1499
1934
  if (kind === "verify") return `import clivly from "${importPath}";
1500
- ${renderAuthPreamble(routeFilePath, auth)}
1935
+ ${renderAuthPreamble(routeFilePath, auth, paths)}
1501
1936
  const handler = clivly.createAuthVerifyHandler(resolveUser);
1502
1937
  `;
1503
1938
  return `import clivly from "${importPath}";
@@ -1505,8 +1940,8 @@ const handler = clivly.createAuthVerifyHandler(resolveUser);
1505
1940
  const handler = clivly.createClivlyHandler();
1506
1941
  `;
1507
1942
  }
1508
- function renderBody(framework, importPath, kind, auth, routeFilePath) {
1509
- const preamble = renderPreamble(kind, importPath, auth, routeFilePath);
1943
+ function renderBody(framework, importPath, kind, auth, routeFilePath, paths) {
1944
+ const preamble = renderPreamble(kind, importPath, auth, paths, routeFilePath);
1510
1945
  switch (framework) {
1511
1946
  case "nextjs": return `${preamble}
1512
1947
  export const POST = (request: Request) => handler(request);
@@ -1536,9 +1971,9 @@ export default defineEventHandler((event) => handler(toWebRequest(event)));
1536
1971
  default: throw new Error(`No route template for framework: ${framework}`);
1537
1972
  }
1538
1973
  }
1539
- function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown")) {
1540
- const path = routePath(framework, kind);
1541
- let body = renderBody(framework, configImport(path), kind, auth, path);
1974
+ function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown"), layout = "app", paths) {
1975
+ const path = routePath(framework, kind, layout);
1976
+ let body = renderBody(framework, configImport(path), kind, auth, path, paths);
1542
1977
  if (framework === "tanstack-start") {
1543
1978
  const url = `/${path.replace(TANSTACK_ROUTE_PREFIX, "").replace(TS_EXTENSION, "")}`;
1544
1979
  body = body.replace("__ROUTE__", url);
@@ -1550,28 +1985,28 @@ const COMMON_FILES = [{
1550
1985
  description: "Your Clivly configuration",
1551
1986
  owned: false
1552
1987
  }];
1553
- function planScaffold(framework) {
1988
+ function planScaffold(framework, layout = "app") {
1554
1989
  const paths = ROUTE_PATHS[framework];
1555
1990
  if (!paths) return [];
1556
1991
  return [
1557
1992
  {
1558
- path: paths.tick,
1993
+ path: applyLayout(framework, paths.tick, layout),
1559
1994
  description: "Clivly sync-trigger route (createClivlyHandler)",
1560
1995
  owned: true
1561
1996
  },
1562
1997
  {
1563
- path: paths.verify,
1998
+ path: applyLayout(framework, paths.verify, layout),
1564
1999
  description: "Clivly auth-verify route (createAuthVerifyHandler) — finish resolveUser",
1565
2000
  owned: true
1566
2001
  },
1567
2002
  ...COMMON_FILES
1568
2003
  ];
1569
2004
  }
1570
- function planWidgetScaffold(framework) {
2005
+ function planWidgetScaffold(framework, layout = "app") {
1571
2006
  const paths = ROUTE_PATHS[framework];
1572
2007
  if (!paths) return [];
1573
2008
  return [{
1574
- path: paths.session,
2009
+ path: applyLayout(framework, paths.session, layout),
1575
2010
  description: "Clivly chat-session route (createChatSessionHandler) — add allowedOrigins",
1576
2011
  owned: true
1577
2012
  }];
@@ -1591,9 +2026,9 @@ function planFiles(args) {
1591
2026
  const render = (path) => {
1592
2027
  if (path === "clivly.config.ts") return renderInitConfig(args.plan);
1593
2028
  const kind = path.includes("verify") ? "verify" : "tick";
1594
- return renderRouteFile(args.framework, kind, args.authWiring);
2029
+ return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile((0, node_path.join)(args.cwd, "tsconfig.json")) ?? "")?.paths);
1595
2030
  };
1596
- for (const file of planScaffold(args.framework)) {
2031
+ for (const file of planScaffold(args.framework, args.layout)) {
1597
2032
  const contents = render(file.path);
1598
2033
  mutations.push({
1599
2034
  path: file.path,
@@ -1624,8 +2059,8 @@ function planMutations(args) {
1624
2059
  };
1625
2060
  }
1626
2061
  function planWidgetMutations(args) {
1627
- return planWidgetScaffold(args.framework).map((file) => {
1628
- const contents = renderRouteFile(args.framework, "session");
2062
+ return planWidgetScaffold(args.framework, args.layout).map((file) => {
2063
+ const contents = renderRouteFile(args.framework, "session", void 0, args.layout);
1629
2064
  return {
1630
2065
  path: file.path,
1631
2066
  contents,
@@ -1950,7 +2385,17 @@ const ALLOWED_CALLS = /* @__PURE__ */ new Set([
1950
2385
  "while"
1951
2386
  ]);
1952
2387
  const SIDE_EFFECT_CALLS = /^(dotenv\.config|config|configDotenv|fileURLToPath|readFileSync|require|process\.chdir)$/;
2388
+ const NATIVE_PACKAGES = /* @__PURE__ */ new Set([
2389
+ "bcrypt",
2390
+ "better-sqlite3",
2391
+ "canvas",
2392
+ "node-gyp",
2393
+ "pg-native",
2394
+ "sharp",
2395
+ "sqlite3"
2396
+ ]);
1953
2397
  const ENV_HINT = "Move it to clivly.cli.ts (`envFiles`) or pass --env-file — the CLI reads those in Node, so your config stays edge-safe.";
2398
+ const NATIVE_HINT = "A compiled binary cannot load on an edge runtime — this is the \"Could not locate the bindings file\" / ERR_DLOPEN_FAILED failure. Import your db lazily inside a function, or use a driver that speaks HTTP (e.g. @neondatabase/serverless) in the config.";
1954
2399
  function isNodeBuiltin(specifier) {
1955
2400
  if (specifier.startsWith("node:")) return true;
1956
2401
  return NODE_BUILTINS.has(specifier.split("/")[0] ?? "");
@@ -1967,6 +2412,12 @@ function specifierIssue(specifier, line) {
1967
2412
  hint: ENV_HINT,
1968
2413
  line
1969
2414
  };
2415
+ if (NATIVE_PACKAGES.has(specifier.split("/")[0] ?? "")) return {
2416
+ code: "native_module_in_edge_config",
2417
+ detail: `imports "${specifier}", which ships a compiled binary`,
2418
+ hint: NATIVE_HINT,
2419
+ line
2420
+ };
1970
2421
  if (isNodeBuiltin(specifier)) return {
1971
2422
  code: "node_builtin_in_edge_config",
1972
2423
  detail: `imports "${specifier}", which does not exist on an edge runtime`,
@@ -2006,8 +2457,56 @@ function analyzeEdgeSafety(source) {
2006
2457
  });
2007
2458
  return issues;
2008
2459
  }
2460
+ /** Every relative specifier `source` imports, in first-seen order, deduped. */
2461
+ function relativeImports(source) {
2462
+ const seen = /* @__PURE__ */ new Set();
2463
+ for (const rawLine of source.split(NEWLINE)) {
2464
+ const line = stripComment(rawLine);
2465
+ const specifier = BARE_IMPORT.exec(line)?.[1] ?? IMPORT_FROM.exec(line)?.[1] ?? REQUIRE_CALL.exec(line)?.[1];
2466
+ if (specifier?.startsWith(".")) seen.add(specifier);
2467
+ }
2468
+ return [...seen];
2469
+ }
2470
+ /**
2471
+ * Edge-safety for the config *and* the modules it imports directly.
2472
+ *
2473
+ * The dominant real-world shape is a clean-looking config with
2474
+ * `import { db } from "./lib/db"`, where the problem is one hop away and
2475
+ * invisible to a scan that reads only the config file.
2476
+ *
2477
+ * One hop, not more: each additional level multiplies the files read for a
2478
+ * shrinking return, and the config's own imports are where a host app puts its
2479
+ * database. Bare specifiers are never followed — resolving into node_modules is
2480
+ * a different job with different failure modes, and the denylist already covers
2481
+ * the packages that matter.
2482
+ *
2483
+ * `readModule` returns source text, or null when the module cannot be read;
2484
+ * unreadable is not a finding, since a scan is not a build.
2485
+ */
2486
+ function analyzeConfigTree(input) {
2487
+ const issues = analyzeEdgeSafety(input.source);
2488
+ for (const specifier of relativeImports(input.source)) {
2489
+ const source = input.readModule(specifier);
2490
+ if (source === null) continue;
2491
+ for (const issue of analyzeEdgeSafety(source)) issues.push({
2492
+ ...issue,
2493
+ module: specifier
2494
+ });
2495
+ }
2496
+ return issues;
2497
+ }
2009
2498
  //#endregion
2010
2499
  //#region src/status-stages.ts
2500
+ const MODULE_CANDIDATES = [
2501
+ ".ts",
2502
+ ".tsx",
2503
+ ".js",
2504
+ ".mjs",
2505
+ ".cjs",
2506
+ "/index.ts",
2507
+ "/index.js",
2508
+ ""
2509
+ ];
2011
2510
  function defaultReadConfigSource(path) {
2012
2511
  try {
2013
2512
  return (0, node_fs.readFileSync)(path, "utf8");
@@ -2022,10 +2521,11 @@ const REASON_HINT = {
2022
2521
  rate_limited: "Rate limited (429). Wait a moment and retry.",
2023
2522
  server_error: "Clivly returned a server error (5xx). Retry shortly.",
2024
2523
  client_error: "The request was rejected (4xx). Check your configuration.",
2524
+ server_too_old: "This Clivly server is older than your CLI and has no /clivly/sdk/ping. Upgrade the server, or pin the CLI to match it.",
2025
2525
  network_error: "Could not reach Clivly. Check your network or --api-url."
2026
2526
  };
2027
2527
  const apiKeyStage = {
2028
- id: "api-key",
2528
+ id: "credential",
2029
2529
  label: "API key present",
2030
2530
  run(ctx) {
2031
2531
  if (ctx.apiKey) return Promise.resolve({
@@ -2035,20 +2535,29 @@ const apiKeyStage = {
2035
2535
  return Promise.resolve({
2036
2536
  state: "fail",
2037
2537
  detail: "Secret key is not set.",
2038
- hint: "Copy your secret key from Settings → API keys into CLIVLY_SECRET_KEY in .env."
2538
+ hint: `Copy your secret key from ${CREDENTIALS_LOCATION} into CLIVLY_SECRET_KEY in .env.`
2039
2539
  });
2040
2540
  }
2041
2541
  };
2042
- const heartbeatStage = {
2043
- id: "heartbeat",
2542
+ const reachabilityStage = {
2543
+ id: "application",
2044
2544
  label: "Clivly reachable",
2045
2545
  needs: [apiKeyStage.id],
2046
2546
  async run(ctx) {
2047
2547
  const result = await ctx.connect(ctx.apiKey, ctx.apiUrl);
2048
- if (result.ok) return {
2049
- state: "pass",
2050
- detail: `Reached org: ${result.org?.name ?? "(unnamed org)"}${result.org?.id ? ` (${result.org.id})` : ""}`
2051
- };
2548
+ if (result.ok) {
2549
+ const name = result.org?.name ?? "(unnamed org)";
2550
+ const id = result.org?.id ? ` (${result.org.id})` : "";
2551
+ if (result.appLastSeenAt === null) return {
2552
+ state: "warn",
2553
+ detail: `Reached org: ${name}${id} — your app has not connected yet`,
2554
+ hint: "Start your app with the Clivly SDK mounted; it will appear in the dashboard within a minute."
2555
+ };
2556
+ return {
2557
+ state: "pass",
2558
+ detail: `Reached org: ${name}${id}`
2559
+ };
2560
+ }
2052
2561
  const status = result.status === null ? "no response" : `HTTP ${result.status}`;
2053
2562
  return {
2054
2563
  state: "fail",
@@ -2076,22 +2585,76 @@ const configStage = {
2076
2585
  }
2077
2586
  }
2078
2587
  };
2079
- const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Heartbeat"]);
2588
+ const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Clivly reachable"]);
2589
+ const sdkChecksStage = {
2590
+ id: "setup-checks",
2591
+ label: "Setup checks",
2592
+ needs: [configStage.id],
2593
+ async run(ctx) {
2594
+ const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
2595
+ const counted = owned.filter((check) => !check.skipped);
2596
+ const passed = counted.filter((check) => check.ok).length;
2597
+ const ok = counted.every((check) => check.ok);
2598
+ const warned = counted.filter((check) => check.warn).length;
2599
+ const summary = warned > 0 ? `${passed} of ${counted.length} passed, ${warned} with warnings` : `${passed} of ${counted.length} passed`;
2600
+ return {
2601
+ state: ok ? "pass" : "fail",
2602
+ detail: summary,
2603
+ sub: owned.map((check) => ({
2604
+ label: check.name,
2605
+ ok: check.ok,
2606
+ skipped: check.skipped,
2607
+ warn: check.warn,
2608
+ detail: check.detail
2609
+ }))
2610
+ };
2611
+ }
2612
+ };
2613
+ const triggerUrlStage = {
2614
+ id: "trigger-url",
2615
+ label: "Sync trigger URL",
2616
+ needs: [configStage.id],
2617
+ run(ctx) {
2618
+ const url = ctx.sdk?.syncTrigger?.url;
2619
+ if (url) return Promise.resolve({
2620
+ state: "pass",
2621
+ detail: url
2622
+ });
2623
+ return Promise.resolve({
2624
+ state: "warn",
2625
+ detail: "Not set — remote sync cannot call back into this app.",
2626
+ hint: "Set CLIVLY_SYNC_TRIGGER_URL once the app is deployed. For local development run `clivly dev` — it opens a tunnel and registers the URL for you. Push-only setups can ignore this."
2627
+ });
2628
+ }
2629
+ };
2080
2630
  /** The full ladder, in the order a developer completes setup. */
2081
2631
  const STATUS_STAGES = [
2082
2632
  apiKeyStage,
2083
- heartbeatStage,
2633
+ reachabilityStage,
2084
2634
  configStage,
2085
2635
  {
2086
2636
  id: "runtime",
2087
2637
  label: "clivly.config is edge-safe",
2638
+ needs: [configStage.id],
2088
2639
  run(ctx) {
2089
2640
  const source = (ctx.readConfigSource ?? defaultReadConfigSource)(ctx.configPath);
2090
2641
  if (source === null) return Promise.resolve({
2091
2642
  state: "skip",
2092
2643
  detail: "config not readable"
2093
2644
  });
2094
- const issues = analyzeEdgeSafety(source);
2645
+ const read = ctx.readConfigSource ?? defaultReadConfigSource;
2646
+ const base = (0, node_path.dirname)(ctx.configPath);
2647
+ const issues = analyzeConfigTree({
2648
+ source,
2649
+ readModule: (specifier) => {
2650
+ const target = (0, node_path.resolve)(base, specifier);
2651
+ for (const candidate of MODULE_CANDIDATES) {
2652
+ const found = read(`${target}${candidate}`);
2653
+ if (found !== null) return found;
2654
+ }
2655
+ return null;
2656
+ }
2657
+ });
2095
2658
  if (issues.length === 0) return Promise.resolve({
2096
2659
  state: "pass",
2097
2660
  detail: "no Node-only code at module scope"
@@ -2108,43 +2671,8 @@ const STATUS_STAGES = [
2108
2671
  });
2109
2672
  }
2110
2673
  },
2111
- {
2112
- id: "setup-checks",
2113
- label: "Setup checks",
2114
- needs: [configStage.id],
2115
- async run(ctx) {
2116
- const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
2117
- const counted = owned.filter((check) => !check.skipped);
2118
- const passed = counted.filter((check) => check.ok).length;
2119
- return {
2120
- state: counted.every((check) => check.ok) ? "pass" : "fail",
2121
- detail: `${passed} of ${counted.length} passed`,
2122
- sub: owned.map((check) => ({
2123
- label: check.name,
2124
- ok: check.ok,
2125
- skipped: check.skipped,
2126
- detail: check.detail
2127
- }))
2128
- };
2129
- }
2130
- },
2131
- {
2132
- id: "trigger-url",
2133
- label: "Sync trigger URL",
2134
- needs: [configStage.id],
2135
- run(ctx) {
2136
- const url = ctx.sdk?.syncTrigger?.url;
2137
- if (url) return Promise.resolve({
2138
- state: "pass",
2139
- detail: url
2140
- });
2141
- return Promise.resolve({
2142
- state: "warn",
2143
- detail: "Not set — remote sync cannot call back into this app.",
2144
- hint: "Set CLIVLY_SYNC_TRIGGER_URL once the app is deployed. For local development run `clivly dev` — it opens a tunnel and registers the URL for you. Push-only setups can ignore this."
2145
- });
2146
- }
2147
- }
2674
+ sdkChecksStage,
2675
+ triggerUrlStage
2148
2676
  ];
2149
2677
  function defaultLoadSdk(path) {
2150
2678
  return loadConfigSdk(path, "doctor");
@@ -2154,15 +2682,15 @@ function defaultLoadSdk(path) {
2154
2682
  /** Stage ids each legacy command maps onto. */
2155
2683
  const ALIAS_STAGE_IDS = {
2156
2684
  status: STATUS_STAGES.map((stage) => stage.id),
2157
- ping: ["api-key", "heartbeat"],
2685
+ ping: ["credential", "application"],
2158
2686
  doctor: [
2159
2687
  "config",
2160
2688
  "runtime",
2161
2689
  "setup-checks"
2162
2690
  ],
2163
2691
  connect: [
2164
- "api-key",
2165
- "heartbeat",
2692
+ "credential",
2693
+ "application",
2166
2694
  "config",
2167
2695
  "trigger-url"
2168
2696
  ]
@@ -2178,9 +2706,9 @@ const defaultConnect = (apiKey, apiUrl) => require_sdk.createClivlySDK({
2178
2706
  apiKey,
2179
2707
  apiUrl,
2180
2708
  retry: { maxAttempts: 1 }
2181
- }).connect();
2709
+ }).ping();
2182
2710
  function subMark(sub) {
2183
- if (sub.skipped) return "⚠️ ";
2711
+ if (sub.skipped || sub.warn) return "⚠️ ";
2184
2712
  return sub.ok ? "✅" : "❌";
2185
2713
  }
2186
2714
  function renderStage(result, verbose, out) {
@@ -2188,7 +2716,7 @@ function renderStage(result, verbose, out) {
2188
2716
  const detail = result.detail ? ` — ${result.detail}` : "";
2189
2717
  out(` ${MARK[result.state]} ${step} · ${result.label}${detail}\n`);
2190
2718
  for (const sub of result.sub ?? []) {
2191
- if (!(verbose || sub.skipped || !sub.ok)) continue;
2719
+ if (!(verbose || sub.skipped || sub.warn || !sub.ok)) continue;
2192
2720
  const subDetail = sub.detail ? ` — ${sub.detail}` : "";
2193
2721
  out(` ${subMark(sub)} ${sub.label}${subDetail}\n`);
2194
2722
  }
@@ -2214,6 +2742,12 @@ async function runStatus(options) {
2214
2742
  }
2215
2743
  //#endregion
2216
2744
  //#region src/index.ts
2745
+ const ENV_FILE_CANDIDATES = [
2746
+ ".env",
2747
+ ".env.local",
2748
+ ".dev.vars"
2749
+ ];
2750
+ const CONFIG_WATCH_DEBOUNCE_MS = 150;
2217
2751
  function flagValue(argv, flag) {
2218
2752
  const index = argv.indexOf(flag);
2219
2753
  return index >= 0 ? argv[index + 1] : void 0;
@@ -2232,7 +2766,10 @@ const KNOWN_COMMANDS = [
2232
2766
  "push-schema",
2233
2767
  "dev",
2234
2768
  "login",
2235
- "help"
2769
+ "help",
2770
+ "ping",
2771
+ "doctor",
2772
+ "connect"
2236
2773
  ];
2237
2774
  function editDistance(a, b) {
2238
2775
  const m = a.length;
@@ -2275,6 +2812,7 @@ function readDeps(cwd) {
2275
2812
  }
2276
2813
  const ADD_USAGE = "Usage: clivly add widget [--force] [--dry-run]";
2277
2814
  const defaultAddDeps = {
2815
+ fileExists: node_fs.existsSync,
2278
2816
  out: (line) => process.stdout.write(line),
2279
2817
  readFile: (path) => (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : null,
2280
2818
  writeFile: (path, contents) => {
@@ -2294,14 +2832,21 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
2294
2832
  deps.out("Couldn't detect your framework from package.json. `clivly add widget` supports Next.js, TanStack Start, SvelteKit, Remix, and Nuxt.\n");
2295
2833
  return 1;
2296
2834
  }
2835
+ const layout = resolveAppLayout(cwd, deps.fileExists);
2297
2836
  const force = argv.includes("--force");
2298
2837
  const dryRun = argv.includes("--dry-run");
2299
2838
  const files = planWidgetMutations({
2300
2839
  framework,
2301
2840
  cwd,
2302
2841
  force,
2842
+ layout,
2303
2843
  readFile: (path) => deps.readFile(path)
2304
2844
  });
2845
+ const shadowing = shadowedAppDirError(cwd, framework, files.map((file) => file.path), deps.fileExists);
2846
+ if (shadowing) {
2847
+ deps.out(shadowing);
2848
+ return 1;
2849
+ }
2305
2850
  deps.out(`\nClivly add widget — ${FRAMEWORK_LABELS[framework]}\n\n`);
2306
2851
  if (dryRun) deps.out("Dry run — nothing was written.\n\n");
2307
2852
  for (const file of files) {
@@ -2322,7 +2867,7 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
2322
2867
  }
2323
2868
  if (!dryRun) {
2324
2869
  const sessionPath = files[0]?.path ?? "";
2325
- deps.out(`\nNext steps:\n 1. Add your site origins to allowedOrigins in ${sessionPath}\n 2. Create the widget + set allowed origins in the Clivly dashboard (Settings → Chat widget)\n 3. Embed it: <ClivlyChatWidget widgetId="…" />\n`);
2870
+ deps.out(`\nNext steps:\n 1. Add your site origins to allowedOrigins in ${sessionPath}\n 2. Create the widget + set allowed origins at ${WIDGET_LOCATION}\n 3. Embed it: <ClivlyChatWidget widgetId="…" />\n`);
2326
2871
  }
2327
2872
  return 0;
2328
2873
  }
@@ -2333,6 +2878,13 @@ function readOwnVersion() {
2333
2878
  if (pkg.name === "clivly" && pkg.version) return pkg.version;
2334
2879
  } catch {}
2335
2880
  }
2881
+ function readOwnEngines() {
2882
+ const req = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
2883
+ for (const rel of ["./package.json", "../package.json"]) try {
2884
+ const pkg = req(rel);
2885
+ if (pkg.name === "clivly") return pkg.engines?.node;
2886
+ } catch {}
2887
+ }
2336
2888
  /**
2337
2889
  * Parse a `--db-import` / `--auth-import` value into a discovery-shaped override.
2338
2890
  *
@@ -2362,12 +2914,24 @@ function authInstanceFromFlag(flag) {
2362
2914
  function defaultReadFile(path) {
2363
2915
  return (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : null;
2364
2916
  }
2917
+ function resolveEnvPath(cwd) {
2918
+ const framework = detectFramework(readDeps(cwd));
2919
+ return (0, node_path.join)(cwd, resolveEnvFile({
2920
+ existing: ENV_FILE_CANDIDATES.filter((name) => {
2921
+ const path = (0, node_path.join)(cwd, name);
2922
+ if (!(0, node_fs.existsSync)(path)) return false;
2923
+ const contents = (0, node_fs.readFileSync)(path, "utf8");
2924
+ return isKeySet(contents, "CLIVLY_SECRET_KEY") || isKeySet(contents, "CLIVLY_API_KEY");
2925
+ }),
2926
+ framework
2927
+ }));
2928
+ }
2365
2929
  function defaultReadEnv(cwd) {
2366
- const path = (0, node_path.join)(cwd, ".env");
2930
+ const path = resolveEnvPath(cwd);
2367
2931
  return (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : "";
2368
2932
  }
2369
2933
  function defaultWriteEnv(cwd, contents) {
2370
- (0, node_fs.writeFileSync)((0, node_path.join)(cwd, ".env"), contents, "utf8");
2934
+ (0, node_fs.writeFileSync)(resolveEnvPath(cwd), contents, "utf8");
2371
2935
  }
2372
2936
  function defaultIsInteractive() {
2373
2937
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) && !process.env.CI;
@@ -2394,6 +2958,8 @@ function resolveInitDeps(options) {
2394
2958
  graph: graphFor(cwd)
2395
2959
  })),
2396
2960
  readFile: options.readFile ?? defaultReadFile,
2961
+ fileExists: options.fileExists ?? node_fs.existsSync,
2962
+ resolveAppLayout: options.resolveAppLayout ?? resolveAppLayout,
2397
2963
  writeConfig: options.writeConfig ?? ((path, contents) => {
2398
2964
  (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
2399
2965
  (0, node_fs.writeFileSync)(path, contents, "utf8");
@@ -2414,6 +2980,7 @@ function resolveInitDeps(options) {
2414
2980
  rotate: false
2415
2981
  })),
2416
2982
  framework: "unknown",
2983
+ layout: "app",
2417
2984
  authWiring: renderAuthWiring("unknown")
2418
2985
  };
2419
2986
  }
@@ -2428,11 +2995,15 @@ async function acquireSchema(options, deps) {
2428
2995
  const orm = detectOrm(appDeps);
2429
2996
  const auth = detectAuth(appDeps);
2430
2997
  deps.framework = framework;
2998
+ const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
2999
+ deps.layout = layout;
2431
3000
  deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
2432
3001
  out("\nClivly init\n");
2433
3002
  out(` Framework: ${FRAMEWORK_LABELS[framework]}\n`);
2434
3003
  out(` ORM: ${orm}\n`);
2435
- out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n\n`);
3004
+ out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n`);
3005
+ if (framework === "nextjs") out(` Layout: ${layout}\n`);
3006
+ out("\n");
2436
3007
  if (orm !== "drizzle") {
2437
3008
  out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
2438
3009
  return { code: 1 };
@@ -2476,6 +3047,7 @@ function mutationsFor(options, deps, plan) {
2476
3047
  cwd: options.cwd,
2477
3048
  force: options.force,
2478
3049
  framework: deps.framework,
3050
+ layout: deps.layout,
2479
3051
  authWiring: deps.authWiring,
2480
3052
  plan,
2481
3053
  readFile: deps.readFile,
@@ -2535,14 +3107,15 @@ function previewMutations(deps, mutations, options) {
2535
3107
  }
2536
3108
  out(options.diff ? "\nRe-run without --diff to apply; --force to overwrite the files marked conflict.\n" : "\nRe-run without --dry-run to apply.\n");
2537
3109
  }
2538
- function printNextSteps(out, authComplete, loginRan) {
3110
+ function printNextSteps(out, authComplete, loginRan, envFile) {
2539
3111
  out("\nNext steps:\n");
2540
- out(loginRan ? " 1. Credentials written by `clivly login`\n" : " 1. Add CLIVLY_SECRET_KEY to .env — create one in the Clivly dashboard\n under Integrations → Create API Key (or Settings → API keys)\n (the legacy CLIVLY_API_KEY is still accepted)\n");
3112
+ out(loginRan ? " 1. Credentials written by `clivly login`\n" : ` 1. Add CLIVLY_SECRET_KEY to ${envFile} — create one at\n ${CREDENTIALS_LOCATION}\n (the legacy CLIVLY_API_KEY is still accepted)\n`);
2541
3113
  out(" 2. Set CLIVLY_SYNC_TRIGGER_URL to your public tick route\n");
2542
3114
  out(" Local dev? Run `clivly dev` to open a tunnel, or skip this step until you deploy (remote sync is deploy-only locally).\n");
2543
3115
  const step = authComplete ? 3 : 4;
2544
3116
  if (!authComplete) out(" 3. Finish resolveUser in the auth/verify route\n");
2545
3117
  out(` ${step}. Run \`clivly status\` to see where you are\n`);
3118
+ out("\nAfter editing clivly.config.ts, restart your app — it loads the config\nat boot, so a running server keeps using the old one.\n");
2546
3119
  }
2547
3120
  function credentialsMissing(envContents) {
2548
3121
  return !(isKeySet(envContents, "CLIVLY_SECRET_KEY") || isKeySet(envContents, "CLIVLY_API_KEY"));
@@ -2563,6 +3136,11 @@ async function scaffold(options, deps, plan) {
2563
3136
  const pm = deps.detectPackageManager(options.cwd);
2564
3137
  const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
2565
3138
  const mutations = mutationsFor(options, deps, plan);
3139
+ const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
3140
+ if (shadowing) {
3141
+ out(shadowing);
3142
+ return 1;
3143
+ }
2566
3144
  if (options.dryRun || options.diff) {
2567
3145
  out(`\nWould install (${pm}): ${packages.join(", ")}\n`);
2568
3146
  previewMutations(deps, mutations, {
@@ -2587,7 +3165,7 @@ async function scaffold(options, deps, plan) {
2587
3165
  out(" Run `clivly login` from a terminal to write CLIVLY_SECRET_KEY and CLIVLY_SYNC_TRIGGER_SECRET.\n");
2588
3166
  } else loginRan = await deps.login(options.cwd) === 0;
2589
3167
  }
2590
- printNextSteps(out, deps.authWiring.complete, loginRan);
3168
+ printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(detectFramework(deps.readDepsFn(options.cwd))));
2591
3169
  return 0;
2592
3170
  }
2593
3171
  function normalizeAppRoot(options) {
@@ -2654,8 +3232,18 @@ function printNoContactGuidance(out, plan, options) {
2654
3232
  out(`\n Tables in ${plan.importPath}:\n`);
2655
3233
  for (const name of plan.tableNames) out(` ${name}\n`);
2656
3234
  const schemaArg = options.schemaFlag ? ` --schema ${options.schemaFlag}` : "";
2657
- out("\n Pick the one that holds your people and re-run:\n");
2658
- out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0]}\n\n`);
3235
+ const best = plan.contactCandidates[0];
3236
+ if (best) {
3237
+ out(`\n Best guess: ${best.table} — ${best.reasons.join(", ")}\n`);
3238
+ const runnerUp = plan.contactCandidates.slice(1, 3).map((candidate) => candidate.table);
3239
+ if (runnerUp.length > 0) out(` Also possible: ${runnerUp.join(", ")}\n`);
3240
+ out("\n Confirm it and re-run:\n");
3241
+ out(` clivly init${schemaArg} --contact-table ${best.table}\n\n`);
3242
+ return;
3243
+ }
3244
+ out("\n Nothing here looks like a people table — no email, phone or name\n");
3245
+ out(" columns turned up. Pick the one that holds your people and re-run:\n");
3246
+ out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0] ?? "<table>"}\n\n`);
2659
3247
  out(" Nothing was written — Clivly needs one entity before a config can load.\n\n");
2660
3248
  }
2661
3249
  function hasCloudflaredOnPath() {
@@ -2751,6 +3339,22 @@ function defaultDevDeps(options) {
2751
3339
  },
2752
3340
  out: (line) => {
2753
3341
  process.stdout.write(`${line}\n`);
3342
+ },
3343
+ watchConfig: (cwd, onChange) => {
3344
+ const target = resolveConfigPath(cwd);
3345
+ try {
3346
+ let timer = null;
3347
+ const watcher = (0, node_fs.watch)(target, () => {
3348
+ if (timer) clearTimeout(timer);
3349
+ timer = setTimeout(onChange, CONFIG_WATCH_DEBOUNCE_MS);
3350
+ });
3351
+ return () => {
3352
+ if (timer) clearTimeout(timer);
3353
+ watcher.close();
3354
+ };
3355
+ } catch {
3356
+ return null;
3357
+ }
2754
3358
  }
2755
3359
  };
2756
3360
  }
@@ -2829,6 +3433,21 @@ function runInitFromArgv(argv, cwd) {
2829
3433
  }
2830
3434
  async function main(argv) {
2831
3435
  const [command, ...rest] = argv;
3436
+ if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
3437
+ process.stdout.write(helpFor(command));
3438
+ return 0;
3439
+ }
3440
+ if (command === "--version" || command === "-v") {
3441
+ process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
3442
+ return 0;
3443
+ }
3444
+ if (!process.env.CLIVLY_SKIP_ENGINE_CHECK) {
3445
+ const engineProblem = engineError(process.version, readOwnEngines());
3446
+ if (engineProblem) {
3447
+ process.stderr.write(engineProblem);
3448
+ return 1;
3449
+ }
3450
+ }
2832
3451
  let cliEnvFiles = [];
2833
3452
  try {
2834
3453
  cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
@@ -2847,14 +3466,16 @@ async function main(argv) {
2847
3466
  case "status":
2848
3467
  case "ping":
2849
3468
  case "doctor":
2850
- case "connect": return await runStatus({
2851
- cwd: process.cwd(),
2852
- apiKey: readSecretKeyEnv(process.env),
2853
- apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
2854
- configPath: flagValue(rest, "--config"),
2855
- only: ALIAS_STAGE_IDS[command],
2856
- verbose: rest.includes("--verbose")
2857
- });
3469
+ case "connect":
3470
+ if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
3471
+ return await runStatus({
3472
+ cwd: process.cwd(),
3473
+ apiKey: readSecretKeyEnv(process.env),
3474
+ apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
3475
+ configPath: flagValue(rest, "--config"),
3476
+ only: ALIAS_STAGE_IDS[command],
3477
+ verbose: rest.includes("--verbose")
3478
+ });
2858
3479
  case "dev": {
2859
3480
  const apiKey = readSecretKeyEnv(process.env);
2860
3481
  const apiUrl = flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL ?? "https://api.clivly.com";
@@ -2877,14 +3498,11 @@ async function main(argv) {
2877
3498
  openBrowser: !rest.includes("--no-browser"),
2878
3499
  deps: defaultLoginDeps()
2879
3500
  });
2880
- case "--version":
2881
- case "-v":
2882
- process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
2883
- return 0;
2884
3501
  case void 0:
3502
+ process.stdout.write(ROOT_HELP);
3503
+ return 0;
2885
3504
  case "help":
2886
- case "--help":
2887
- process.stdout.write("clivly — embed a CRM in your app\n\nUsage:\n clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]\n [--schema <path|package>] [--db-import <specifier>] [--auth-import <specifier>]\n Scaffold Clivly (config, routes, .env) for your app\n clivly add widget [--force] [--dry-run] Scaffold the chat-session route\n clivly status [--verbose] [--config <path>] [--env-file <path>] Check your setup, step by step\n clivly push-schema [--config <path>] Report your schema to Clivly without deploying\n clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>] Tunnel localhost for remote sync\n clivly login [--force] [--rotate] [--api-url <url>] [--no-browser] Pair this machine and write CLIVLY_SECRET_KEY / CLIVLY_SYNC_TRIGGER_SECRET to .env\n clivly --version Print the installed clivly version\n");
3505
+ process.stdout.write(helpFor(rest[0]));
2888
3506
  return 0;
2889
3507
  default: {
2890
3508
  process.stdout.write(`Unknown command: ${command}\n`);