@elevasis/sdk 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -6,6 +6,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __commonJS = (cb, mod) => function __require() {
10
13
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
14
  };
@@ -225,8 +228,8 @@ var require_main = __commonJS({
225
228
  }
226
229
  return null;
227
230
  }
228
- function _resolveHome(envPath) {
229
- return envPath[0] === "~" ? path.join(os2.homedir(), envPath.slice(1)) : envPath;
231
+ function _resolveHome(envPath2) {
232
+ return envPath2[0] === "~" ? path.join(os2.homedir(), envPath2.slice(1)) : envPath2;
230
233
  }
231
234
  function _configVault(options2) {
232
235
  const debug = Boolean(options2 && options2.debug);
@@ -6622,14 +6625,14 @@ var require_async_iterator = __commonJS({
6622
6625
  };
6623
6626
  }
6624
6627
  function readAndResolve(iter) {
6625
- var resolve6 = iter[kLastResolve];
6626
- if (resolve6 !== null) {
6628
+ var resolve4 = iter[kLastResolve];
6629
+ if (resolve4 !== null) {
6627
6630
  var data = iter[kStream].read();
6628
6631
  if (data !== null) {
6629
6632
  iter[kLastPromise] = null;
6630
6633
  iter[kLastResolve] = null;
6631
6634
  iter[kLastReject] = null;
6632
- resolve6(createIterResult(data, false));
6635
+ resolve4(createIterResult(data, false));
6633
6636
  }
6634
6637
  }
6635
6638
  }
@@ -6637,13 +6640,13 @@ var require_async_iterator = __commonJS({
6637
6640
  process.nextTick(readAndResolve, iter);
6638
6641
  }
6639
6642
  function wrapForNext(lastPromise, iter) {
6640
- return function(resolve6, reject) {
6643
+ return function(resolve4, reject) {
6641
6644
  lastPromise.then(function() {
6642
6645
  if (iter[kEnded]) {
6643
- resolve6(createIterResult(void 0, true));
6646
+ resolve4(createIterResult(void 0, true));
6644
6647
  return;
6645
6648
  }
6646
- iter[kHandlePromise](resolve6, reject);
6649
+ iter[kHandlePromise](resolve4, reject);
6647
6650
  }, reject);
6648
6651
  };
6649
6652
  }
@@ -6663,12 +6666,12 @@ var require_async_iterator = __commonJS({
6663
6666
  return Promise.resolve(createIterResult(void 0, true));
6664
6667
  }
6665
6668
  if (this[kStream].destroyed) {
6666
- return new Promise(function(resolve6, reject) {
6669
+ return new Promise(function(resolve4, reject) {
6667
6670
  process.nextTick(function() {
6668
6671
  if (_this[kError]) {
6669
6672
  reject(_this[kError]);
6670
6673
  } else {
6671
- resolve6(createIterResult(void 0, true));
6674
+ resolve4(createIterResult(void 0, true));
6672
6675
  }
6673
6676
  });
6674
6677
  });
@@ -6691,13 +6694,13 @@ var require_async_iterator = __commonJS({
6691
6694
  return this;
6692
6695
  }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
6693
6696
  var _this2 = this;
6694
- return new Promise(function(resolve6, reject) {
6697
+ return new Promise(function(resolve4, reject) {
6695
6698
  _this2[kStream].destroy(null, function(err) {
6696
6699
  if (err) {
6697
6700
  reject(err);
6698
6701
  return;
6699
6702
  }
6700
- resolve6(createIterResult(void 0, true));
6703
+ resolve4(createIterResult(void 0, true));
6701
6704
  });
6702
6705
  });
6703
6706
  }), _Object$setPrototypeO), AsyncIteratorPrototype);
@@ -6719,15 +6722,15 @@ var require_async_iterator = __commonJS({
6719
6722
  value: stream._readableState.endEmitted,
6720
6723
  writable: true
6721
6724
  }), _defineProperty(_Object$create, kHandlePromise, {
6722
- value: function value(resolve6, reject) {
6725
+ value: function value(resolve4, reject) {
6723
6726
  var data = iterator[kStream].read();
6724
6727
  if (data) {
6725
6728
  iterator[kLastPromise] = null;
6726
6729
  iterator[kLastResolve] = null;
6727
6730
  iterator[kLastReject] = null;
6728
- resolve6(createIterResult(data, false));
6731
+ resolve4(createIterResult(data, false));
6729
6732
  } else {
6730
- iterator[kLastResolve] = resolve6;
6733
+ iterator[kLastResolve] = resolve4;
6731
6734
  iterator[kLastReject] = reject;
6732
6735
  }
6733
6736
  },
@@ -6746,12 +6749,12 @@ var require_async_iterator = __commonJS({
6746
6749
  iterator[kError] = err;
6747
6750
  return;
6748
6751
  }
6749
- var resolve6 = iterator[kLastResolve];
6750
- if (resolve6 !== null) {
6752
+ var resolve4 = iterator[kLastResolve];
6753
+ if (resolve4 !== null) {
6751
6754
  iterator[kLastPromise] = null;
6752
6755
  iterator[kLastResolve] = null;
6753
6756
  iterator[kLastReject] = null;
6754
- resolve6(createIterResult(void 0, true));
6757
+ resolve4(createIterResult(void 0, true));
6755
6758
  }
6756
6759
  iterator[kEnded] = true;
6757
6760
  });
@@ -6766,7 +6769,7 @@ var require_async_iterator = __commonJS({
6766
6769
  var require_from = __commonJS({
6767
6770
  "../../node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/from.js"(exports2, module2) {
6768
6771
  "use strict";
6769
- function asyncGeneratorStep(gen, resolve6, reject, _next, _throw, key, arg) {
6772
+ function asyncGeneratorStep(gen, resolve4, reject, _next, _throw, key, arg) {
6770
6773
  try {
6771
6774
  var info = gen[key](arg);
6772
6775
  var value = info.value;
@@ -6775,7 +6778,7 @@ var require_from = __commonJS({
6775
6778
  return;
6776
6779
  }
6777
6780
  if (info.done) {
6778
- resolve6(value);
6781
+ resolve4(value);
6779
6782
  } else {
6780
6783
  Promise.resolve(value).then(_next, _throw);
6781
6784
  }
@@ -6783,13 +6786,13 @@ var require_from = __commonJS({
6783
6786
  function _asyncToGenerator(fn) {
6784
6787
  return function() {
6785
6788
  var self2 = this, args = arguments;
6786
- return new Promise(function(resolve6, reject) {
6789
+ return new Promise(function(resolve4, reject) {
6787
6790
  var gen = fn.apply(self2, args);
6788
6791
  function _next(value) {
6789
- asyncGeneratorStep(gen, resolve6, reject, _next, _throw, "next", value);
6792
+ asyncGeneratorStep(gen, resolve4, reject, _next, _throw, "next", value);
6790
6793
  }
6791
6794
  function _throw(err) {
6792
- asyncGeneratorStep(gen, resolve6, reject, _next, _throw, "throw", err);
6795
+ asyncGeneratorStep(gen, resolve4, reject, _next, _throw, "throw", err);
6793
6796
  }
6794
6797
  _next(void 0);
6795
6798
  });
@@ -26487,9 +26490,67 @@ var require_zod = __commonJS({
26487
26490
  }
26488
26491
  });
26489
26492
 
26493
+ // src/cli/config.ts
26494
+ var config_exports = {};
26495
+ __export(config_exports, {
26496
+ findEnvFile: () => findEnvFile,
26497
+ resolveApiKey: () => resolveApiKey,
26498
+ resolveApiUrl: () => resolveApiUrl,
26499
+ resolveEnvironment: () => resolveEnvironment
26500
+ });
26501
+ function resolveApiUrl(cliOverride, prod) {
26502
+ if (cliOverride) return cliOverride;
26503
+ if (prod) return PROD_API_URL;
26504
+ if (process.env.ELEVASIS_API_URL) return process.env.ELEVASIS_API_URL;
26505
+ if (process.env.NODE_ENV === "development") return DEV_API_URL;
26506
+ return PROD_API_URL;
26507
+ }
26508
+ function resolveEnvironment(prod) {
26509
+ if (prod) return "production";
26510
+ return process.env.NODE_ENV === "development" ? "development" : "production";
26511
+ }
26512
+ function resolveApiKey(prod) {
26513
+ if (!prod && process.env.NODE_ENV === "development") {
26514
+ return process.env.ELEVASIS_PLATFORM_KEY_DEV ?? process.env.ELEVASIS_PLATFORM_KEY ?? "";
26515
+ }
26516
+ return process.env.ELEVASIS_PLATFORM_KEY ?? "";
26517
+ }
26518
+ function findEnvFile(startDir) {
26519
+ const cwd = (0, import_path.resolve)(startDir ?? process.cwd());
26520
+ let dir = cwd;
26521
+ while (true) {
26522
+ const candidate = (0, import_path.resolve)(dir, ".env");
26523
+ if ((0, import_fs.existsSync)(candidate)) return candidate;
26524
+ const parent = (0, import_path.dirname)(dir);
26525
+ if (parent === dir) break;
26526
+ dir = parent;
26527
+ }
26528
+ dir = cwd;
26529
+ while (true) {
26530
+ if ((0, import_fs.existsSync)((0, import_path.resolve)(dir, "pnpm-workspace.yaml"))) {
26531
+ const candidate = (0, import_path.resolve)(dir, ".env");
26532
+ if ((0, import_fs.existsSync)(candidate)) return candidate;
26533
+ break;
26534
+ }
26535
+ const parent = (0, import_path.dirname)(dir);
26536
+ if (parent === dir) break;
26537
+ dir = parent;
26538
+ }
26539
+ return void 0;
26540
+ }
26541
+ var import_fs, import_path, DEV_API_URL, PROD_API_URL;
26542
+ var init_config = __esm({
26543
+ "src/cli/config.ts"() {
26544
+ "use strict";
26545
+ import_fs = require("fs");
26546
+ import_path = require("path");
26547
+ DEV_API_URL = "http://localhost:5170";
26548
+ PROD_API_URL = "https://api.elevasis.io";
26549
+ }
26550
+ });
26551
+
26490
26552
  // src/cli/index.ts
26491
26553
  var import_dotenv = __toESM(require_main(), 1);
26492
- var import_path5 = require("path");
26493
26554
 
26494
26555
  // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/esm.mjs
26495
26556
  var import_index = __toESM(require_commander(), 1);
@@ -27004,7 +27065,7 @@ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
27004
27065
  var source_default = chalk;
27005
27066
 
27006
27067
  // src/cli/commands/check.ts
27007
- var import_path2 = require("path");
27068
+ var import_path3 = require("path");
27008
27069
 
27009
27070
  // ../../node_modules/.pnpm/ora@7.0.1/node_modules/ora/index.js
27010
27071
  var import_node_process6 = __toESM(require("node:process"), 1);
@@ -27516,7 +27577,7 @@ function ora(options2) {
27516
27577
  }
27517
27578
 
27518
27579
  // src/cli/commands/deploy.ts
27519
- var import_path = require("path");
27580
+ var import_path2 = require("path");
27520
27581
  var import_promises = require("fs/promises");
27521
27582
  var import_gray_matter = __toESM(require_gray_matter(), 1);
27522
27583
 
@@ -43774,28 +43835,11 @@ var ResourceRegistry = class {
43774
43835
  }
43775
43836
  };
43776
43837
 
43777
- // src/cli/config.ts
43778
- var DEV_API_URL = "http://localhost:5170";
43779
- var PROD_API_URL = "https://api.elevasis.io";
43780
- function resolveApiUrl(cliOverride, prod) {
43781
- if (cliOverride) return cliOverride;
43782
- if (prod) return PROD_API_URL;
43783
- if (process.env.ELEVASIS_API_URL) return process.env.ELEVASIS_API_URL;
43784
- if (process.env.NODE_ENV === "development") return DEV_API_URL;
43785
- return PROD_API_URL;
43786
- }
43787
- function resolveEnvironment(prod) {
43788
- if (prod) return "production";
43789
- return process.env.NODE_ENV === "development" ? "development" : "production";
43790
- }
43791
- function resolveApiKey(prod) {
43792
- if (!prod && process.env.NODE_ENV === "development") {
43793
- return process.env.ELEVASIS_PLATFORM_KEY_DEV ?? process.env.ELEVASIS_PLATFORM_KEY ?? "";
43794
- }
43795
- return process.env.ELEVASIS_PLATFORM_KEY ?? "";
43796
- }
43838
+ // src/cli/commands/deploy.ts
43839
+ init_config();
43797
43840
 
43798
43841
  // src/cli/api-client.ts
43842
+ init_config();
43799
43843
  function getApiKey(apiUrl) {
43800
43844
  const isProd = !apiUrl.includes("localhost");
43801
43845
  const key = resolveApiKey(isProd);
@@ -43893,7 +43937,7 @@ function wrapAction(commandName, fn) {
43893
43937
  // package.json
43894
43938
  var package_default = {
43895
43939
  name: "@elevasis/sdk",
43896
- version: "1.0.2",
43940
+ version: "1.1.0",
43897
43941
  description: "SDK for building Elevasis organization resources",
43898
43942
  type: "module",
43899
43943
  bin: {
@@ -43907,10 +43951,6 @@ var package_default = {
43907
43951
  "./worker": {
43908
43952
  types: "./dist/types/worker/index.d.ts",
43909
43953
  import: "./dist/worker/index.js"
43910
- },
43911
- "./templates": {
43912
- types: "./dist/types/templates.d.ts",
43913
- import: "./dist/templates.js"
43914
43954
  }
43915
43955
  },
43916
43956
  files: [
@@ -43921,8 +43961,6 @@ var package_default = {
43921
43961
  "dist/types/worker/platform.d.ts",
43922
43962
  "dist/types/worker/adapters/",
43923
43963
  "dist/cli.cjs",
43924
- "dist/templates.js",
43925
- "dist/types/templates.d.ts",
43926
43964
  "reference/"
43927
43965
  ],
43928
43966
  scripts: {
@@ -43958,13 +43996,13 @@ var SDK_VERSION = package_default.version;
43958
43996
 
43959
43997
  // src/cli/commands/deploy.ts
43960
43998
  function getEsbuild() {
43961
- const consumerRequire = (0, import_module.createRequire)((0, import_path.resolve)(process.cwd(), "package.json"));
43999
+ const consumerRequire = (0, import_module.createRequire)((0, import_path2.resolve)(process.cwd(), "package.json"));
43962
44000
  return consumerRequire("esbuild");
43963
44001
  }
43964
44002
  async function loadTsModule(filePath) {
43965
44003
  const esbuild = getEsbuild();
43966
- const absPath = (0, import_path.resolve)(filePath);
43967
- const tmpOut = (0, import_path.resolve)(`.elevasis-tmp-${Date.now()}.mjs`);
44004
+ const absPath = (0, import_path2.resolve)(filePath);
44005
+ const tmpOut = (0, import_path2.resolve)(`.elevasis-tmp-${Date.now()}.mjs`);
43968
44006
  try {
43969
44007
  await esbuild.build({
43970
44008
  entryPoints: [absPath],
@@ -44023,7 +44061,7 @@ function bumpVersion(current, type) {
44023
44061
  }
44024
44062
  var IGNORED_DOC_DIRS = /* @__PURE__ */ new Set([".archive"]);
44025
44063
  async function scanDocumentation() {
44026
- const docsDir = (0, import_path.resolve)("docs");
44064
+ const docsDir = (0, import_path2.resolve)("docs");
44027
44065
  const files = [];
44028
44066
  let totalSize = 0;
44029
44067
  async function scan(dir, relPrefix) {
@@ -44034,7 +44072,7 @@ async function scanDocumentation() {
44034
44072
  return;
44035
44073
  }
44036
44074
  for (const entry of entries) {
44037
- const fullPath = (0, import_path.resolve)(dir, entry.name);
44075
+ const fullPath = (0, import_path2.resolve)(dir, entry.name);
44038
44076
  const relPath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
44039
44077
  if (entry.isDirectory()) {
44040
44078
  if (IGNORED_DOC_DIRS.has(entry.name)) continue;
@@ -44121,21 +44159,12 @@ async function generateResourceMap(org) {
44121
44159
  `**Total:** ${workflows.length + agents.length} resources (${workflows.length} workflows, ${agents.length} agents)`,
44122
44160
  ""
44123
44161
  );
44124
- await (0, import_promises.mkdir)((0, import_path.resolve)("docs"), { recursive: true });
44125
- await (0, import_promises.writeFile)((0, import_path.resolve)("docs/resource-map.mdx"), lines.join("\n"), "utf-8");
44162
+ await (0, import_promises.mkdir)((0, import_path2.resolve)("docs"), { recursive: true });
44163
+ await (0, import_promises.writeFile)((0, import_path2.resolve)("docs/resource-map.mdx"), lines.join("\n"), "utf-8");
44126
44164
  }
44127
44165
  async function generateProjectMap(org) {
44128
44166
  const workflows = org.workflows ?? [];
44129
44167
  const agents = org.agents ?? [];
44130
- let templateVersion = "unknown";
44131
- try {
44132
- const cfg = await loadTsModule("elevasis.config.ts");
44133
- const cfgObj = cfg.default ?? cfg;
44134
- if (cfgObj?.templateVersion != null) {
44135
- templateVersion = String(cfgObj.templateVersion);
44136
- }
44137
- } catch {
44138
- }
44139
44168
  const lastDeploy = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
44140
44169
  const lines = [
44141
44170
  "---",
@@ -44153,7 +44182,6 @@ async function generateProjectMap(org) {
44153
44182
  "| Field | Value |",
44154
44183
  "| --- | --- |",
44155
44184
  `| SDK Version | ${SDK_VERSION} |`,
44156
- `| Template Version | ${templateVersion} |`,
44157
44185
  `| Last Deploy | ${lastDeploy} |`,
44158
44186
  `| Resources | ${workflows.length} workflows, ${agents.length} agents |`,
44159
44187
  ""
@@ -44167,7 +44195,7 @@ async function generateProjectMap(org) {
44167
44195
  "| --- | --- | --- | --- |"
44168
44196
  );
44169
44197
  try {
44170
- const srcEntries = await (0, import_promises.readdir)((0, import_path.resolve)("src"), { withFileTypes: true });
44198
+ const srcEntries = await (0, import_promises.readdir)((0, import_path2.resolve)("src"), { withFileTypes: true });
44171
44199
  const domainDirs = srcEntries.filter((e) => e.isDirectory());
44172
44200
  if (domainDirs.length === 0) {
44173
44201
  lines.push("| (none) | src/ | 0 | \u2014 |");
@@ -44233,10 +44261,10 @@ async function generateProjectMap(org) {
44233
44261
  const relPath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
44234
44262
  if (entry.isDirectory()) {
44235
44263
  if (IGNORED_DOC_DIRS.has(entry.name)) continue;
44236
- await scanDocsDir((0, import_path.resolve)(dir, entry.name), relPath);
44264
+ await scanDocsDir((0, import_path2.resolve)(dir, entry.name), relPath);
44237
44265
  } else if (entry.isFile() && entry.name.endsWith(".mdx") && relPath !== "project-map.mdx" && relPath !== "resource-map.mdx") {
44238
44266
  try {
44239
- const raw = await (0, import_promises.readFile)((0, import_path.resolve)(dir, entry.name), "utf-8");
44267
+ const raw = await (0, import_promises.readFile)((0, import_path2.resolve)(dir, entry.name), "utf-8");
44240
44268
  const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
44241
44269
  let title = relPath;
44242
44270
  let description = "";
@@ -44256,7 +44284,7 @@ async function generateProjectMap(org) {
44256
44284
  }
44257
44285
  }
44258
44286
  }
44259
- await scanDocsDir((0, import_path.resolve)("docs"), "");
44287
+ await scanDocsDir((0, import_path2.resolve)("docs"), "");
44260
44288
  docEntries.sort((a, b) => {
44261
44289
  if (a.order !== b.order) return a.order - b.order;
44262
44290
  return a.title.localeCompare(b.title);
@@ -44274,7 +44302,7 @@ async function generateProjectMap(org) {
44274
44302
  lines.push("");
44275
44303
  lines.push("## SDK Reference", "");
44276
44304
  try {
44277
- const navPath = (0, import_path.resolve)("node_modules/@elevasis/sdk/reference/_navigation.md");
44305
+ const navPath = (0, import_path2.resolve)("node_modules/@elevasis/sdk/reference/_navigation.md");
44278
44306
  const navContent = await (0, import_promises.readFile)(navPath, "utf-8");
44279
44307
  const navLines = navContent.split(/\r?\n/);
44280
44308
  const categories = [];
@@ -44314,7 +44342,7 @@ async function generateProjectMap(org) {
44314
44342
  }
44315
44343
  lines.push("## Command and Rules System", "", "### Commands", "");
44316
44344
  try {
44317
- const cmdEntries = await (0, import_promises.readdir)((0, import_path.resolve)(".claude/commands"), { withFileTypes: true });
44345
+ const cmdEntries = await (0, import_promises.readdir)((0, import_path2.resolve)(".claude/commands"), { withFileTypes: true });
44318
44346
  const cmdFiles = cmdEntries.filter((e) => e.isFile() && e.name.endsWith(".md"));
44319
44347
  if (cmdFiles.length === 0) {
44320
44348
  lines.push("No commands found.", "");
@@ -44324,7 +44352,7 @@ async function generateProjectMap(org) {
44324
44352
  const cmdName = f.name.replace(/\.md$/, "");
44325
44353
  let purpose = "";
44326
44354
  try {
44327
- const raw = await (0, import_promises.readFile)((0, import_path.resolve)(".claude/commands", f.name), "utf-8");
44355
+ const raw = await (0, import_promises.readFile)((0, import_path2.resolve)(".claude/commands", f.name), "utf-8");
44328
44356
  const goalMatch = raw.match(/\*\*Goal:\*\*\s*(.+)/);
44329
44357
  if (goalMatch) {
44330
44358
  purpose = goalMatch[1].trim();
@@ -44343,7 +44371,7 @@ async function generateProjectMap(org) {
44343
44371
  }
44344
44372
  lines.push("### Rules (auto-injected)", "");
44345
44373
  try {
44346
- const ruleEntries = await (0, import_promises.readdir)((0, import_path.resolve)(".claude/rules"), { withFileTypes: true });
44374
+ const ruleEntries = await (0, import_promises.readdir)((0, import_path2.resolve)(".claude/rules"), { withFileTypes: true });
44347
44375
  const ruleFiles = ruleEntries.filter((e) => e.isFile() && e.name.endsWith(".md"));
44348
44376
  if (ruleFiles.length === 0) {
44349
44377
  lines.push("No rules found.", "");
@@ -44353,7 +44381,7 @@ async function generateProjectMap(org) {
44353
44381
  const ruleName = f.name.replace(/\.md$/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
44354
44382
  let scope = "";
44355
44383
  try {
44356
- const raw = await (0, import_promises.readFile)((0, import_path.resolve)(".claude/rules", f.name), "utf-8");
44384
+ const raw = await (0, import_promises.readFile)((0, import_path2.resolve)(".claude/rules", f.name), "utf-8");
44357
44385
  const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
44358
44386
  if (fmMatch) {
44359
44387
  const descMatch = fmMatch[1].match(/^description:\s*(.+)$/m);
@@ -44374,14 +44402,14 @@ async function generateProjectMap(org) {
44374
44402
  }
44375
44403
  lines.push("### Skills", "");
44376
44404
  try {
44377
- const skillEntries = await (0, import_promises.readdir)((0, import_path.resolve)(".claude/skills"), { withFileTypes: true });
44405
+ const skillEntries = await (0, import_promises.readdir)((0, import_path2.resolve)(".claude/skills"), { withFileTypes: true });
44378
44406
  const skillDirs = skillEntries.filter((e) => e.isDirectory());
44379
44407
  if (skillDirs.length === 0) {
44380
44408
  lines.push("No skills found.", "");
44381
44409
  } else {
44382
44410
  lines.push("| Skill | File | Trigger |", "| --- | --- | --- |");
44383
44411
  for (const d of skillDirs) {
44384
- const skillFile = (0, import_path.resolve)(".claude/skills", d.name, "SKILL.md");
44412
+ const skillFile = (0, import_path2.resolve)(".claude/skills", d.name, "SKILL.md");
44385
44413
  let trigger = "";
44386
44414
  try {
44387
44415
  const raw = await (0, import_promises.readFile)(skillFile, "utf-8");
@@ -44414,7 +44442,7 @@ async function generateProjectMap(org) {
44414
44442
  return;
44415
44443
  }
44416
44444
  for (const entry of entries) {
44417
- const fullPath = (0, import_path.resolve)(dir, entry.name);
44445
+ const fullPath = (0, import_path2.resolve)(dir, entry.name);
44418
44446
  const relPath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
44419
44447
  if (entry.isDirectory()) {
44420
44448
  await scanMemory(fullPath, relPath);
@@ -44431,7 +44459,7 @@ async function generateProjectMap(org) {
44431
44459
  }
44432
44460
  }
44433
44461
  }
44434
- await scanMemory((0, import_path.resolve)(".claude/memory"), "");
44462
+ await scanMemory((0, import_path2.resolve)(".claude/memory"), "");
44435
44463
  if (memoryFiles.length === 0) {
44436
44464
  lines.push("No memory files found.", "");
44437
44465
  } else {
@@ -44448,7 +44476,8 @@ async function generateProjectMap(org) {
44448
44476
  let apiKeySet = "no";
44449
44477
  let nodeEnv = "not set";
44450
44478
  try {
44451
- const envContent = await (0, import_promises.readFile)((0, import_path.resolve)(".env"), "utf-8");
44479
+ const { findEnvFile: findEnvFile2 } = await Promise.resolve().then(() => (init_config(), config_exports));
44480
+ const envContent = await (0, import_promises.readFile)(findEnvFile2() ?? (0, import_path2.resolve)(".env"), "utf-8");
44452
44481
  const apiKeyMatch = envContent.match(/^ELEVASIS_PLATFORM_KEY=(.+)$/m);
44453
44482
  if (apiKeyMatch && apiKeyMatch[1].trim()) apiKeySet = "yes";
44454
44483
  const nodeEnvMatch = envContent.match(/^NODE_ENV=(.+)$/m);
@@ -44458,14 +44487,13 @@ async function generateProjectMap(org) {
44458
44487
  lines.push(
44459
44488
  "| Setting | Source | Value |",
44460
44489
  "| --- | --- | --- |",
44461
- `| Template Version | elevasis.config.ts | ${templateVersion} |`,
44462
44490
  `| SDK Version | package.json | ${SDK_VERSION} |`,
44463
44491
  `| API Key Set | .env | ${apiKeySet} |`,
44464
44492
  `| Node Env | .env | ${nodeEnv} |`,
44465
44493
  ""
44466
44494
  );
44467
- await (0, import_promises.mkdir)((0, import_path.resolve)("docs"), { recursive: true });
44468
- await (0, import_promises.writeFile)((0, import_path.resolve)("docs/project-map.mdx"), lines.join("\n"), "utf-8");
44495
+ await (0, import_promises.mkdir)((0, import_path2.resolve)("docs"), { recursive: true });
44496
+ await (0, import_promises.writeFile)((0, import_path2.resolve)("docs/project-map.mdx"), lines.join("\n"), "utf-8");
44469
44497
  }
44470
44498
  async function generateNavigationMap(docs) {
44471
44499
  const excludedFiles = /* @__PURE__ */ new Set(["docs/navigation-map.mdx", "docs/project-map.mdx", "docs/resource-map.mdx"]);
@@ -44493,8 +44521,8 @@ async function generateNavigationMap(docs) {
44493
44521
  lines.push(`| ${escapeMdx(doc.frontmatter.title)} | ${escapeMdx(doc.frontmatter.description)} | ${doc.path} |`);
44494
44522
  }
44495
44523
  lines.push("");
44496
- await (0, import_promises.mkdir)((0, import_path.resolve)("docs"), { recursive: true });
44497
- await (0, import_promises.writeFile)((0, import_path.resolve)("docs/navigation-map.mdx"), lines.join("\n"), "utf-8");
44524
+ await (0, import_promises.mkdir)((0, import_path2.resolve)("docs"), { recursive: true });
44525
+ await (0, import_promises.writeFile)((0, import_path2.resolve)("docs/navigation-map.mdx"), lines.join("\n"), "utf-8");
44498
44526
  }
44499
44527
  function registerDeployCommand(program3) {
44500
44528
  program3.command("deploy").description(
@@ -44537,7 +44565,7 @@ function registerDeployCommand(program3) {
44537
44565
  org = entryModule.default;
44538
44566
  if (!org) {
44539
44567
  validateSpinner.fail("Invalid entry: no default export found");
44540
- console.error(source_default.gray(` Entry file: ${(0, import_path.resolve)(entryPath)}`));
44568
+ console.error(source_default.gray(` Entry file: ${(0, import_path2.resolve)(entryPath)}`));
44541
44569
  throw new Error("Invalid entry: no default export found");
44542
44570
  }
44543
44571
  new ResourceRegistry({ [orgName]: org });
@@ -44555,7 +44583,7 @@ function registerDeployCommand(program3) {
44555
44583
  const currentVersion = org.version;
44556
44584
  if (bumpType !== null) {
44557
44585
  const newVersion = bumpVersion(currentVersion, bumpType);
44558
- const absEntryPath = (0, import_path.resolve)(entryPath);
44586
+ const absEntryPath = (0, import_path2.resolve)(entryPath);
44559
44587
  const entryContent = await (0, import_promises.readFile)(absEntryPath, "utf-8");
44560
44588
  const updatedContent = entryContent.replace(
44561
44589
  /version:\s*['"][\d]+\.[\d]+\.[\d]+['"]/,
@@ -44628,8 +44656,8 @@ function registerDeployCommand(program3) {
44628
44656
  console.log("");
44629
44657
  }
44630
44658
  const bundleSpinner = ora("Bundling...").start();
44631
- const wrapperPath = (0, import_path.resolve)("__elevasis_worker.ts");
44632
- const bundleOutfile = (0, import_path.resolve)("dist/bundle.js");
44659
+ const wrapperPath = (0, import_path2.resolve)("__elevasis_worker.ts");
44660
+ const bundleOutfile = (0, import_path2.resolve)("dist/bundle.js");
44633
44661
  try {
44634
44662
  const entryImport = entryPath.replace(/\.ts$/, ".js");
44635
44663
  const wrapperContent = `import org from ${JSON.stringify(entryImport)}
@@ -44637,7 +44665,7 @@ import { startWorker } from '@elevasis/sdk/worker'
44637
44665
  startWorker(org)
44638
44666
  `;
44639
44667
  await (0, import_promises.writeFile)(wrapperPath, wrapperContent, "utf-8");
44640
- await (0, import_promises.mkdir)((0, import_path.resolve)("dist"), { recursive: true });
44668
+ await (0, import_promises.mkdir)((0, import_path2.resolve)("dist"), { recursive: true });
44641
44669
  const esbuild = getEsbuild();
44642
44670
  await esbuild.build({
44643
44671
  entryPoints: [wrapperPath],
@@ -44747,7 +44775,7 @@ function registerCheckCommand(program3) {
44747
44775
  const org = entryModule.default;
44748
44776
  if (!org) {
44749
44777
  spinner.fail("Invalid entry: no default export found");
44750
- console.error(source_default.gray(` Entry file: ${(0, import_path2.resolve)(entryPath)}`));
44778
+ console.error(source_default.gray(` Entry file: ${(0, import_path3.resolve)(entryPath)}`));
44751
44779
  console.error(source_default.gray(" Expected: export default { workflows: [...], agents: [...] }"));
44752
44780
  throw new Error("Invalid entry");
44753
44781
  }
@@ -44816,6 +44844,7 @@ function registerCheckCommand(program3) {
44816
44844
 
44817
44845
  // src/cli/commands/exec.ts
44818
44846
  var import_node_fs = require("node:fs");
44847
+ init_config();
44819
44848
  var POLL_INTERVAL_MS = 3e3;
44820
44849
  async function pollForCompletion(resourceId, executionId, apiUrl) {
44821
44850
  const pollSpinner = ora("Waiting for completion...").start();
@@ -44830,7 +44859,7 @@ async function pollForCompletion(resourceId, executionId, apiUrl) {
44830
44859
  };
44831
44860
  process.on("SIGINT", cleanup);
44832
44861
  while (true) {
44833
- await new Promise((resolve6) => setTimeout(resolve6, POLL_INTERVAL_MS));
44862
+ await new Promise((resolve4) => setTimeout(resolve4, POLL_INTERVAL_MS));
44834
44863
  const elapsed = Math.round((Date.now() - startTime) / 1e3);
44835
44864
  pollSpinner.text = `Waiting for completion... (${elapsed}s)`;
44836
44865
  try {
@@ -44935,6 +44964,7 @@ function registerExecCommand(program3) {
44935
44964
  }
44936
44965
 
44937
44966
  // src/cli/commands/resources.ts
44967
+ init_config();
44938
44968
  function registerResourcesCommand(program3) {
44939
44969
  program3.command("resources").description("List deployed resources for your organization").option("--api-url <url>", "API URL").option("--json", "Output as JSON").action(wrapAction("resources", async (options2) => {
44940
44970
  const apiUrl = resolveApiUrl(options2.apiUrl);
@@ -44980,6 +45010,7 @@ function registerResourcesCommand(program3) {
44980
45010
  }
44981
45011
 
44982
45012
  // src/cli/commands/executions.ts
45013
+ init_config();
44983
45014
  function registerExecutionsCommand(program3) {
44984
45015
  program3.command("executions <resourceId>").description("List execution history for a resource\n Example: elevasis-sdk executions my-workflow --limit 10").option("--api-url <url>", "API URL").option("--json", "Output as JSON").option("--limit <number>", "Limit number of results (default: 50)").option("--status <status>", "Filter by status (running|completed|failed)").action(wrapAction("executions", async (resourceId, options2) => {
44985
45016
  const apiUrl = resolveApiUrl(options2.apiUrl);
@@ -45038,6 +45069,7 @@ function registerExecutionsCommand(program3) {
45038
45069
  }
45039
45070
 
45040
45071
  // src/cli/commands/execution.ts
45072
+ init_config();
45041
45073
  function registerExecutionCommand(program3) {
45042
45074
  program3.command("execution <resourceId> <executionId>").description("Get detailed information about a specific execution\n Example: elevasis-sdk execution my-workflow abc-123-uuid --logs-only").option("--api-url <url>", "API URL").option("--json", "Output raw JSON response").option("--logs-only", "Show only execution logs").option("--input", "Include input data in output").option("--result", "Include result data in output").action(wrapAction("execution", async (resourceId, executionId, options2) => {
45043
45075
  const apiUrl = resolveApiUrl(options2.apiUrl);
@@ -45140,6 +45172,7 @@ function displayLog(log) {
45140
45172
  }
45141
45173
 
45142
45174
  // src/cli/commands/deployments.ts
45175
+ init_config();
45143
45176
  function registerDeploymentsCommand(program3) {
45144
45177
  program3.command("deployments").description("List deployments for your organization").option("--api-url <url>", "API URL").option("--json", "Output as JSON").action(wrapAction("deployments", async (options2) => {
45145
45178
  const apiUrl = resolveApiUrl(options2.apiUrl);
@@ -45200,6 +45233,7 @@ function registerDeploymentsCommand(program3) {
45200
45233
  }
45201
45234
 
45202
45235
  // src/cli/commands/describe.ts
45236
+ init_config();
45203
45237
  function hasSchemaContent(schema) {
45204
45238
  return Object.keys(schema).some((k) => k !== "$schema");
45205
45239
  }
@@ -45269,3085 +45303,8 @@ function registerDescribeCommand(program3) {
45269
45303
  );
45270
45304
  }
45271
45305
 
45272
- // src/cli/commands/init.ts
45273
- var import_path3 = require("path");
45274
- var import_promises2 = require("fs/promises");
45275
-
45276
- // src/cli/commands/templates/core/workspace.ts
45277
- var TEMPLATE_VERSION = 34;
45278
- function configTemplate() {
45279
- return `import type { ElevasConfig } from '@elevasis/sdk'
45280
-
45281
- export default {
45282
- templateVersion: ${TEMPLATE_VERSION},
45283
- // defaultStatus: 'dev', // Default status for new resources ('dev' | 'prod')
45284
- // dev: { port: 5170 }, // Local API port (internal development only)
45285
- } satisfies ElevasConfig
45286
- `;
45287
- }
45288
- function packageJsonTemplate(organization) {
45289
- return JSON.stringify(
45290
- {
45291
- name: organization,
45292
- private: true,
45293
- type: "module",
45294
- scripts: {
45295
- "check-types": "tsc --noEmit",
45296
- check: "elevasis-sdk check",
45297
- deploy: "elevasis-sdk deploy"
45298
- },
45299
- dependencies: {
45300
- "@elevasis/sdk": `^${SDK_VERSION}`
45301
- },
45302
- devDependencies: {
45303
- typescript: "5.9.2",
45304
- zod: "4.1.12"
45305
- }
45306
- },
45307
- null,
45308
- 2
45309
- ) + "\n";
45310
- }
45311
- function pnpmWorkspaceTemplate() {
45312
- return `packages: []
45313
- `;
45314
- }
45315
- function tsconfigTemplate() {
45316
- return JSON.stringify(
45317
- {
45318
- compilerOptions: {
45319
- target: "ES2022",
45320
- module: "ESNext",
45321
- moduleResolution: "Bundler",
45322
- strict: true,
45323
- esModuleInterop: true,
45324
- skipLibCheck: true,
45325
- forceConsistentCasingInFileNames: true,
45326
- isolatedModules: true,
45327
- outDir: "./dist"
45328
- },
45329
- include: ["src"],
45330
- exclude: ["node_modules", "dist"]
45331
- },
45332
- null,
45333
- 2
45334
- ) + "\n";
45335
- }
45336
- function envTemplate() {
45337
- return `ELEVASIS_PLATFORM_KEY=
45338
- `;
45339
- }
45340
- function npmrcTemplate() {
45341
- return `auto-install-peers = true
45342
- `;
45343
- }
45344
- function gitignoreTemplate(ctx = {}) {
45345
- let content = `node_modules/
45346
- .env
45347
- dist/
45348
- __elevasis_worker.ts
45349
- .claude/settings.local.json
45350
- .claude/memory/
45351
- package-lock.json
45352
- `;
45353
- if (ctx.hasUI) {
45354
- content += `ui/node_modules/
45355
- ui/dist/
45356
- `;
45357
- }
45358
- return content;
45359
- }
45360
- function docsIndexTemplate(organization) {
45361
- return `---
45362
- title: ${organization}
45363
- description: Documentation for the ${organization} Elevasis workspace
45364
- order: 1
45365
- ---
45366
-
45367
- # ${organization}
45368
-
45369
- An [Elevasis](https://elevasis.io) workspace built with the \`@elevasis/sdk\`.
45370
-
45371
- ## Setup
45372
-
45373
- \`\`\`bash
45374
- pnpm install
45375
- \`\`\`
45376
-
45377
- Add your API key to \`.env\`:
45378
-
45379
- \`\`\`
45380
- ELEVASIS_PLATFORM_KEY=sk_...
45381
- \`\`\`
45382
-
45383
- ## Development
45384
-
45385
- \`\`\`bash
45386
- pnpm run check # Validate resource definitions
45387
- pnpm run deploy # Bundle and deploy to platform
45388
- pnpm exec elevasis-sdk exec <resourceId> --input '...' # Execute a resource
45389
- pnpm exec elevasis-sdk resources # List deployed resources
45390
- pnpm exec elevasis-sdk describe <resourceId> # Show resource definition + schemas
45391
- pnpm exec elevasis-sdk executions <resourceId> # View execution history
45392
- \`\`\`
45393
-
45394
- ## Project Structure
45395
-
45396
- - \`elevasis.config.ts\` -- Workspace config (optional settings)
45397
- - \`src/index.ts\` -- Resource registry (aggregates from domain barrels)
45398
- - \`src/operations/\` -- Operations domain (platform-status workflow)
45399
- - \`src/example/\` -- Example domain (echo workflow -- replace with your own)
45400
- - \`src/shared/\` -- Cross-domain shared types and utilities
45401
- - \`docs/\` -- Documentation (.mdx files, deployed alongside code)
45402
- - \`.env\` -- API key for CLI authentication
45403
-
45404
- ## Resources
45405
-
45406
- ### Platform Status Workflow (\`src/operations/\`)
45407
-
45408
- A multi-step workflow that queries platform status and compiles a natural language
45409
- summary using an LLM. Demonstrates platform API usage with the \`llm\` typed adapter and \`platform.call()\`.
45410
-
45411
- \`\`\`bash
45412
- pnpm exec elevasis-sdk exec platform-status --input '{"timeRange": "24h"}'
45413
- \`\`\`
45414
-
45415
- **Input:** \`{ "timeRange": "1h" | "24h" | "7d" }\`
45416
- **Output:** \`{ "raw": object, "summary": string }\`
45417
-
45418
- ### Echo Workflow (\`src/example/\`)
45419
-
45420
- A simple workflow that echoes the input message back. Use it as a starter pattern
45421
- for new workflows:
45422
-
45423
- \`\`\`bash
45424
- pnpm exec elevasis-sdk exec echo --input '{"message": "hello"}'
45425
- \`\`\`
45426
-
45427
- **Input:** \`{ "message": string }\`
45428
- **Output:** \`{ "echo": string }\`
45429
- `;
45430
- }
45431
-
45432
- // src/cli/commands/templates/core/claude.ts
45433
- function claudeSettingsTemplate() {
45434
- return JSON.stringify(
45435
- {
45436
- autoCompact: false,
45437
- statusLine: {
45438
- type: "command",
45439
- command: "node .claude/scripts/statusline-command.js"
45440
- },
45441
- hooks: {
45442
- PreToolUse: [
45443
- {
45444
- matcher: "Write|Edit|MultiEdit|Bash",
45445
- hooks: [
45446
- {
45447
- type: "command",
45448
- command: "node .claude/hooks/enforce-sdk-boundary.mjs"
45449
- }
45450
- ]
45451
- }
45452
- ],
45453
- PostToolUse: [
45454
- {
45455
- matcher: "Write|Edit|MultiEdit",
45456
- hooks: [
45457
- {
45458
- type: "command",
45459
- command: "node .claude/hooks/post-edit-validate.mjs"
45460
- }
45461
- ]
45462
- }
45463
- ],
45464
- PostToolUseFailure: [
45465
- {
45466
- matcher: "Bash",
45467
- hooks: [
45468
- {
45469
- type: "command",
45470
- command: "node .claude/hooks/tool-failure-recovery.mjs"
45471
- }
45472
- ]
45473
- }
45474
- ]
45475
- }
45476
- },
45477
- null,
45478
- 2
45479
- ) + "\n";
45480
- }
45481
- function claudeStatuslineScriptTemplate() {
45482
- return `#!/usr/bin/env node
45483
- let input = '';
45484
- process.stdin.on('data', chunk => input += chunk);
45485
- process.stdin.on('end', () => {
45486
- const data = JSON.parse(input);
45487
- const model = data.model?.display_name || '?';
45488
- const pct = Math.floor(data.context_window?.used_percentage || 0);
45489
-
45490
- const DIM = '\\x1b[90m', RESET = '\\x1b[0m';
45491
- const GREEN = '\\x1b[32m', YELLOW = '\\x1b[33m', RED = '\\x1b[31m';
45492
-
45493
- const color = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;
45494
-
45495
- const width = 20;
45496
- const filled = Math.floor(pct * width / 100);
45497
- const empty = width - filled;
45498
- const bar = '#'.repeat(filled) + '-'.repeat(empty);
45499
-
45500
- console.log(\`\${DIM}[\${RESET}\${model}\${DIM}]\${RESET} \${color}\${bar}\${RESET} \${pct}%\`);
45501
- });
45502
- `;
45503
- }
45504
- function claudeSdkBoundaryHookTemplate() {
45505
- return String.raw`#!/usr/bin/env node
45506
- // enforce-sdk-boundary.mjs
45507
- // Blocks file modifications (Write, Edit, MultiEdit, destructive Bash) outside the project root.
45508
- // Git, gh, and other CLI tools are NOT blocked -- the agent can use them freely.
45509
-
45510
- import { resolve, normalize } from "node:path";
45511
- import { appendFileSync, mkdirSync } from "node:fs";
45512
-
45513
- const LOG_DIR = (process.env.CLAUDE_PROJECT_DIR ?? process.cwd()) + "/.claude/logs";
45514
- const LOG_FILE = LOG_DIR + "/boundary-hook.log";
45515
-
45516
- function log(msg) {
45517
- try {
45518
- mkdirSync(LOG_DIR, { recursive: true });
45519
- appendFileSync(LOG_FILE, "[" + new Date().toISOString() + "] " + msg + "\n");
45520
- } catch {}
45521
- }
45522
-
45523
- function deny(reason) {
45524
- log("DENY -- " + reason);
45525
- process.stdout.write(
45526
- JSON.stringify({
45527
- hookSpecificOutput: {
45528
- hookEventName: "PreToolUse",
45529
- permissionDecision: "deny",
45530
- permissionDecisionReason: reason,
45531
- },
45532
- })
45533
- );
45534
- }
45535
-
45536
- try {
45537
- const chunks = [];
45538
- for await (const chunk of process.stdin) chunks.push(chunk);
45539
- const input = JSON.parse(Buffer.concat(chunks).toString());
45540
-
45541
- const projectDir = normalize(process.env.CLAUDE_PROJECT_DIR ?? process.cwd());
45542
- const sep = process.platform === "win32" ? "\\" : "/";
45543
- const prefix = projectDir.endsWith("\\") || projectDir.endsWith("/") ? projectDir : projectDir + sep;
45544
-
45545
- function isOutside(filePath) {
45546
- const target = normalize(resolve(filePath));
45547
- return !target.startsWith(prefix) && target !== projectDir;
45548
- }
45549
-
45550
- if (input.tool_name === "Bash") {
45551
- const cmd = input.tool_input?.command ?? "";
45552
-
45553
- // Path-scoped blocks -- destructive commands or redirects outside project root
45554
- const winPaths = cmd.match(/(?<![A-Za-z])[A-Za-z]:[/\\][^\s"'|;&)]+/g) || [];
45555
- const unixPaths = cmd.match(/(?<=\s|^|"|')\/[^\s"'|;&)]+/g) || [];
45556
- const allPaths = [...winPaths, ...unixPaths]
45557
- .map((p) => p.trim())
45558
- .filter((p) => !p.startsWith("/dev/"));
45559
-
45560
- const outsidePaths = allPaths.filter((p) => isOutside(p));
45561
-
45562
- if (outsidePaths.length > 0) {
45563
- const hasDestructiveCmd = /(?<![-])\b(rm|rmdir|del|unlink|mv|cp|touch|mkdir|chmod|chown|truncate|tee|dd|install)\b/.test(cmd);
45564
- const hasInPlaceEdit = /\bsed\b.*\s-i/.test(cmd);
45565
- const hasRedirect = />{1,2}\s*[^\s&>]/.test(cmd);
45566
-
45567
- const hasTempPath = outsidePaths.some(
45568
- (p) => /[/\\]tmp[/\\]/i.test(p) || /[/\\]Temp[/\\]/i.test(p)
45569
- );
45570
-
45571
- if (hasDestructiveCmd || hasInPlaceEdit || hasRedirect) {
45572
- const instead = hasTempPath
45573
- ? "INSTEAD: Use pipes instead of temp files: cmd 2>&1 | grep pattern not cmd > /tmp/out.txt. All file writes must target paths inside the project."
45574
- : "INSTEAD: Only files within the project directory may be modified. Ask the user to run this command manually if external paths are needed.";
45575
-
45576
- deny(
45577
- "BLOCKED: destructive command references path(s) outside the project: " + outsidePaths.join(", ") + ".\n" +
45578
- "WHY: File modifications outside the project boundary are not allowed.\n" +
45579
- instead
45580
- );
45581
- }
45582
- }
45583
- } else {
45584
- // Write, Edit, MultiEdit: check file_path
45585
- const filePath = input.tool_input?.file_path;
45586
- if (filePath && isOutside(filePath)) {
45587
- deny(
45588
- "BLOCKED: " + filePath + " is outside the project.\n" +
45589
- "WHY: [" + (input.tool_name ?? "Unknown") + "] file operations outside the project boundary are not allowed.\n" +
45590
- "INSTEAD: Only files within the project directory may be modified."
45591
- );
45592
- }
45593
- }
45594
- } catch (err) {
45595
- log("ERROR: " + err.message + "\n" + err.stack);
45596
- }
45597
-
45598
- process.exit(0);
45599
- `;
45600
- }
45601
- function claudeMdTemplate(ctx = {}) {
45602
- return `<!-- initialized: false -->
45603
-
45604
- # CLAUDE.md
45605
-
45606
- ## Session Initialization
45607
-
45608
- At the start of every session:
45609
-
45610
- 0. Check the \`<!-- initialized: ... -->\` flag at the top of this file.
45611
- If \`false\`, read \`.claude/commands/init.md\` and run the \`/init\` flow.
45612
- After initialization completes, change the flag to \`<!-- initialized: true -->\`.
45613
- If \`true\`, proceed with steps below.
45614
- 1. Read \`.claude/memory/profile/skills.md\` -- adapt all responses to the user's
45615
- assessed skill levels (see Interaction Guidance below).
45616
- 2. Read \`.claude/memory/index.md\` -- drill into relevant topic files as needed.
45617
- Balance context relevance against token usage.
45618
- 3. Check installed \`@elevasis/sdk\` template version against \`templateVersion\`
45619
- in \`elevasis.config.ts\`. If newer, notify and suggest \`/fix\`.
45620
- 4. If \`.claude/memory/\` does not exist, suggest \`/init\`.
45621
- 5. If user Platform Navigation level is none (from skills.md) and
45622
- \`.claude/memory/tutorial-progress.md\` does not exist, suggest \`/tutorial\`.
45623
- If tutorial-progress.md exists and Phase is not complete, mention that the
45624
- tutorial has more to explore.
45625
-
45626
- Do this silently. Do not narrate the steps to the user.
45627
-
45628
- ## Identity
45629
-
45630
- You are the development agent for an Elevasis workspace. You help the user
45631
- design, build, and deploy business automation workflows on the Elevasis
45632
- platform. You are not just a code assistant -- you are a guide who translates
45633
- business intent into working automation.
45634
-
45635
- Your users range from experienced developers to business operators who have
45636
- never written code. Read the user's skill profile at session start and adapt
45637
- every interaction -- vocabulary, code completeness, explanation depth, and
45638
- proactivity -- to their assessed levels.
45639
-
45640
- ## Navigation
45641
-
45642
- | Resource | Location | When to Load |
45643
- | --- | --- | --- |
45644
- | Workspace concepts | \`reference/concepts.mdx\` | User asks "what is...?" or needs conceptual grounding |
45645
- | SDK patterns and examples | \`reference/resources/patterns.mdx\` | Building or modifying a workflow |
45646
- | Platform tool catalog | \`reference/platform-tools/index.mdx\` | Connecting to external services |
45647
- | CLI reference | \`reference/cli.mdx\` | Running execution/platform operations |
45648
- | Credential model | \`reference/platform-tools/index.mdx\` | Setting up integrations or credential security |
45649
- | Interaction guidance | \`reference/framework/interaction-guidance.mdx\` | Unsure how to adapt for a skill combination |
45650
- | Error history | \`.claude/memory/errors/index.md\` | Debugging errors, checking past fixes |
45651
- | Command View model | \`reference/deployment/command-center.mdx\` | Deploying or building resources that invoke other resources |
45652
- | Command Center UI reference | \`reference/deployment/command-center.mdx\` | User asks about post-deployment UI or Command Center navigation |
45653
- | SDK error reference | \`reference/troubleshooting.mdx\` | Unknown error not in workspace memory |
45654
- | Project map | \`docs/project-map.mdx\` | Session start, project orientation |
45655
- | Resource inventory | \`docs/resource-map.mdx\` | Finding a specific resource by name or ID |
45656
- | Project priorities | \`docs/priorities.mdx\` | Deciding what to work on next |
45657
- | User profile and skills | \`.claude/memory/profile/skills.md\` | Session start (mandatory) |
45658
- | Cross-session memory | \`.claude/memory/index.md\` | Session start, recalling past context |${ctx.hasUI ? `
45659
- | UI app source | \`ui/src/\` | Modifying the frontend, adding routes or components |` : ""}
45660
-
45661
- All \`reference/\` paths resolve to \`node_modules/@elevasis/sdk/reference/\`.
45662
-
45663
- ## Elevasis CLI
45664
-
45665
- **MANDATORY:** Use the \`elevasis-sdk\` CLI for all execution/platform operations -- never \`curl\` or any other tool.
45666
-
45667
- Use pnpm scripts for check and deploy (they resolve the local binary automatically):
45668
-
45669
- - \`pnpm run check\` -- validate resource definitions without deploying
45670
- - \`pnpm run deploy\` -- deploy to the platform
45671
-
45672
- Use \`pnpm exec elevasis-sdk\` for runtime commands (resolves the locally installed binary):
45673
-
45674
- - \`pnpm exec elevasis-sdk exec <resource-id> --input '{...}'\` -- run a resource synchronously
45675
- - \`pnpm exec elevasis-sdk exec <resource-id> --input '{...}' --async\` -- run async, returns execution ID
45676
- - \`pnpm exec elevasis-sdk execution <resource-id> <execution-id>\` -- inspect execution detail
45677
- - \`pnpm exec elevasis-sdk rename <old-id> --to <new-id> [--execute] [--prod]\` -- rename a resource ID across platform tables (dry run by default)
45678
-
45679
- Organization is derived from your API key -- no org prefix needed in the resource ID.
45680
- For full CLI reference: \`reference/cli.mdx\`
45681
-
45682
- ## Rules
45683
-
45684
- SDK patterns (imports, source structure, platform tools) are auto-loaded from
45685
- \`.claude/rules/sdk-patterns.md\`. Project-specific patterns live in
45686
- \`.claude/rules/workspace-patterns.md\`.
45687
-
45688
- - Documentation goes in \`docs/\` as \`.mdx\` files
45689
- - Resources are not visible in the Command Center until deployed. Always deploy before directing users to verify in the UI.
45690
-
45691
- ### Error Handling
45692
-
45693
- When an error occurs:
45694
- 1. Check \`.claude/memory/errors/\` first for past fixes
45695
- 2. If new, check \`reference/troubleshooting.mdx\`
45696
- 3. After resolving, record in \`.claude/memory/errors/\` with context and fix
45697
- 4. If an error recurs 3+ times, add a rule to \`.claude/rules/workspace-patterns.md\`${ctx.hasUI ? `
45698
-
45699
- ### UI App (\`ui/\`)
45700
-
45701
- - \`ui/\` is a standalone Vite + React app with its own \`package.json\` -- not part of the pnpm workspace
45702
- - Import from \`@elevasis/sdk-ui\`, never from \`@elevasis/sdk\` or \`@repo/ui\`
45703
- - Dev server runs on port 5100: \`cd ui && pnpm dev\`
45704
- - Set \`VITE_WORKOS_CLIENT_ID\` in \`ui/.env\` before running
45705
- - \`ElevasisCoreProvider\` (headless, no Mantine dependency) is pre-configured in \`ui/src/App.tsx\` with \`auth={{ mode: 'oauth', clientId, redirectUri }}\`, \`apiUrl="http://localhost:5170"\`, and \`theme={{ colorScheme: 'dark', preset: 'default' }}\`
45706
- - To use pre-built Mantine components from \`@elevasis/sdk-ui\`, switch to \`ElevasisUIProvider\` and install \`@mantine/core\` and \`@mantine/hooks\`
45707
- - OAuth redirect is handled by the \`AuthRedirect\` component at \`/auth-redirect\` -- it uses \`useAuthContext()\` from \`@elevasis/sdk-ui/auth\` and navigates home once \`user\` is set
45708
- - API must be running on port 5170 for the UI to work (\`pnpm --filter api dev\` from the platform monorepo)` : ""}
45709
-
45710
- ## Interaction Guidance
45711
-
45712
- Adapt your communication based on \`.claude/memory/profile/skills.md\`.
45713
- Read the profile at session start (Step 1). Adjust every response --
45714
- vocabulary, code completeness, explanation depth, and proactivity --
45715
- based on what you find.
45716
-
45717
- - Match vocabulary to the user's level. Avoid jargon for beginners;
45718
- be precise for experts. Define technical terms in parentheses the first time.
45719
- - Provide step-by-step UI navigation for users with Platform Navigation below comfortable.
45720
- Reference exact page names and paths until they are oriented.
45721
- - Explain "why" before "how" for users new to automation.
45722
- - For users comfortable with the platform, focus on SDK-specific patterns and advanced operations.
45723
- - Leverage domain expertise -- if the user knows sales but not code,
45724
- ask for business process descriptions and translate.
45725
- - When growth is observed, note it in the skills.md Growth Log.
45726
-
45727
- For detailed per-dimension adaptation rules, read
45728
- \`reference/framework/interaction-guidance.mdx\`.
45729
-
45730
- ## Commands
45731
-
45732
- | Command | Purpose |
45733
- | --- | --- |
45734
- | \`/init\` | First-run workspace setup and competency assessment |
45735
- | \`/status\` | Project health dashboard |
45736
- | \`/fix\` | Maintenance, drift repair, and SDK upgrade |
45737
- | \`/deploy\` | Full deploy pipeline (validate \u2192 deploy \u2192 verify) |
45738
- | \`/docs\` | Browse, create, and verify permanent documentation |
45739
- | \`/tutorial\` | Progressive learning path (21 items across 4 sections) |
45740
-
45741
- ## Skills
45742
-
45743
- Skills auto-trigger based on conversation context. You do not need to invoke them manually.
45744
-
45745
- | Skill | Triggers When |
45746
- | --- | --- |
45747
- | \`work\` | You say /work, ask to track or save progress across sessions, ask what you were working on, want to create/resume/complete a task doc, or say you are done for today. Also proactively save when conversation is heavy or 2+ steps completed |
45748
- | \`creds\` | You mention credentials, API keys, secrets, webhook secrets, or setting up integrations |
45749
- | \`diagnostics\` | An execution fails, user asks why something failed, user mentions runtime errors, or agent observes a failed execution |
45750
-
45751
- ## Maintaining Memory
45752
-
45753
- ### What Memory Is
45754
-
45755
- Memory stores persistent state and observations that inform future sessions.
45756
- Every file must contain data the agent writes and later reads to make better
45757
- decisions. File names must clearly indicate they contain state or data
45758
- (e.g., \`deployment-state.md\`, \`tutorial-progress.md\`, \`skills.md\`).
45759
-
45760
- Priorities live in \`docs/priorities.mdx\`, not in memory. Memory is for internal
45761
- agent state; priorities are project documentation the user may also read.
45762
-
45763
- ### What Memory Is NOT
45764
-
45765
- Do not store in \`.claude/memory/\`:
45766
- - Instructions, commands, or procedures (belong in \`.claude/commands/\`)
45767
- - Reference documentation or teaching material (belong in \`docs/\` or SDK reference)
45768
- - Templates or boilerplate code
45769
- - Conversation transcripts or chat history
45770
- - Anything the agent reads but never updates
45771
-
45772
- ### Structure
45773
-
45774
- - \`.claude/memory/index.md\` is the root -- maps to topic files and subdirectories
45775
- - Every subdirectory has its own \`index.md\` mapping to children
45776
- - Start at the root index and drill down
45777
- - When a file outgrows a single document, split into a subdirectory
45778
-
45779
- ### Pruning
45780
-
45781
- - Keep ~20 recent entries per table; drop stale patterns (30+ days, no recurrence)
45782
- - If a file/index references a missing child, remove the row
45783
- - If a child exists without an index entry, add it
45784
- - If an error pattern recurs 3+ times, promote to Rules above
45785
- `;
45786
- }
45787
- function claudeTutorialCommandTemplate() {
45788
- return `# /tutorial command
45789
-
45790
- You are a tutorial guide for this Elevasis workspace.
45791
-
45792
- ## Context
45793
-
45794
- Read \`.claude/memory/profile/skills.md\` first. The \`automation\` skill level
45795
- controls which docs you load and which lesson variant you deliver.
45796
-
45797
- **automation: none**
45798
- - Load from \`reference/concepts.mdx\`: Glossary, What is a Workflow,
45799
- Platform Tools Overview only. Skip Zod, Execution Model, Design Decisions.
45800
- - Load \`reference/deployment/command-center.mdx\` for UI-first teaching.
45801
- - Do NOT load \`reference/resources/patterns.mdx\` or
45802
- \`reference/platform-tools/adapters.mdx\` during core lessons.
45803
-
45804
- **automation: low-code**
45805
- - Load all sections of \`reference/concepts.mdx\`.
45806
- - Load \`reference/resources/patterns.mdx\` with Zapier/Make mapping in mind.
45807
- - Load \`reference/platform-tools/adapters.mdx\` on-demand (when tools are used).
45808
-
45809
- **automation: custom**
45810
- - Load all docs listed per-lesson and per-module as specified below.
45811
-
45812
- Read \`.claude/memory/tutorial-progress.md\` to check current lesson progress.
45813
-
45814
- ## Invocation
45815
-
45816
- \`/tutorial\` -- ALWAYS shows the main menu first. Never silently auto-resumes without giving the user a choice. See ## Menu section for the exact menu format.
45817
-
45818
- ## Menu
45819
-
45820
- When \`/tutorial\` is invoked:
45821
-
45822
- 1. Read \`.claude/memory/tutorial-progress.md\` (if it exists)
45823
- 2. Display the full menu table. Fill in progress indicators from the progress file.
45824
- 3. User picks a number -> start or resume that item directly. No track gating.
45825
-
45826
- Progress indicators: \`[ ]\` not started, \`[>]\` in progress, \`[x] YYYY-MM-DD\` complete.
45827
-
45828
- Example (first time, no progress):
45829
-
45830
- \`\`\`
45831
- Elevasis Tutorial
45832
- ==================
45833
-
45834
- INTRODUCTION 0/4
45835
- 1 Welcome & Orientation [ ]
45836
- 2 How This Workspace Works [ ]
45837
- 3 Project Commands (/init, /status, /fix, /deploy) [ ]
45838
- 4 /work and /docs [ ]
45839
-
45840
- CORE CONCEPTS 0/6
45841
- 5 Your First Custom Workflow [ ]
45842
- 6 Understanding Data (Schemas) [ ]
45843
- 7 Using Platform Tools [ ]
45844
- 8 Multi-Step Workflows [ ]
45845
- 9 Decision Points [ ]
45846
- 10 Going to Production [ ]
45847
-
45848
- ADVANCED MODULES 0/9
45849
- 11 Human-in-the-Loop [ ]
45850
- 12 Task Scheduling [ ]
45851
- 13 Notification System [ ]
45852
- 14 Real-World Integrations [ ]
45853
- 15 Error Handling Mastery [ ]
45854
- 16 Advanced Workflows [ ]
45855
- 17 Resource Composition [ ]
45856
- 18 LLM Integration [ ]
45857
- 19 AI Agents [ ]
45858
-
45859
- ADVANCED WORKSPACE 0/2
45860
- 20 Rules, Memory, and Customization [ ]
45861
- 21 Template Lifecycle [ ]
45862
-
45863
- Pick a number to start.
45864
- \`\`\`
45865
-
45866
- Always show this full table when \`/tutorial\` is invoked. Populate progress
45867
- indicators from completed/current state. \`"status"\` -> show the same table.
45868
-
45869
- ## Progress Logic
45870
-
45871
- 1. Read \`.claude/memory/tutorial-progress.md\`
45872
- 2. Show the full menu table (## Menu) with progress filled in
45873
- 3. User picks a number -> start or resume that lesson or module directly
45874
- 4. After user confirms readiness: mark done in progress file, show updated menu table
45875
- 5. All 21 items complete -> congratulate, suggest exploring docs/ or /work
45876
-
45877
- ## Lesson Flow
45878
-
45879
- Each lesson follows this flow:
45880
- 1. Announce lesson title and what they'll learn (1-2 sentences)
45881
- 2. Explain the concept (read docs per skill level, adapt to user)
45882
- 3. Guide user to build or modify something (agent writes all code for automation: none)
45883
- 4. Verify it works (CLI primary for all levels; Command Center for visual review -- Command View, Execution Logs)
45884
- 5. Celebrate success and ask: "Any questions, or ready to continue?"
45885
- 6. Once the user confirms, record observations in \`.claude/memory/tutorial-progress.md\`
45886
-
45887
- ## Lessons
45888
-
45889
- **Item 1: Welcome & Orientation**
45890
-
45891
- When automation is none:
45892
- Skip the file tour. Start with what Elevasis does for their business -- use analogies
45893
- from \`reference/framework/interaction-guidance.mdx\` (recipe, assembly line, kitchen
45894
- appliance). Explain deployment plainly: "You write the recipe here, then deploy it so
45895
- it's live." Deploy the starter echo workflow (\`elevasis-sdk check\` + \`elevasis-sdk deploy\`),
45896
- THEN tour the Command Center so the user sees populated pages, not empty ones. Tour:
45897
- Command View (echo node), Execution Logs (result).
45898
- Observation focus: automation value understanding, Command Center comfort.
45899
-
45900
- When automation is low-code or custom:
45901
- Tour project files: src/index.ts (registry), src/example/echo.ts (starter
45902
- workflow), src/operations/platform-status.ts (platform API example),
45903
- elevasis.config.ts, .env, docs/. Explain the execution model.
45904
- Verify: run \`elevasis-sdk resources\`. Then open the Command Center and tour the
45905
- main pages: Command View (resource graph), Execution Logs.
45906
- Point out the echo workflow node in Command View.
45907
- Observation focus: cloud deployment model, UI navigation comfort.
45908
-
45909
- **Item 2: How This Workspace Works**
45910
-
45911
- When automation is none:
45912
- "This workspace comes with a built-in assistant that knows your project, your tools,
45913
- and your goals. Let me show you how it's set up." Open CLAUDE.md and explain in
45914
- plain terms: it's the agent's instruction sheet. Point out the commands in the
45915
- Commands table. Show /status, /tutorial. Explain the work and creds skills as
45916
- "the assistant automatically helps when you mention tasks or API keys." Tour the memory folder
45917
- at a high level -- "this is where the agent stores what it learns about your project."
45918
- Verify: Ask the user a question about their business goal and show how the agent
45919
- references their profile in the answer.
45920
- Observation focus: agent-as-assistant concept, CLAUDE.md as instruction sheet.
45921
-
45922
- When automation is low-code:
45923
- Read CLAUDE.md and walk through each section. Explain: what the agent reads on
45924
- session start, how the navigation table works, what the Skills section means.
45925
- Explain the three commands briefly and the two auto-triggering skills (work, creds). Show that the agent has memory: open
45926
- \`.claude/memory/profile/skills.md\` and show their own profile -- "every session,
45927
- the agent reads this and adapts." Explain the initialized flag.
45928
- Verify: Run /status to see project status.
45929
- Observation focus: memory system concept, session initialization flow.
45930
-
45931
- When automation is custom:
45932
- Read CLAUDE.md in full. Explain the session initialization sequence: CLAUDE.md ->
45933
- navigation table -> memory files -> context loading. Walk through: Commands section
45934
- (3 commands + work and creds skills), Rules section (auto-loaded based on file paths), Skills
45935
- section (auto-triggered by content patterns). Point out the initialized flag and
45936
- explain how /init set it.
45937
- Verify: Run /status to see project status; observe which fields it reports.
45938
- Observation focus: initialization model, command-vs-rule-vs-skill distinction.
45939
-
45940
- **Item 3: Project Commands (/init, /status, /fix, /deploy)**
45941
-
45942
- When automation is none:
45943
- "Think of /status as your project dashboard -- it shows what's healthy and what needs
45944
- attention." Run /status and narrate the output in plain language: what each field means.
45945
- Explain /fix as "the agent tidies up and applies updates."
45946
- Explain /deploy as "the agent publishes your changes in one step." Mention the
45947
- diagnostics skill: "If something goes wrong, the assistant automatically investigates."
45948
- Verify: Run /status. Narrate the output together.
45949
- Observation focus: project lifecycle concept, dashboard reading.
45950
-
45951
- When automation is low-code:
45952
- Show all project commands with their purpose. Map to familiar concepts: /fix is
45953
- like "repair this Zap" in Zapier; /deploy is a one-command publish pipeline.
45954
- Walk through /status output: template version (SDK template your workspace
45955
- uses), SDK version (installed package), profile summary, drift check. Mention the
45956
- diagnostics skill auto-triggers on execution failures.
45957
- Verify: Run /status and interpret each field together.
45958
- Observation focus: deploy pipeline understanding, version tracking.
45959
-
45960
- When automation is custom:
45961
- Read each command file in \`.claude/commands/\`: init.md (/init -- first-run setup
45962
- with assessment), status.md (/status -- health dashboard), fix.md (/fix -- drift
45963
- repair + SDK upgrade + rules health), deploy.md (/deploy -- 9-step pipeline: check,
45964
- typecheck, docs, git, deploy, project-map, verify, state, push). Explain the
45965
- diagnostics skill (auto-triggered on execution failures for runtime debugging).
45966
- Explain the merge strategy for CLAUDE.md and commands. Note the template access
45967
- model: templates read from @elevasis/sdk/templates subpath.
45968
- Verify: Run /status to see project status. Identify what a version mismatch looks like.
45969
- Observation focus: full lifecycle coverage, pipeline internals.
45970
-
45971
- **Item 4: /work and /docs**
45972
-
45973
- When automation is none:
45974
- "You can ask the assistant to track work across conversations. Just say /work and tell it
45975
- what you're working on -- it figures out the rest. It'll save your progress automatically,
45976
- and next session you just say /work to pick up where you left off." Walk through the
45977
- concept without deep command details. Then introduce /docs:
45978
- "When a task is done, the assistant will ask if you want to finalize it -- that moves it
45979
- to docs/ permanently. /docs helps you find and read what's there -- like a notebook for
45980
- your project." Run /docs (no args) to show the docs/ overview together.
45981
- Verify: Run \`/work\` and describe "practice task", see it created automatically.
45982
- Then run /docs to see the docs/ structure.
45983
- Observation focus: persistence concept, cross-session continuity, docs as permanent notes.
45984
-
45985
- When automation is low-code:
45986
- Show /work as intent-driven: the agent detects whether to create, resume, or save based
45987
- on context. Create happens when you describe new work, resume when you pick an existing
45988
- task, save happens automatically when progress is made. Complete is the only action that
45989
- asks permission first.
45990
- Then introduce /docs: "/docs is for permanent knowledge -- things that don't expire. Use
45991
- /docs create to document a workflow or integration. Use /docs verify to check if your
45992
- docs match the current code." Explain the boundary: /work manages in-progress/, /docs
45993
- manages permanent docs/.
45994
- Verify: Run \`/work\` and describe "practice task", see auto-create. Make some changes,
45995
- then notice auto-save. Then run /docs to browse docs/.
45996
- Observation focus: intent-driven task tracking, /work vs /docs separation.
45997
-
45998
- When automation is custom:
45999
- Read \`.claude/skills/work/SKILL.md\`. Full /work coverage:
46000
- Intent detection table (list, create, resume, save auto-invoked; complete always suggests).
46001
- Task doc anatomy: kebab-case filename, frontmatter with status, Objective/Plan/Progress/
46002
- Resume Context sections. Auto-save behavior: triggers on heavy context, wrap-up signals,
46003
- 2+ steps completed. Resolution order for resume: number, keyword match, single in-progress.
46004
- Then read \`.claude/commands/docs.md\`. Cover /docs operations:
46005
- /docs (default): browse permanent docs/, categorized with read-only auto-generated files
46006
- separate; /docs create: interview-driven, resource-aware doc creation from src/ code
46007
- analysis; /docs verify: cross-references resource IDs, schema fields, platform tools in
46008
- docs against src/ -- standalone analog of /fix step 5.
46009
- Explain the relationship: /work owns docs/in-progress/ (task lifecycle), completing a task
46010
- moves docs to permanent location, /docs browses and verifies what's there.
46011
- Verify: Create a task via /work, make progress, observe auto-save, then run /work complete
46012
- to move it. Run /docs to see it in the permanent docs/ listing.
46013
- Observation focus: intent detection, auto-save behavior, /work-to-/docs handoff, docs verification.
46014
-
46015
- **Item 5: Your First Custom Workflow**
46016
-
46017
- When automation is none:
46018
- Frame the workflow as "a recipe." Use plain language: "settings" not "config",
46019
- "what data it needs" not "contract", "instructions" not "steps", "where it starts"
46020
- not "entryPoint." Agent writes all code changes. Agent runs \`elevasis-sdk exec\` to verify
46021
- and narrates the result in plain terms.
46022
- Observation focus: recipe-to-result connection.
46023
-
46024
- When automation is low-code or custom:
46025
- Modify the echo workflow. Walk through each part: config, contract, steps,
46026
- entryPoint. Deploy: \`elevasis-sdk check\` then \`elevasis-sdk deploy\`. Test with
46027
- \`elevasis-sdk exec echo --input '{"message":"hello"}'\`. Then open the Execution
46028
- Runner in the Command Center, find the echo workflow, fill out the form, and
46029
- run it from the UI. Compare the result to the CLI output.
46030
- Observation focus: deployment-to-execution loop, TypeScript syntax comfort.
46031
-
46032
- **Item 6: Understanding Data (Schemas)**
46033
-
46034
- When automation is none:
46035
- Frame as "What information does your automation need?" Describe types in plain English:
46036
- text, number, yes/no, a choice from a list. NO Zod, no z.string(), no z.infer(), no
46037
- code shown. Agent reads identity.md goals and writes the workflow schema. Agent runs
46038
- \`elevasis-sdk exec\` with sample input and narrates the result.
46039
- Observation focus: data-to-input connection, required vs optional understanding.
46040
-
46041
- When automation is low-code:
46042
- "Field mapping like Zapier, but with validation." Show Zod types briefly. Demonstrate
46043
- how \`.describe()\` documents each field. Build schema based on identity.md goals.
46044
- After deploy, run with \`elevasis-sdk exec --input '{...}'\` to verify each field.
46045
- Observation focus: schema-to-input mapping, optional fields, types.
46046
-
46047
- When automation is custom:
46048
- Explain schemas in plain English (concepts page). Show common Zod types.
46049
- Explain \`z.infer\`. Build a new workflow with real-world input schema based
46050
- on the user's goals (read .claude/memory/profile/identity.md). After deploy,
46051
- run with \`elevasis-sdk exec --input '{...}'\` to verify the schema and inspect
46052
- the execution output.
46053
- Observation focus: schema-to-input mapping, optional fields, types.
46054
-
46055
- **Item 7: Using Platform Tools**
46056
-
46057
- When automation is none:
46058
- Frame as "Connecting your automation to a service you already use." Pick ONE
46059
- service from identity.md tools. Agent makes the code edit -- no adapter or
46060
- singleton explanation, no imports shown. Guide credential creation step-by-step
46061
- via Command Center UI (Settings > Credentials). Show where the connection appears
46062
- in Command View after deploy.
46063
- Observation focus: service-connection concept, credential comfort.
46064
-
46065
- When automation is low-code or custom:
46066
- Explain platform tools (concepts page). Browse available tools via
46067
- reference/platform-tools/index.mdx. Pick a tool based on user's goals.
46068
- Build: add a tool step using typed adapters (preferred) or platform.call().
46069
- Show adapter pattern: \`const attio = createAttioAdapter('cred')\`.
46070
- Show singleton pattern: \`import { scheduler, llm } from '@elevasis/sdk/worker'\`.
46071
- Guide credential creation: for API keys, use the \`creds\` skill or Settings >
46072
- Credentials in the Command Center. For OAuth credentials, the UI is required.
46073
- If using the approval tool, note that pending requests surface in Command Queue.
46074
- See reference/platform-tools/adapters.mdx for full API.
46075
- Observation focus: credential setup (CLI + UI), async/await.
46076
-
46077
- **Item 8: Multi-Step Workflows**
46078
-
46079
- When automation is none:
46080
- Frame as "Step 1 passes its result to Step 2, like a relay race." Command View is
46081
- PRIMARY teaching tool -- show the visual graph before explaining code. Agent builds
46082
- the 2-step workflow. Agent runs \`elevasis-sdk exec\` to verify and shows output flow.
46083
- User opens Command View to see the two nodes + arrow. Code is secondary.
46084
- Observation focus: relay-race concept, visual graph comprehension.
46085
-
46086
- When automation is low-code or custom:
46087
- Chain steps with StepType.LINEAR. Build a 2-step workflow. Explain data
46088
- flow between steps. Deploy and test. Then open the Command View and show the
46089
- relationship edges between resources. Explain how declared relationships map
46090
- to the visual graph.
46091
- Observation focus: data flow reasoning, relationship visualization.
46092
-
46093
- **Item 9: Decision Points**
46094
-
46095
- When automation is none:
46096
- Frame as "If the customer is VIP, do this -- otherwise, do that." No StepType.CONDITIONAL
46097
- jargon -- focus on the concept, not the implementation. Agent adds the condition.
46098
- Agent runs \`elevasis-sdk exec\` for both paths. Open Execution Logs to see which
46099
- path ran. Guide log navigation step-by-step.
46100
- Observation focus: branching concept understanding, log navigation.
46101
-
46102
- When automation is low-code or custom:
46103
- Conditional routing with StepType.CONDITIONAL. Add a condition to the
46104
- multi-step workflow from Lesson 5. Test both paths. After testing, open
46105
- Execution Logs in the Command Center, filter by the resource, and show how
46106
- each path appears in the log detail (step trace, input/output).
46107
- Observation focus: branching logic reasoning, execution log interpretation.
46108
-
46109
- **Item 10: Going to Production**
46110
-
46111
- When automation is none:
46112
- Frame as "draft vs live" not "dev vs production." Error handling: "when something
46113
- goes wrong with your data" / "when a connected service fails" -- no type names.
46114
- Task Scheduler and Knowledge Base stay as-is (UI-friendly already). Open Deployments
46115
- page to show version is active.
46116
- Observation focus: draft/live concept, readiness for independent Command Center use.
46117
-
46118
- When automation is low-code or custom:
46119
- Change status from dev to production. Cover error handling: try/catch,
46120
- ExecutionError, PlatformToolError. Create a schedule in Task Scheduler (use
46121
- Recurring type for a cron schedule). If docs/ has pages, show Knowledge Base.
46122
- Open Deployments page to confirm the latest version is active. Show CLI
46123
- monitoring: elevasis-sdk executions, elevasis-sdk execution. Suggest next steps.
46124
- Observation focus: readiness for independent operation (CLI + UI).
46125
-
46126
- ## Module Menu
46127
-
46128
- Module order (items 11-19 in the main menu): hitl, schedules, notifications,
46129
- integrations, error-handling, workflows, composition, llm, agents.
46130
-
46131
- After completing a module, show the updated full menu table (## Menu).
46132
-
46133
- ## Module Flow
46134
-
46135
- Each module follows this flow:
46136
- 1. Announce module title and what they'll build (1-2 sentences)
46137
- 2. Read the listed SDK reference docs for teaching context
46138
- 3. Guide user to build a resource exercising the module's concepts
46139
- 4. Verify it works (CLI + Command Center where applicable)
46140
- 5. Record observations in \`.claude/memory/tutorial-progress.md\`
46141
- 6. Show updated full menu table (## Menu)
46142
-
46143
- ## Modules
46144
-
46145
- **Module: hitl -- Human-in-the-Loop**
46146
- Read: \`reference/deployment/command-center.mdx\` (Command Queue section).
46147
- Build: Add an approval gate using \`approval.requestApproval()\`. Test full lifecycle:
46148
- trigger, see pending in Command Queue, approve/reject, observe resume.
46149
- Key concepts: approval adapter, pending state, Command Queue UI, resume on decision.
46150
- Verify: Trigger workflow, open Command Queue, approve, confirm completion.
46151
-
46152
- **Module: schedules -- Task Scheduling**
46153
- Read: \`reference/deployment/command-center.mdx\` (Task Scheduler section).
46154
- Build: Create all three schedule types (Recurring cron, Relative delay, Absolute
46155
- datetime). Use \`scheduler\` adapter for in-workflow scheduling.
46156
- Key concepts: schedule types, cron syntax, scheduler adapter, Task Scheduler UI.
46157
- Verify: Create each type in Task Scheduler, confirm scheduled execution in Execution Logs.
46158
-
46159
- **Module: notifications -- Notification System**
46160
- Read: \`reference/platform-tools/adapters.mdx\` (notifications, email singletons).
46161
- Build: Add notification and email steps to a workflow. Send alerts on completion.
46162
- Key concepts: notifications singleton, email singleton, alert patterns.
46163
- Verify: Run workflow, check notification in Command Center, confirm email received.
46164
-
46165
- **Module: integrations -- Real-World Integrations**
46166
- Read: \`reference/platform-tools/index.mdx\`, \`reference/platform-tools/adapters.mdx\`,
46167
- \`reference/platform-tools/index.mdx\`.
46168
- Build: Pick a real integration adapter based on user's goals (read \`identity.md\`).
46169
- Set up credential (OAuth via UI, API key via CLI). Build end-to-end integration workflow.
46170
- Key concepts: adapter pattern, credential scoping, error handling for external calls.
46171
- Verify: Run workflow with real credential, confirm external service call, test error
46172
- handling with invalid credential.
46173
-
46174
- **Module: error-handling -- Error Handling Mastery**
46175
- Read: \`reference/resources/patterns.mdx\` (error handling),
46176
- \`reference/troubleshooting.mdx\`.
46177
- Build: Create a workflow demonstrating all three error types. Add try/catch,
46178
- \`context.logger\`, and error recovery.
46179
- Key concepts: ExecutionError, PlatformToolError, ToolingError, recovery patterns.
46180
- Verify: Trigger each error type, confirm messages in Execution Logs with correct
46181
- categorization.
46182
-
46183
- **Module: workflows -- Advanced Workflows**
46184
- Read: \`reference/resources/patterns.mdx\` (execution store, logging, organizing).
46185
- Build: Refactor an existing workflow to use \`context.store\` for cross-step data,
46186
- \`context.logger\` for structured logging, and organize into a domain directory.
46187
- Add advanced schema patterns (nested objects, arrays, optional fields).
46188
- Key concepts: context.store, context.logger, domain organization, schema depth.
46189
- Verify: Run workflow, confirm store values in step output, check logs in Execution Logs.
46190
-
46191
- **Module: composition -- Resource Composition**
46192
- Read: \`reference/deployment/command-center.mdx\`, \`reference/resources/patterns.mdx\`.
46193
- Build: Create two workflows where the first triggers the second using
46194
- \`execution.trigger()\`. Declare the relationship.
46195
- Key concepts: execution.trigger, relationship declarations, Command View graph edges.
46196
- Verify: Deploy, see relationship edge in Command View, trigger parent and confirm
46197
- child executes.
46198
-
46199
- **Module: llm -- LLM Integration**
46200
- Read: \`reference/platform-tools/adapters.mdx\` (llm singleton).
46201
- Build: Create a workflow step using \`llm.generate()\` with structured output.
46202
- Experiment with model selection and temperature.
46203
- Key concepts: llm singleton, structured output, model selection, temperature.
46204
- Verify: Run workflow, compare outputs with different settings, confirm structured output.
46205
-
46206
- **Module: agents -- AI Agents**
46207
- Read: \`reference/framework/agent.mdx\`.
46208
- Build: Create an agent definition with tools. Configure LLM tool calling.
46209
- Compare agent vs workflow for a task.
46210
- Key concepts: agent definition, tool registration, LLM tool calling, execution trace.
46211
- Verify: Run agent with \`elevasis-sdk exec\`, review tool call trace in Execution Logs.
46212
-
46213
- ## Advanced Workspace Track
46214
-
46215
- The Advanced Workspace track teaches power-user workspace customization and maintenance --
46216
- rules, memory, and the template lifecycle. Independent of the core path; can be taken at any time.
46217
-
46218
- Each item follows the same flow as core lessons: announce, explain per skill level, verify, record observations.
46219
-
46220
- **Item 20: Rules, Memory, and Customization**
46221
-
46222
- When automation is none:
46223
- "The assistant has a set of reminders specific to your project. Over time, when it
46224
- makes the same mistake 3 times, you can tell it to always remember that rule -- it
46225
- lives in a file so the rule sticks across conversations."
46226
- Show \`.claude/rules/workspace-patterns.md\` without technical detail. Explain: "This
46227
- is where YOUR project's rules go. The other rule files are updated automatically by
46228
- SDK releases."
46229
- Verify: Open \`.claude/rules/workspace-patterns.md\` and read the current content together.
46230
- Observation focus: customization concept, owned vs managed files.
46231
-
46232
- When automation is low-code:
46233
- Show the \`.claude/rules/\` directory. Explain the two types: sdk-patterns.md (MANAGED --
46234
- updated by elevasis-sdk update) and workspace-patterns.md (INIT_ONLY -- yours to edit).
46235
- Explain path-scoping briefly: "These rules only activate when the agent is working on
46236
- certain file types." Show an example rule with WRONG/RIGHT pattern. Explain error
46237
- promotion: if something goes wrong 3+ times, add it here.
46238
- Verify: Read \`.claude/rules/workspace-patterns.md\`. Note the "When to Add a Rule" section.
46239
- Observation focus: two-tier ownership model, rule format.
46240
-
46241
- When automation is custom:
46242
- Read \`.claude/rules/sdk-patterns.md\` and \`.claude/rules/workspace-patterns.md\`.
46243
- Explain MANAGED vs INIT_ONLY lifecycle. Show rule frontmatter structure (paths: for
46244
- auto-loading by the agent). Explain the memory system layout: \`.claude/memory/\`
46245
- (index.md root, profile/ subdirectory, errors/ for promoted issues,
46246
- tutorial-progress.md). Explain error promotion: 3+ recurrences -> rule in
46247
- workspace-patterns.md. Walk through how to add a new rule.
46248
- Verify: Read \`.claude/rules/workspace-patterns.md\`. Add a sample rule entry together.
46249
- Observation focus: MANAGED vs INIT_ONLY lifecycle, rule authoring, memory layout.
46250
-
46251
- **Item 21: Template Lifecycle**
46252
-
46253
- When automation is none:
46254
- "When Elevasis SDK releases updates, the assistant can apply them to your workspace
46255
- automatically. You don't have to redo your customizations." Explain /fix as
46256
- the command that applies updates. Skip technical file classification details.
46257
- Show \`docs/project-map.mdx\` briefly: "This is an auto-generated map of everything
46258
- in your project -- the agent uses it for navigation."
46259
- Verify: Run /fix (or explain what it would do). Check \`docs/project-map.mdx\`.
46260
- Next steps: point to reference docs in docs/, encourage using /work for new tasks.
46261
- Observation focus: update model concept, project map as navigation aid.
46262
-
46263
- When automation is low-code:
46264
- Explain MANAGED (auto-updated by elevasis-sdk update) vs INIT_ONLY (set once, yours).
46265
- Show how /fix applies SDK updates with conflict handling: "If a file changed,
46266
- it shows you both versions and lets you decide."
46267
- Show \`docs/project-map.mdx\` and explain what it contains: resources, commands,
46268
- rules, memory index. Note that deploy auto-regenerates it.
46269
- Verify: Read \`elevasis.config.ts\` templateVersion. Compare to the running SDK version from /status.
46270
- Observation focus: update workflow, project map freshness.
46271
-
46272
- When automation is custom:
46273
- Read \`elevasis.config.ts\` for the current templateVersion. Read \`docs/project-map.mdx\`.
46274
- Explain the full template lifecycle: init (writes all files with classification),
46275
- update (applies MANAGED changes, flags conflicts, preserves INIT_ONLY), fix (detects
46276
- drift, offers SDK upgrade, runs full repair). Explain conflict handling: read current
46277
- file, read template from @elevasis/sdk/templates, merge preserving customizations.
46278
- Explain the project map: auto-generated by deploy, contains resource inventory,
46279
- command list, rule list, memory index.
46280
- Next steps: explore reference docs, use /work for complex tasks, build custom rules.
46281
- Verify: Compare elevasis.config.ts templateVersion with output of /status. Identify any drift.
46282
- Observation focus: full template lifecycle, conflict resolution pattern.
46283
-
46284
- ## Adaptation Rules
46285
-
46286
- **automation: none**
46287
- Use the non-technical variant for each lesson. Agent writes all code -- user
46288
- never types code. Agent runs \`elevasis-sdk exec\` for verification and narrates results.
46289
- Avoid all jargon; use analogies. CLI is the primary verification tool.
46290
- Always deploy before directing the user to the Command Center.
46291
-
46292
- **automation: low-code**
46293
- Map concepts to Zapier/Make equivalents. Show code with plain-English explanations.
46294
- CLI is the primary verification tool. Show Zod types with labels.
46295
-
46296
- **automation: custom**
46297
- Full technical content. Code-first. CLI and UI are equal. Condense explanations
46298
- for intermediate/advanced users.
46299
-
46300
- **General rules (all levels)**
46301
- - If user is fast, acknowledge and offer to skip ahead within a lesson
46302
- - After the user confirms readiness at the end of a lesson, update \`.claude/memory/tutorial-progress.md\`
46303
- - If user demonstrates a level change, promote to skills.md Growth Log
46304
- - After completing a module, show the updated full menu table
46305
- - Adapt module depth to skill level as with lessons
46306
-
46307
- ## Progress Format
46308
-
46309
- On first \`/tutorial\` invocation, if \`.claude/memory/tutorial-progress.md\` does not exist,
46310
- create it with this exact format:
46311
-
46312
- \`\`\`markdown
46313
- # Tutorial Progress
46314
-
46315
- Current: Not started
46316
- Started: {today's date}
46317
- Last Session: {today's date}
46318
-
46319
- ## Completed Lessons
46320
-
46321
- | Item | Title | Completed | Duration |
46322
- | --- | --- | --- | --- |
46323
-
46324
- ## Completed Modules
46325
-
46326
- | Module | Title | Completed | Duration |
46327
- | --- | --- | --- | --- |
46328
-
46329
- ## Capability Observations
46330
-
46331
- | Source | Observation |
46332
- | --- | --- |
46333
-
46334
- ## Assessment Notes
46335
-
46336
- (none yet)
46337
- \`\`\`
46338
-
46339
- Update rules:
46340
- - \`Current\`: free-form, e.g. "7: Using Platform Tools" or "M:integrations" or "20: Rules, Memory, and Customization"
46341
- - \`Last Session\`: update to today's date on each \`/tutorial\` invocation
46342
- - Completed Lessons: add a row when any numbered item (1-10, 20-21) finishes
46343
- - Completed Modules: add a row when any module (items 11-19) finishes
46344
- - Capability Observations: prefix source with item number for lessons (#), M:<id> for modules
46345
- - Assessment Notes: bullet points of general skill observations
46346
-
46347
- Backward-compatible: missing Completed Modules treated as empty. Old files with Completed MF Lessons: map entries to items 2-4 and 20-21 by lesson title match.
46348
- `;
46349
- }
46350
- function claudeInitCommandTemplate() {
46351
- return `# /init command
46352
-
46353
- You are a project management assistant for this Elevasis workspace.
46354
-
46355
- ## Context
46356
-
46357
- Read \`elevasis.config.ts\` to get the current \`templateVersion\`.
46358
- Read \`package.json\` to get the installed \`@elevasis/sdk\` version.
46359
- Read \`.claude/memory/index.md\` if it exists for project state.
46360
-
46361
- ## Operation
46362
-
46363
- Guided setup for a freshly scaffolded workspace. Triggered automatically
46364
- by the \`<!-- initialized: false -->\` flag in CLAUDE.md, or run manually.
46365
-
46366
- 1. **Install dependencies**
46367
- Run \`pnpm install\`. Wait for completion. Report any errors.
46368
-
46369
- 2. **Setup environment**
46370
- Read \`.env\`. It should contain only a single line: \`ELEVASIS_PLATFORM_KEY=\`.
46371
- If \`ELEVASIS_PLATFORM_KEY\` is empty or missing, ask the user: "What is your
46372
- Elevasis API key?" When the user provides it, write \`.env\` with exactly:
46373
- \`\`\`
46374
- ELEVASIS_PLATFORM_KEY=<value they provided>
46375
- \`\`\`
46376
- No other keys (no \`NODE_ENV\`, no extras). The \`.env\` file must contain
46377
- only \`ELEVASIS_PLATFORM_KEY\`.
46378
- Validate the key works: run \`elevasis-sdk resources\` (should return an empty
46379
- list, not an auth error). If auth fails, tell the user their key appears
46380
- invalid and ask them to check it in the Elevasis dashboard.
46381
-
46382
- 3. **Competency Assessment**
46383
- Ask these questions to build the user's profile:
46384
-
46385
- Identity & Goals (3 questions):
46386
- - "What does your business or team do?"
46387
- - "What do you want to automate with Elevasis?"
46388
- - "Which tools does your team already use?" (email, CRM, spreadsheets, etc.)
46389
-
46390
- Competency (2 questions):
46391
- - "Have you used the Elevasis Command Center before?"
46392
- Never used it -> platformNavigation: none
46393
- Explored it / know the main sections -> platformNavigation: oriented
46394
- Use it regularly -> platformNavigation: comfortable
46395
- - "Have you used automation tools? (Zapier, Make, cron jobs, scripts)"
46396
- No -> automation: none
46397
- Zapier/Make flows -> automation: low-code
46398
- Custom scripts -> automation: custom
46399
-
46400
- Inferred dimensions (do NOT ask, derive from answers above):
46401
- - apiIntegration: automation: none -> none, low-code -> basic, custom -> proficient.
46402
- Override: if tools answer includes API services (Stripe API, webhook, REST), upgrade one level.
46403
- - domainExpertise: if goals are specific (names processes, metrics, edge cases) -> high.
46404
- If goals are vague -> low.
46405
-
46406
- Communication (1 question):
46407
- - "Step-by-step explanations or concise answers?"
46408
-
46409
- Write responses to memory:
46410
- - Create \`.claude/memory/index.md\` (root index)
46411
- - Create \`.claude/memory/profile/index.md\` (profile index)
46412
- - Create \`.claude/memory/profile/identity.md\` (org, goals, tools)
46413
- - Create \`.claude/memory/profile/skills.md\` using this exact format:
46414
-
46415
- \`\`\`markdown
46416
- # Skills
46417
-
46418
- | Dimension | Level | Since |
46419
- | --- | --- | --- |
46420
- | platformNavigation | {level} | {date} |
46421
- | apiIntegration | {level} | {date} |
46422
- | automation | {level} | {date} |
46423
- | domainExpertise | {level} | {date} |
46424
-
46425
- ## Growth Log
46426
-
46427
- | Date | Observation | Dimension | Change |
46428
- | --- | --- | --- | --- |
46429
- \`\`\`
46430
-
46431
- - Create \`.claude/memory/profile/preferences.md\` (verbosity, guidance)
46432
-
46433
- 4. **Git check**
46434
- - If \`.git/\` exists: note git is configured in .claude/memory/profile/preferences.md
46435
- - If \`.git/\` does not exist: suggest \`git init\` and optionally GitHub
46436
- - If git remote exists: note remote URL in .claude/memory/profile/preferences.md
46437
-
46438
- 5. **Verify project**
46439
- Run \`elevasis-sdk check\` to confirm the starter resource is valid.
46440
- Optionally deploy the echo workflow.
46441
-
46442
- 6. **Report**
46443
- Summary of what was set up. Suggest next steps based on goals.
46444
-
46445
- If the user's Platform Navigation level is none or automation level is none,
46446
- suggest /tutorial: "I recommend starting with /tutorial -- it walks
46447
- you through building workflows step by step, at your own pace."
46448
-
46449
- 7. **Update flag**
46450
- Change \`<!-- initialized: false -->\` to \`<!-- initialized: true -->\`
46451
- in CLAUDE.md.
46452
- `;
46453
- }
46454
- function claudeStatusCommandTemplate() {
46455
- return `# /status command
46456
-
46457
- You are a project management assistant for this Elevasis workspace.
46458
-
46459
- ## Context
46460
-
46461
- Read \`elevasis.config.ts\` to get the current \`templateVersion\`.
46462
- Read \`package.json\` to get the installed \`@elevasis/sdk\` version.
46463
- Read \`.claude/memory/index.md\` if it exists for project state.
46464
-
46465
- ## Operation
46466
-
46467
- Display a project health summary:
46468
- 1. Template version (from elevasis.config.ts) and installed SDK version (from package.json). Suggest \`elevasis-sdk update\` to check for updates
46469
- 2. Profile summary (from .claude/memory/profile/skills.md)
46470
- 3. Quick drift check: count of missing managed files, missing gitignore entries
46471
- 4. Last deployment status (from .claude/memory/deployment-state.md if it exists)
46472
- `;
46473
- }
46474
- function claudeFixCommandTemplate() {
46475
- return `# /fix command
46476
-
46477
- You are a project management assistant for this Elevasis workspace.
46478
-
46479
- ## Context
46480
-
46481
- Read \`elevasis.config.ts\` to get the current \`templateVersion\`.
46482
- Read \`package.json\` to get the installed \`@elevasis/sdk\` version.
46483
- Read \`.claude/memory/index.md\` if it exists for project state.
46484
-
46485
- ## Operation
46486
-
46487
- Detect and repair all drift. Optionally upgrades the SDK first.
46488
-
46489
- 0. **SDK version check** -- Compare installed \`@elevasis/sdk\` against the latest
46490
- available. If behind, offer to run \`pnpm update @elevasis/sdk\` before
46491
- continuing. If the user accepts, run it, then run \`elevasis-sdk update\` to add
46492
- any new managed files and flag conflicts. For each flagged file:
46493
- - Read the current project file and the new template from \`@elevasis/sdk/templates\`
46494
- - Add new sections that don't exist; preserve user customizations
46495
- - If a section differs, show both versions and let the user choose
46496
- 1. **Missing managed files:** Regenerate from templates
46497
- 2. **Gitignore drift:** Append missing entries
46498
- 3. **CLAUDE.md sections:** Add missing sections in correct position
46499
- 4. **Memory structure:** Create base structure if missing, then verify index consistency.
46500
- If \`.claude/memory/\` does not exist or is empty:
46501
- - Create \`.claude/memory/index.md\` (root index with placeholder entries)
46502
- - Create \`.claude/memory/errors/index.md\` (error category summary, empty tables)
46503
- - Create \`.claude/memory/errors/deploy.md\`, \`.claude/memory/errors/runtime.md\`, \`.claude/memory/errors/typescript.md\`
46504
- If memory exists, verify: every file referenced in an index exists; every file
46505
- without an index entry gets one added; broken references are removed.
46506
- 5. **Documentation verification:** For each file in docs/:
46507
- a. Cross-reference claims against src/ code (resource IDs, schema fields, platform tools used)
46508
- b. Verify file path references point to real files
46509
- c. Flag mismatches between documented schemas and actual resource definitions
46510
- d. Check for undocumented resources (resources in src/ without docs coverage)
46511
- e. Report discrepancies with suggested fixes
46512
- Note: \`/docs verify\` is available for standalone interactive verification outside this pipeline.
46513
- 6. **Settings consistency:** Verify expected fields
46514
- 7. **Rules health:** Scan \`.claude/memory/errors/\` -- flag any entry that has recurred
46515
- 3+ times and is not yet in \`.claude/rules/workspace-patterns.md\`.
46516
- If \`workspace-patterns.md\` has no rules yet and 5+ resources exist in \`src/\`,
46517
- suggest adding patterns. Surface suggestions only -- do not auto-generate.
46518
- 8. **Project map freshness:** Check whether \`docs/project-map.mdx\` reflects the
46519
- current project state (resources, commands, rules, skills, memory files).
46520
- Compare filesystem state against the map. If stale, run \`elevasis-sdk deploy\`
46521
- to regenerate, or patch inline for minor drift.
46522
-
46523
- Each step reports its result. Steps 1-8 run even if step 0 is skipped.
46524
-
46525
- ## Merge Strategy
46526
-
46527
- - **CLAUDE.md:** Add new sections in correct position. Preserve customizations.
46528
- - **Commands:** Usually additive. Show diff for changes.
46529
- - **.gitignore:** Append-only -- never remove existing entries.
46530
-
46531
- ## Template Access
46532
-
46533
- The agent reads current templates from the installed SDK:
46534
- \`@elevasis/sdk/templates\` subpath exports all template functions.
46535
- `;
46536
- }
46537
- function claudeDeployCommandTemplate() {
46538
- return `# /deploy command
46539
-
46540
- You are a project management assistant for this Elevasis workspace.
46541
-
46542
- ## Context
46543
-
46544
- Read \`elevasis.config.ts\` to get the current \`templateVersion\`.
46545
- Read \`package.json\` to get the installed \`@elevasis/sdk\` version.
46546
- Read \`.claude/memory/index.md\` if it exists for project state.
46547
-
46548
- ## Operation
46549
-
46550
- 0. Read \`reference/deployment/command-center.mdx\` -- understand the Command View
46551
- model, relationship declarations, and what deploy-time validation checks.
46552
- This context is essential for diagnosing validation failures in steps 1-2.
46553
- 1. Run \`elevasis-sdk check\` (validation)
46554
- 2. Type check if \`tsconfig.json\` exists
46555
- 3. Verify docs reflect current resources
46556
- 4. If git configured: stage changes, commit with deploy message
46557
- 5. Run \`elevasis-sdk deploy\`
46558
- 6. \`docs/project-map.mdx\` is auto-regenerated by deploy (no manual bump needed)
46559
- 7. Verify deployment via platform
46560
- 8. Update \`.claude/memory/deployment-state.md\` with count, timestamp, inventory
46561
- 9. If git configured and remote exists: optionally push
46562
-
46563
- Each step reports its result. Pipeline stops on failure with suggested fix.
46564
- If validation fails with relationship errors, re-read \`reference/deployment/command-center.mdx\`
46565
- for the enforcement model and common fixes.
46566
- `;
46567
- }
46568
- function claudeDiagnosticsSkillTemplate() {
46569
- return `---
46570
- name: diagnostics
46571
- description: "Execution diagnostics and runtime debugging. TRIGGER when: an execution fails, user asks why something failed or errored, user mentions runtime errors or unexpected behavior, or agent observes a failed execution result. DO NOT TRIGGER when: user is discussing errors in code (type errors, lint errors) or build failures -- those are development issues, not runtime diagnostics."
46572
- ---
46573
-
46574
- # Execution Diagnostics
46575
-
46576
- You are a runtime diagnostics assistant for this Elevasis workspace.
46577
-
46578
- ## Context
46579
-
46580
- Read \`.claude/memory/errors/index.md\` if it exists for past error patterns.
46581
- Read \`.claude/memory/deployment-state.md\` if it exists for deployment context.
46582
-
46583
- ## When Triggered
46584
-
46585
- Diagnose runtime failures and environment issues:
46586
-
46587
- 1. **Identify the failure** -- get the execution ID and resource ID from the error or conversation context
46588
- 2. **Pull execution details** -- run \`elevasis-sdk execution <resource-id> <execution-id>\` to get logs
46589
- 3. **Cross-reference** -- check \`.claude/memory/errors/\` for known patterns
46590
- 4. **Check deployment status** -- is the resource deployed? Is it the latest version?
46591
- 5. **Verify environment** -- API key valid, required credentials accessible
46592
- 6. **Diagnose root cause** -- analyze logs, identify the failing step, trace the error
46593
- 7. **Record** -- save new error patterns to \`.claude/memory/errors/\` with context and fix
46594
- 8. **Suggest fix** -- propose a concrete fix or next step
46595
-
46596
- If the error has occurred before (found in memory/errors/), apply the known fix directly.
46597
- If it recurs 3+ times, suggest adding a rule to \`.claude/rules/workspace-patterns.md\`.
46598
- `;
46599
- }
46600
- function claudeWorkSkillTemplate() {
46601
- return `---
46602
- name: work
46603
- description: "Task tracking and progress persistence. TRIGGER when: user says /work, asks to track or save progress across sessions, asks what they were working on, wants to create/resume/complete a task doc, or says they are done for today. DO NOT TRIGGER when: user is just doing work without wanting to track it in docs/in-progress/."
46604
- ---
46605
-
46606
- # Task Tracking
46607
-
46608
- You are a task tracking assistant for this Elevasis workspace. \`/work\` is the primary interface for managing all work and projects.
46609
-
46610
- Your job is to **intelligently manage tasks without requiring the user to know subcommands**. Detect what the user needs from context and act accordingly.
46611
-
46612
- ## Context
46613
-
46614
- Read \`docs/priorities.mdx\` if it exists for current priorities.
46615
- Scan \`docs/in-progress/\` recursively for \`.mdx\` files with \`status\` frontmatter.
46616
-
46617
- ## Directory Structure
46618
-
46619
- Task docs live in \`docs/in-progress/\`. Organize intelligently:
46620
-
46621
- - **Small standalone tasks**: \`docs/in-progress/<slug>.mdx\`
46622
- - **Multi-file tasks**: \`docs/in-progress/<slug>/index.mdx\` (+ supporting docs)
46623
- - **Related tasks**: group under the same directory
46624
-
46625
- When scanning, treat \`index.mdx\` as the primary task doc for a directory.
46626
-
46627
- ## Status Values
46628
-
46629
- Enforce exactly three values in frontmatter: \`planned\`, \`in-progress\`, \`complete\`.
46630
-
46631
- ## Intent Detection
46632
-
46633
- When \`/work\` is invoked (with or without arguments), detect intent from context:
46634
-
46635
- | Signal | Action |
46636
- |--------|--------|
46637
- | No arguments, no active conversation context | **List** tasks, then let user pick |
46638
- | User picks a number or names a task | **Resume** that task automatically |
46639
- | User describes new work (not matching existing tasks) | **Create** a task doc automatically |
46640
- | \`/work\` with a description that matches no existing task | **Create** automatically |
46641
- | \`/work\` with a keyword/name matching an existing task | **Resume** automatically |
46642
- | Conversation is getting heavy, user wrapping up, or 2+ steps completed | **Save** automatically |
46643
- | All plan steps are COMPLETE | **Suggest** \`/work complete\` (never auto-invoke) |
46644
-
46645
- **Key principle:** Create, save, and resume are auto-invoked. Complete always asks permission first.
46646
-
46647
- ## Behaviors
46648
-
46649
- ### List and Pick (default when no context)
46650
-
46651
- 1. Scan \`docs/in-progress/\` recursively for \`.mdx\` files with \`status\` frontmatter
46652
- 2. For directories, read \`index.mdx\` as the primary task doc
46653
- 3. Display a numbered list sorted by status (\`in-progress\` first, then \`planned\`, then \`complete\`):
46654
-
46655
- \`\`\`
46656
- Active Tasks
46657
- ============
46658
-
46659
- 1. [in-progress] SDK Adapter Migration
46660
- Last saved: 2026-03-02 | Step 3/5: Building factory adapters
46661
-
46662
- 2. [planned] Email Template System
46663
- Created: 2026-03-01 | Not started
46664
-
46665
- 3. [complete] CRM Integration
46666
- Completed: 2026-03-03
46667
-
46668
- Pick a task by number or name, or describe new work to start.
46669
- \`\`\`
46670
-
46671
- 4. Cross-reference with \`docs/priorities.mdx\` if it exists
46672
- 5. When the user picks a number or describes a task, auto-invoke the appropriate flow (resume or create)
46673
- 6. If no tasks found, ask: "What are you trying to accomplish?"
46674
-
46675
- ### Create (auto-invoked when new work detected)
46676
-
46677
- 1. If the user's intent is clear, skip the interview and create directly
46678
- 2. If ambiguous, ask 1-2 focused questions:
46679
- - "What does success look like?" (acceptance criteria)
46680
- - "Do we need to investigate anything first, or is the path clear?"
46681
- 3. Scan \`docs/in-progress/\` for existing directories related to the topic
46682
- 4. Determine directory placement:
46683
- - If related to existing directory, create as a file within it
46684
- - If new concept that may grow, create \`docs/in-progress/<slug>/index.mdx\`
46685
- - If small/standalone, create \`docs/in-progress/<slug>.mdx\`
46686
- 5. Create the doc with \`status: planned\` and structured sections:
46687
-
46688
- \`\`\`yaml
46689
- ---
46690
- title: {Task Title}
46691
- description: {Concise description}
46692
- status: planned
46693
- ---
46694
- \`\`\`
46695
-
46696
- Sections: Objective (what and why), Plan (numbered steps), Progress (per-step tracking with PENDING markers), Resume Context (current state, key docs, "To continue" prompt).
46697
-
46698
- 6. Update \`docs/priorities.mdx\` if it exists
46699
- 7. Report what was created with location and step count
46700
-
46701
- ### Save (auto-invoked when progress detected)
46702
-
46703
- Auto-save triggers (do NOT ask, just save):
46704
- - The conversation context is getting heavy (many tool calls, large file reads)
46705
- - The user appears to be wrapping up (thanks, goodbye, switching topics)
46706
- - Significant progress has been made (2+ steps completed without saving)
46707
- - Before a context reset
46708
-
46709
- Save flow:
46710
- 1. Identify the current task from conversation context
46711
- 2. If not working on a tracked task, offer to create a new one
46712
- 3. Update Progress section:
46713
- - Mark completed steps as \`COMPLETE\` with: what was done, key decisions, files changed
46714
- - Mark current step as \`IN PROGRESS\` with current state
46715
- - Leave future steps as \`PENDING\`
46716
- 4. Update Resume Context section with:
46717
- - Current State ({today's date}): summary of accomplishments and next steps
46718
- - Files Modified: table of file paths and descriptions of changes
46719
- - Key docs to read on resume: file paths with why they matter
46720
- - To continue: copy-pasteable prompt for the next session
46721
- 5. Set \`status\` appropriately (\`in-progress\` if ongoing)
46722
- 6. Briefly confirm: "Progress saved to {path}."
46723
-
46724
- ### Resume (auto-invoked when existing task detected)
46725
-
46726
- **Resolution order:**
46727
- 1. If a number is given, map to the numbered list from the task list
46728
- 2. If a name/keyword is given, substring match against task titles and filenames in \`docs/in-progress/\`
46729
- 3. If no argument, scan for \`status: in-progress\` docs -- if one found, use it; if multiple, list and ask
46730
- 4. If multiple matches, list them and ask which to resume
46731
-
46732
- **Resume flow:**
46733
- 1. Read the target task doc
46734
- 2. Parse the Resume Context section
46735
- 3. Load key docs listed in "Key docs to read on resume" in parallel
46736
- 4. Quick verify: check that referenced files exist (Glob), report warnings for missing files
46737
- 5. Present resume summary:
46738
-
46739
- \`\`\`
46740
- Resuming: {task title}
46741
- ========================
46742
-
46743
- Last completed: Step {N}: {title}
46744
- Next: Step {M}: {title}
46745
-
46746
- Key context loaded:
46747
- - {doc 1}
46748
- - {doc 2}
46749
-
46750
- Ready to continue. {Copy of "To continue" prompt}
46751
- \`\`\`
46752
-
46753
- ### Complete (NEVER auto-invoked -- always suggest)
46754
-
46755
- When all plan steps are COMPLETE, suggest: "All steps for '{task}' look done. Want me to finalize it?"
46756
-
46757
- Only proceed after explicit user confirmation. Then:
46758
-
46759
- 1. **Validate readiness:** Check that all plan steps are marked COMPLETE. If not, warn and ask for confirmation.
46760
- 2. **Clean up the doc:**
46761
- - Strip \`## Resume Context\` section entirely (header through next \`##\` or EOF)
46762
- - Strip progress markers: \`COMPLETE\`, \`IN PROGRESS\`, \`PENDING\` from step headings
46763
- - Remove steps still marked PENDING entirely (header + body) -- they were never done
46764
- - Remove \`status\` from frontmatter (keep \`title\` and \`description\`)
46765
- - Target 200-400 lines; flag if result exceeds 500 lines
46766
- 3. **Determine destination:**
46767
- - Scan \`docs/\` (excluding \`docs/in-progress/\`) for existing directories related to this work
46768
- - If a related directory exists, propose merging into it
46769
- - If no related directory, propose \`docs/<slug>/\` or \`docs/<slug>.mdx\`
46770
- - Present the proposed destination and ask user to confirm
46771
- 4. **Move the doc(s):**
46772
- - Single file: move from \`docs/in-progress/\` to destination
46773
- - Directory: move entire directory
46774
- 5. **Verify and report:**
46775
- - Confirm destination exists, source removed
46776
- - Check no leftover \`status:\` or \`## Resume Context\` in moved files
46777
- - Update \`docs/priorities.mdx\` if it exists
46778
- - Report: task title, cleanup stats (lines before/after), destination path
46779
- `;
46780
- }
46781
- function claudeDocsCommandTemplate() {
46782
- return `# /docs command
46783
-
46784
- You are a documentation assistant for this Elevasis workspace. \`/docs\` manages the
46785
- permanent \`docs/\` tree -- browsing, creating reference content, and verifying accuracy
46786
- against code.
46787
-
46788
- **Scope:** Everything in \`docs/\` EXCEPT:
46789
- - \`docs/in-progress/\` -- \`/work\`'s territory
46790
- - \`docs/project-map.mdx\` and \`docs/resource-map.mdx\` -- auto-generated, read-only
46791
-
46792
- ## Context
46793
-
46794
- Read \`.claude/memory/profile/skills.md\` first. The \`automation\` skill level controls
46795
- how results are presented.
46796
-
46797
- ## Operations
46798
-
46799
- ### \`/docs\` (no arguments) -- Browse
46800
-
46801
- Scan \`docs/\` recursively. Display:
46802
-
46803
- \`\`\`
46804
- Your Docs
46805
- =========
46806
-
46807
- Auto-generated (read-only):
46808
- project-map.mdx Updated 2026-03-03
46809
- resource-map.mdx Updated 2026-03-03
46810
-
46811
- Reference (3):
46812
- 1. index.mdx Workspace overview
46813
- 2. priorities.mdx Current priorities
46814
- 3. crm-integration/ CRM integration guide (2 files)
46815
-
46816
- Pick a number to read and discuss, or say:
46817
- "create" to write a new doc
46818
- "verify" to check docs against current code
46819
- \`\`\`
46820
-
46821
- Steps:
46822
- 1. Scan \`docs/\` recursively for \`.mdx\` files, excluding \`in-progress/\`
46823
- 2. Separate auto-generated files (\`project-map.mdx\`, \`resource-map.mdx\`) into a
46824
- read-only group -- show modification date, no number
46825
- 3. Number all user-maintained docs. For directories, show \`index.mdx\` as primary
46826
- with file count
46827
- 4. Sort: \`index.mdx\` first, \`priorities.mdx\` second, then alphabetical
46828
- 5. When user picks a number: read the file and present a summary. Ask what they
46829
- want -- discuss, update, or go back
46830
- 6. If only auto-generated files and \`index.mdx\` exist, suggest: "Your docs/ is
46831
- mostly empty. Run \`/docs create\` to add reference documentation."
46832
-
46833
- **automation: none** -- Frame as "your project's knowledge base." Plain language:
46834
- "These are your project's permanent notes. Pick one to read or discuss."
46835
-
46836
- **automation: low-code** -- Standard presentation. Map to "like a wiki for your automations."
46837
-
46838
- **automation: custom** -- Compact. Show file sizes and last-modified dates.
46839
-
46840
- ---
46841
-
46842
- ### \`create [description]\` -- Reference Doc Creation
46843
-
46844
- Interview-driven creation for permanent documentation. Task docs go through \`/work\`.
46845
-
46846
- 1. If no description given, ask: "What do you want to document?"
46847
- 2. Determine doc type (infer or ask):
46848
- - **Resource guide** -- documents a specific workflow or agent
46849
- - **Integration guide** -- how a specific external tool is used
46850
- - **Architecture notes** -- design decisions, system diagrams
46851
- - **Process doc** -- operational procedures, runbooks
46852
- - **General reference** -- glossaries, onboarding, anything else
46853
- 3. If the doc is about a specific resource: scan \`src/\` for matching resource IDs.
46854
- If found, pre-populate with resource config, schemas, step names, and platform
46855
- tools used. The user does not need to describe what the resource does.
46856
- 4. Determine placement:
46857
- - Scan \`docs/\` for existing directories related to the topic
46858
- - If related to an existing directory, propose adding to it
46859
- - If the topic may grow into multiple files, create \`docs/<slug>/index.mdx\`
46860
- - If small and standalone, create \`docs/<slug>.mdx\`
46861
- 5. Create with proper frontmatter:
46862
- \`\`\`yaml
46863
- ---
46864
- title: Guide Title
46865
- description: What this covers
46866
- ---
46867
- \`\`\`
46868
- Sections by doc type:
46869
- - **Resource guide:** Overview, Input/Output, How It Works, Platform Tools Used, Configuration
46870
- - **Integration guide:** Overview, Setup (credentials), Data Model, Usage Patterns, Troubleshooting
46871
- - **Architecture notes:** Context, Decision, Consequences, Alternatives Considered
46872
- - **Process doc:** Purpose, Prerequisites, Steps, Recovery
46873
- - **General reference:** determined by content
46874
- 6. Report what was created and suggest next steps.
46875
-
46876
- **automation: none** -- Agent writes the full doc from code analysis. User reviews and
46877
- approves. "I've written a guide for your CRM integration based on the code. Take a look
46878
- and tell me if anything is missing."
46879
-
46880
- **automation: low-code** -- Agent drafts, highlights sections the user should customize.
46881
- Shows what was auto-detected vs what needs human input.
46882
-
46883
- **automation: custom** -- Agent scaffolds structure and fills in code-derived content.
46884
- Leaves technical prose to the user. Concise.
46885
-
46886
- ---
46887
-
46888
- ### \`verify [file?]\` -- Interactive Documentation Verification
46889
-
46890
- Standalone interactive version of \`/fix\` step 5. Checks docs against current code.
46891
-
46892
- **Without argument -- verify all:**
46893
-
46894
- 1. Scan \`docs/\` for user-maintained \`.mdx\` files (skip \`in-progress/\`,
46895
- \`project-map.mdx\`, \`resource-map.mdx\`)
46896
- 2. For each file: cross-reference resource IDs, schema fields, and platform tools
46897
- mentioned against \`src/\`
46898
- 3. Check for undocumented resources: resources in \`src/\` without docs coverage
46899
- 4. Present results interactively:
46900
-
46901
- \`\`\`
46902
- Docs Verification
46903
- =================
46904
-
46905
- crm-integration/index.mdx:
46906
- - Line 23: references resourceId "attio-sync" but src/ has "attio-sync-v2"
46907
- - Line 45: schema field "companyName" no longer exists in input schema
46908
-
46909
- onboarding-guide.mdx:
46910
- - No issues found
46911
-
46912
- Undocumented resources (2):
46913
- - email-sender (src/communications/email-sender.ts)
46914
- - lead-scorer (src/scoring/lead-scorer.ts)
46915
-
46916
- Fix crm-integration issues now? (yes/no/skip)
46917
- \`\`\`
46918
-
46919
- 5. When user says yes: read source code, apply fixes to doc, show the diff
46920
- 6. For undocumented resources: offer to create a doc for each one (invokes \`create\` flow)
46921
-
46922
- **With argument -- verify one file:**
46923
-
46924
- Same but scoped to a single file. Resolves by substring match against \`docs/\` file names.
46925
-
46926
- \`\`\`
46927
- /docs verify crm-integration
46928
- \`\`\`
46929
-
46930
- **automation: none** -- Plain language: "Your CRM guide mentions a field called
46931
- 'companyName' but that field was renamed to 'company'. Want me to fix it?"
46932
-
46933
- **automation: low-code** -- Standard presentation with suggested fixes.
46934
-
46935
- **automation: custom** -- Compact diff-style. Auto-fix obvious issues, ask only for
46936
- ambiguous ones.
46937
-
46938
- ---
46939
-
46940
- ## What /docs Does NOT Do
46941
-
46942
- - Touch \`docs/in-progress/\` -- \`/work\`'s territory
46943
- - Handle task lifecycle (planned / in-progress / complete)
46944
- - Edit \`project-map.mdx\` or \`resource-map.mdx\` -- auto-generated, read-only
46945
- - Replace \`/fix\` step 5 -- it supplements it with interactivity
46946
- `;
46947
- }
46948
- function claudeCredsSkillTemplate() {
46949
- return `---
46950
- name: creds
46951
- description: "Credential management assistant. TRIGGER when: user mentions credentials, API keys, secrets, webhook secrets, or asks to set up integrations that need authentication. DO NOT TRIGGER when: user is discussing code that references credentials without needing to manage them."
46952
- ---
46953
-
46954
- # Credential Management
46955
-
46956
- You are a credential management assistant for this Elevasis workspace.
46957
-
46958
- ## Context
46959
-
46960
- Credentials are stored encrypted (AES-256-GCM) on the Elevasis platform and scoped to your
46961
- organization. They are used by workflows and agents at runtime via \`platform.getCredential()\`
46962
- or the \`credential:\` field on tool steps.
46963
-
46964
- The SDK CLI (\`elevasis-sdk creds\`) manages credentials via API key authentication.
46965
- Your \`ELEVASIS_PLATFORM_KEY\` in \`.env\` determines the organization.
46966
-
46967
- ## Credential Types
46968
-
46969
- | Type | Value Format | Example Providers |
46970
- | --- | --- | --- |
46971
- | \`api-key\` | \`{"apiKey": "sk-..."}\` | Stripe, Resend, Apify, Attio, Instantly |
46972
- | \`webhook-secret\` | \`{"signingSecret": "whsec_..."}\` | Cal.com, Stripe webhooks |
46973
- | \`oauth\` | N/A (browser flow only) | Notion, Google Sheets, Dropbox |
46974
-
46975
- OAuth credentials **cannot** be created via CLI. Redirect the user to the Command Center UI.
46976
-
46977
- ## Naming Rules
46978
-
46979
- - Lowercase letters, digits, and hyphens only (\`[a-z0-9-]\`)
46980
- - No consecutive hyphens (\`--\`)
46981
- - 1-100 characters
46982
- - Convention: \`{org}-{provider}\` (e.g., \`tester-stripe-key\`, \`my-project-resend\`)
46983
-
46984
- ## Operations
46985
-
46986
- **No arguments (default):** Show this reference and list credentials.
46987
-
46988
- **\`list\`:** List all credentials for the organization.
46989
- \`\`\`bash
46990
- elevasis-sdk creds list
46991
- \`\`\`
46992
- Display the output. Note which are \`oauth\` (not modifiable via CLI).
46993
-
46994
- **\`create\`:** Guided credential creation flow:
46995
- 1. Ask credential type (\`api-key\` or \`webhook-secret\`). Not \`oauth\`.
46996
- 2. Ask credential name. Validate naming rules before proceeding.
46997
- 3. Ask the user to paste the credential value directly in chat.
46998
- - For \`api-key\`: ask for the API key, construct \`{"apiKey": "..."}\`
46999
- - For \`webhook-secret\`: ask for the signing secret, construct \`{"signingSecret": "..."}\`
47000
- 4. Pipe to CLI: \`echo '{"apiKey":"..."}' | elevasis-sdk creds create --name {name} --type {type}\`
47001
- 5. Confirm success. **NEVER echo the credential value back.**
47002
-
47003
- **\`update\`:** Update credential value:
47004
- 1. Run \`elevasis-sdk creds list\` to confirm the credential exists.
47005
- 2. Ask the user to paste the new value.
47006
- 3. Pipe to CLI: \`echo '{"apiKey":"..."}' | elevasis-sdk creds update {name}\`
47007
- 4. Confirm success. **NEVER echo the value.**
47008
-
47009
- **\`rename\`:** Rename a credential:
47010
- 1. Run \`elevasis-sdk creds list\` to confirm it exists.
47011
- 2. Ask for the new name. Validate naming rules.
47012
- 3. Run: \`elevasis-sdk creds rename {name} --to {newName}\`
47013
-
47014
- **\`delete\`:** Delete a credential:
47015
- 1. Run \`elevasis-sdk creds list\` to confirm it exists.
47016
- 2. Confirm with user before proceeding.
47017
- 3. Run: \`elevasis-sdk creds delete {name} --force\`
47018
-
47019
- **\`webhook-url\`:** Generate a webhook URL:
47020
- Ask for provider, org UUID, resource ID, and credential name. Construct:
47021
- \`POST https://api.elevasis.io/api/webhooks/{provider}?org={uuid}&resource={resourceId}&credential={credentialName}\`
47022
-
47023
- **\`audit\`:** Scan project for credential references:
47024
- 1. Search \`src/**/*.ts\` for \`credential:\` patterns and \`platform.getCredential()\` calls.
47025
- 2. Extract all credential names referenced.
47026
- 3. Run \`elevasis-sdk creds list\` to get the actual credential list.
47027
- 4. Report: missing credentials (referenced but not created), unused credentials (created but not referenced).
47028
-
47029
- ## Security Rules (MANDATORY)
47030
-
47031
- - **NEVER** log, repeat, or display credential values after the user provides them
47032
- - **NEVER** store credential values in files, memory, or command history
47033
- - If an API call fails, ask the user to **re-paste** rather than retrying with a cached value
47034
- - Always confirm name and type **before** asking for the value
47035
- - OAuth credentials cannot be created via CLI -- redirect to Command Center UI
47036
- `;
47037
- }
47038
- function claudeSdkPatternsRuleTemplate() {
47039
- return `---
47040
- description: Elevasis SDK patterns -- imports, source structure, runtime, and platform tools
47041
- paths:
47042
- - src/**
47043
- - elevasis.config.ts
47044
- ---
47045
-
47046
- # SDK Patterns
47047
-
47048
- ## Imports
47049
-
47050
- - \`@elevasis/sdk\` -- types and constants: \`WorkflowDefinition\`, \`StepType\`, \`ExecutionError\`, \`ToolingError\`
47051
- - \`@elevasis/sdk/worker\` -- runtime: \`platform\`, \`PlatformToolError\`, typed adapters
47052
- - **Never import from \`@repo/core\`** -- monorepo-internal, not available in external projects
47053
-
47054
- ## Source Structure
47055
-
47056
- - All resource definitions live in \`src/\` and are exported via \`src/index.ts\`
47057
- - Organize by business domain: \`src/<domain>/\` (e.g., \`src/operations/\`, \`src/acquisition/\`)
47058
- - Each domain barrel (\`src/<domain>/index.ts\`) exports \`workflows\` and \`agents\` arrays
47059
- - Cross-domain utilities go in \`src/shared/\`; domain-specific utilities in \`src/<domain>/shared/\`
47060
- - The default export in \`src/index.ts\` must be a \`DeploymentSpec\` object
47061
- - \`resourceId\` must be lowercase with hyphens, unique per organization
47062
- - \`dist/\` is generated by deploy -- never commit it
47063
-
47064
- ## Runtime
47065
-
47066
- - \`.env\` contains only \`ELEVASIS_PLATFORM_KEY\` for CLI auth -- never deployed, never in worker memory
47067
- - Integration credentials are managed via the \`creds\` skill or Command Center UI
47068
-
47069
- ## Platform Tools
47070
-
47071
- Prefer typed adapters over raw \`platform.call()\`.
47072
-
47073
- ### Singleton adapters (no credential needed)
47074
-
47075
- \`\`\`typescript
47076
- import { scheduler, storage, llm, notifications, acqDb, pdf, approval, execution, email } from '@elevasis/sdk/worker'
47077
- \`\`\`
47078
-
47079
- ### Factory adapters (credential-bound)
47080
-
47081
- \`\`\`typescript
47082
- import { createAttioAdapter, createResendAdapter } from '@elevasis/sdk/worker'
47083
- const attio = createAttioAdapter('credential-name')
47084
- \`\`\`
47085
-
47086
- Use \`platform.call()\` directly only for tools without adapters: \`supabase\`, \`session-memory\`, \`hitl\`, \`status\`, \`http\`.
47087
- `;
47088
- }
47089
- function claudeWorkspaceRulesTemplate() {
47090
- return `---
47091
- description: Project-specific patterns for this workspace, promoted as the project grows
47092
- paths:
47093
- - src/**
47094
- - .claude/rules/workspace-patterns.md
47095
- ---
47096
-
47097
- # Workspace Patterns
47098
-
47099
- Add project-specific patterns here as they emerge. Only add patterns that have already
47100
- occurred multiple times or represent a deliberate convention -- not speculative rules.
47101
-
47102
- ## Rule File Ownership
47103
-
47104
- This file is yours. The other \`.claude/rules/\` files are SDK-owned and updated by
47105
- \`elevasis-sdk update\` -- do not add project-specific notes to them, add them here instead:
47106
-
47107
- - \`sdk-patterns.md\` -- SDK imports, source structure, runtime, adapter patterns
47108
- - \`docs-authoring.md\` -- MDX escaping, frontmatter, docs conventions
47109
- - \`memory-conventions.md\` -- memory system structure and pruning
47110
- - \`project-map.md\` -- auto-generated project map conventions
47111
- - \`task-tracking.md\` -- in-progress task conventions
47112
- - \`logging.md\` -- context.logger usage, console.log prohibition, logging standard
47113
-
47114
- ## When to Add a Rule
47115
-
47116
- - An error has recurred 3+ times (CLAUDE.md instructs you to promote from \`.claude/memory/errors/\`)
47117
- - A pattern appears across 3+ resources and is worth documenting for consistency
47118
- - A naming or structural convention exists that future sessions would likely get wrong
47119
-
47120
- ## Patterns
47121
-
47122
- <!-- Rules are added here as the project grows. Examples:
47123
- - "All Attio records use 'attio-main' as the credential name"
47124
- - "Workflow IDs follow the pattern: <domain>-<verb>-<noun>"
47125
- - "Shared LLM prompt templates live in src/shared/prompts.ts"
47126
- -->
47127
- `;
47128
- }
47129
- function claudeDocsAuthoringRuleTemplate() {
47130
- return `---
47131
- description: Documentation conventions for docs/ files -- MDX escaping, frontmatter, structure
47132
- paths:
47133
- - docs/**/*.mdx
47134
- ---
47135
-
47136
- # Docs Authoring
47137
-
47138
- ## MDX Escaping
47139
-
47140
- - Less-than \`<\` must be \`\\<\` (MDX interprets bare \`<\` as JSX tag)
47141
- - Curly braces \`{var}\` must be in backticks or escaped: \`\\{var\\}\`
47142
- - Greater-than \`>\` must be \`\\>\`
47143
-
47144
- ## Frontmatter
47145
-
47146
- Every \`.mdx\` file requires \`title\` and \`description\`:
47147
-
47148
- \`\`\`yaml
47149
- ---
47150
- title: Feature Name
47151
- description: Concise description
47152
- ---
47153
- \`\`\`
47154
-
47155
- ## Structure
47156
-
47157
- - \`docs/project-map.mdx\` is auto-generated -- do not edit manually
47158
- - \`docs/in-progress/\` for task tracking docs
47159
- - Sort order via \`order\` frontmatter field (lower = earlier)
47160
- `;
47161
- }
47162
- function claudeMemoryConventionsRuleTemplate() {
47163
- return `---
47164
- description: Memory system conventions -- what to store, structure, pruning
47165
- paths:
47166
- - .claude/memory/**
47167
- ---
47168
-
47169
- # Memory Conventions
47170
-
47171
- ## What Memory Is
47172
-
47173
- Memory stores persistent agent state: skills, errors, tutorial progress.
47174
- It is NOT for instructions (commands), reference docs, or templates.
47175
-
47176
- ## Structure
47177
-
47178
- - \`index.md\` at every level maps to children
47179
- - Start at root index and drill down
47180
- - When a file outgrows a single document, split into a subdirectory
47181
-
47182
- ## Pruning
47183
-
47184
- - Keep ~20 recent entries per table; drop stale patterns (30+ days)
47185
- - If an error recurs 3+ times, promote to \`.claude/rules/workspace-patterns.md\`
47186
- `;
47187
- }
47188
- function claudeProjectMapRuleTemplate() {
47189
- return `---
47190
- description: Project map conventions -- auto-generated, do not edit, maintained by deploy and /fix
47191
- paths:
47192
- - docs/project-map.mdx
47193
- - docs/resource-map.mdx
47194
- ---
47195
-
47196
- # Project Map
47197
-
47198
- - \`docs/project-map.mdx\` and \`docs/resource-map.mdx\` are fully auto-generated by \`elevasis-sdk deploy\`
47199
- - Do not edit either file manually -- changes are overwritten on next deploy
47200
- - \`/fix\` step 8 checks for drift and patches the map
47201
- - If a new command, rule, skill, or memory file is added, run \`/fix\` or \`elevasis-sdk deploy\` to update
47202
- `;
47203
- }
47204
- function claudeTaskTrackingRuleTemplate() {
47205
- return `---
47206
- description: In-progress task conventions -- /work command, doc format, status values, auto-save behavior
47207
- paths:
47208
- - docs/in-progress/**
47209
- ---
47210
-
47211
- # Task Tracking
47212
-
47213
- ## Status Values
47214
-
47215
- Exactly three values for frontmatter \`status\`: \`planned\`, \`in-progress\`, \`complete\`.
47216
-
47217
- ## Doc Format
47218
-
47219
- - Frontmatter: \`title\`, \`description\`, \`status\`
47220
- - Sections: Objective, Plan, Progress, Resume Context
47221
- - Progress subsections use markers: \`### Step N: Title -- PENDING\`, \`-- IN PROGRESS\`, \`-- COMPLETE\`
47222
-
47223
- ## Auto-Update Behavior
47224
-
47225
- - When working on a tracked task, update the Progress section when a plan step transitions:
47226
- - PENDING -> IN PROGRESS (starting work on a step)
47227
- - IN PROGRESS -> COMPLETE (finishing a step)
47228
- - Do NOT update on every action -- only on step transitions
47229
-
47230
- ## Auto-Save Behavior
47231
-
47232
- The agent auto-saves progress (no user action needed) when:
47233
- - The conversation context is getting heavy (many tool calls, large file reads)
47234
- - The user appears to be wrapping up (thanks, goodbye, switching topics)
47235
- - Significant progress has been made (2+ steps completed without saving)
47236
- - Before a context reset
47237
-
47238
- Auto-save updates the task doc's Progress and Resume Context sections silently, then briefly confirms.
47239
-
47240
- ## Completion Suggestions
47241
-
47242
- When all plan steps are marked COMPLETE, **suggest** completing the task -- never auto-invoke. Ask: "All steps for '{task}' look done. Want me to finalize it?"
47243
-
47244
- ## Directory Conventions
47245
-
47246
- - \`docs/in-progress/\` for all active task docs
47247
- - Small tasks: \`<slug>.mdx\` directly in \`docs/in-progress/\`
47248
- - Multi-file tasks: \`<slug>/index.mdx\` with supporting docs alongside
47249
- - Completed tasks move OUT of \`docs/in-progress/\` to \`docs/<relevant-dir>/\`
47250
- `;
47251
- }
47252
- function claudeLoggingRuleTemplate() {
47253
- return `---
47254
- description: Logging conventions for workflow and agent handlers
47255
- paths:
47256
- - src/**
47257
- ---
47258
-
47259
- # Logging
47260
-
47261
- ## Always Use \`context.logger\` in Handlers
47262
-
47263
- **Never use \`console.log\`, \`console.warn\`, or \`console.error\` in step/agent handlers.**
47264
- The platform does not capture \`console.*\` output \u2014 it will not appear in execution logs.
47265
-
47266
- \`\`\`typescript
47267
- // \u274C WRONG \u2014 invisible in Command Center
47268
- handler: async (rawInput) => {
47269
- console.log('Processing...')
47270
- }
47271
-
47272
- // \u2705 CORRECT \u2014 visible in Command Center
47273
- handler: async (rawInput, context) => {
47274
- context.logger.info('Processing...')
47275
- }
47276
- \`\`\`
47277
-
47278
- ## Logger Methods
47279
-
47280
- \`\`\`typescript
47281
- context.logger.debug('Verbose detail \u2014 shown in debug mode only')
47282
- context.logger.info('Normal progress messages')
47283
- context.logger.warn('Non-fatal issue \u2014 skipped, retried, partial result')
47284
- context.logger.error('Fatal error or unexpected failure')
47285
- \`\`\`
47286
-
47287
- ## Extensive Logging Standard
47288
-
47289
- Every handler should log:
47290
-
47291
- 1. **Entry** \u2014 step name + key input params (category, count, domain, etc.)
47292
- 2. **Progress** \u2014 inside loops: per-item status (processed, skipped, failed)
47293
- 3. **Decisions** \u2014 idempotency skips, early exits, conditional branches
47294
- 4. **Summary** \u2014 counts at the end (X processed, Y skipped, Z errors)
47295
-
47296
- \`\`\`typescript
47297
- handler: async (rawInput, context) => {
47298
- const data = rawInput as SomeType
47299
- context.logger.info(\`[step-name] Starting \u2014 \${data.items.length} items\`)
47300
-
47301
- let processed = 0, skipped = 0
47302
- for (const item of data.items) {
47303
- if (item.alreadyDone) {
47304
- skipped++
47305
- context.logger.info(\`[step-name] Skipping \${item.name} \u2014 already complete\`)
47306
- continue
47307
- }
47308
- // ...
47309
- processed++
47310
- context.logger.info(\`[step-name] Processed \${item.name}\`)
47311
- }
47312
-
47313
- context.logger.info(\`[step-name] Done \u2014 \${processed} processed, \${skipped} skipped\`)
47314
- }
47315
- \`\`\`
47316
-
47317
- ## Warnings vs Errors
47318
-
47319
- - \`warn\`: skipped item, not found in DB, LLM timeout on one domain (processing continues)
47320
- - \`error\`: step-level failures that propagate as thrown errors (log before throwing if possible)
47321
- `;
47322
- }
47323
- function claudePostEditValidateHookTemplate() {
47324
- return `#!/usr/bin/env node
47325
- // post-edit-validate.mjs
47326
- // PostToolUse hook \u2014 auto-formats with prettier, type-checks .ts/.tsx files.
47327
- // Fires after Edit|Write|MultiEdit succeeds.
47328
-
47329
- import { existsSync } from 'node:fs'
47330
- import { resolve, normalize, extname, join, dirname } from 'node:path'
47331
- import { execSync } from 'node:child_process'
47332
-
47333
- const ROOT = process.env.CLAUDE_PROJECT_DIR ?? process.cwd()
47334
-
47335
- // Extensions prettier should format
47336
- const PRETTIER_EXTENSIONS = new Set([
47337
- '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json', '.css', '.md', '.mdx'
47338
- ])
47339
-
47340
- // Extensions that trigger type-checking
47341
- const TS_EXTENSIONS = new Set(['.ts', '.tsx'])
47342
-
47343
- function findNearestTsconfig(startDir) {
47344
- let dir = startDir
47345
- const root = normalize(ROOT)
47346
- while (dir.length >= root.length) {
47347
- const candidate = join(dir, 'tsconfig.json')
47348
- if (existsSync(candidate)) return candidate
47349
- const parent = dirname(dir)
47350
- if (parent === dir) break
47351
- dir = parent
47352
- }
47353
- return null
47354
- }
47355
-
47356
- try {
47357
- const chunks = []
47358
- for await (const chunk of process.stdin) chunks.push(chunk)
47359
- const input = JSON.parse(Buffer.concat(chunks).toString())
47360
-
47361
- const filePath = input.tool_input?.file_path
47362
- if (!filePath) process.exit(0)
47363
-
47364
- const ext = extname(filePath).toLowerCase()
47365
- const absPath = normalize(resolve(filePath))
47366
- if (!existsSync(absPath)) process.exit(0)
47367
-
47368
- const results = []
47369
-
47370
- // 1. Prettier
47371
- if (PRETTIER_EXTENSIONS.has(ext)) {
47372
- try {
47373
- execSync('pnpm exec prettier --write "' + absPath + '"', {
47374
- cwd: ROOT,
47375
- stdio: ['pipe', 'pipe', 'pipe'],
47376
- timeout: 10_000
47377
- })
47378
- } catch (err) {
47379
- const stderr = err.stderr?.toString().trim() || ''
47380
- if (stderr && !/ignored/i.test(stderr)) {
47381
- results.push('Prettier error: ' + stderr.slice(0, 300))
47382
- }
47383
- }
47384
- }
47385
-
47386
- // 2. Type-check for .ts/.tsx
47387
- if (TS_EXTENSIONS.has(ext)) {
47388
- const tsconfig = findNearestTsconfig(dirname(absPath))
47389
- if (tsconfig) {
47390
- try {
47391
- execSync('pnpm exec tsc --noEmit -p "' + tsconfig + '"', {
47392
- cwd: ROOT,
47393
- stdio: ['pipe', 'pipe', 'pipe'],
47394
- timeout: 30_000,
47395
- env: { ...process.env, NODE_OPTIONS: '--max-old-space-size=4096' }
47396
- })
47397
- } catch (err) {
47398
- if (err.killed) process.exit(0) // Don't block on timeout
47399
- const stdout = err.stdout?.toString() || ''
47400
- if (stdout.includes('error TS')) {
47401
- const errorLines = stdout
47402
- .split('\\n')
47403
- .filter(l => l.includes('error TS'))
47404
- .slice(0, 10)
47405
- results.push('Type errors after editing ' + filePath + ':\\n' + errorLines.join('\\n'))
47406
- }
47407
- }
47408
- }
47409
- }
47410
-
47411
- // Output errors to Claude's context (silence = success)
47412
- if (results.length > 0) {
47413
- process.stderr.write(results.join('\\n\\n'))
47414
- process.exit(2) // Exit 2 = send stderr as feedback to Claude
47415
- }
47416
- } catch {}
47417
-
47418
- process.exit(0)
47419
- `;
47420
- }
47421
- function claudeToolFailureRecoveryHookTemplate() {
47422
- return `#!/usr/bin/env node
47423
- // tool-failure-recovery.mjs
47424
- // PostToolUseFailure hook \u2014 pattern-matches known Bash errors and returns
47425
- // recovery advice via stderr + exit 2 (feedback to Claude).
47426
-
47427
- const RECOVERY_TABLE = [
47428
- {
47429
- test: r => /JavaScript heap out of memory/i.test(r),
47430
- advice: 'Out of memory.',
47431
- fix: 'Run the command with NODE_OPTIONS="--max-old-space-size=4096".',
47432
- why: 'Large TypeScript projects can exceed Node default heap limit.',
47433
- },
47434
- {
47435
- test: r => /boundary hook/i.test(r) && /block|denied/i.test(r),
47436
- advice: 'Command blocked by SDK boundary hook.',
47437
- fix: 'Ask the user to run this command manually.',
47438
- why: 'The boundary hook blocks file modifications (Write, Edit, destructive Bash) outside the project boundary.',
47439
- see: 'CLAUDE.md',
47440
- },
47441
- {
47442
- test: r => /ENOENT/.test(r) && /node_modules/.test(r),
47443
- advice: 'Missing node_modules dependency.',
47444
- fix: 'Run: pnpm install',
47445
- why: 'Dependencies are not installed or were cleared.',
47446
- },
47447
- {
47448
- test: r => /ERR_MODULE_NOT_FOUND/.test(r) && /@elevasis\\/sdk/.test(r),
47449
- advice: '@elevasis/sdk module not found.',
47450
- fix: 'Run: pnpm install \u2014 then verify @elevasis/sdk is in package.json dependencies.',
47451
- why: 'The SDK package is not installed or the version is mismatched.',
47452
- },
47453
- {
47454
- test: r => /ERR_MODULE_NOT_FOUND/.test(r),
47455
- advice: 'Module not found at import path.',
47456
- fix: 'Check the import path and verify the package is installed (pnpm install).',
47457
- why: 'The import path does not match any installed package or local file.',
47458
- },
47459
- {
47460
- test: r => /TS2307/.test(r) || (/cannot find/i.test(r) && /declaration/i.test(r)),
47461
- advice: 'TypeScript cannot resolve module or declaration file.',
47462
- fix: 'Check that the package is installed and tsconfig paths are correct.',
47463
- why: 'Missing dependency or incorrect TypeScript configuration.',
47464
- },
47465
- {
47466
- test: r => /EPERM/.test(r) || /permission denied/i.test(r),
47467
- advice: 'Permission denied (EPERM).',
47468
- fix: 'Close the file in any other process (editor, terminal, or dev server) and retry.',
47469
- why: 'On Windows, files locked by another process cannot be written to.',
47470
- },
47471
- {
47472
- test: r => /lockfile/i.test(r) && /conflict|outdated|ERR_PNPM/i.test(r),
47473
- advice: 'pnpm lockfile conflict or outdated.',
47474
- fix: 'Run: pnpm install to regenerate the lockfile.',
47475
- why: 'The lockfile is out of sync with package.json changes.',
47476
- },
47477
- {
47478
- test: r => /elevasis-sdk check/.test(r) || /elevasis-sdk deploy/.test(r),
47479
- advice: 'elevasis-sdk CLI command failed.',
47480
- fix: 'Check the error output above. Common causes: missing .env ELEVASIS_API_KEY, invalid resource schemas, or network issues.',
47481
- why: 'The SDK CLI validates resources and communicates with the platform API.',
47482
- },
47483
- {
47484
- test: r => /EADDRINUSE/.test(r),
47485
- advice: 'Port already in use.',
47486
- fix: 'Find and kill the process using the port, or use a different port.',
47487
- why: 'A previous dev server or process is still holding the port.',
47488
- },
47489
- ]
47490
-
47491
- function formatRecovery(entry) {
47492
- let msg = 'FAILED: ' + entry.advice + '\\nFIX: ' + entry.fix
47493
- if (entry.why) msg += '\\nWHY: ' + entry.why
47494
- if (entry.see) msg += '\\nSEE: ' + entry.see
47495
- return msg
47496
- }
47497
-
47498
- try {
47499
- const chunks = []
47500
- for await (const chunk of process.stdin) chunks.push(chunk)
47501
- const input = JSON.parse(Buffer.concat(chunks).toString())
47502
-
47503
- const response = input.tool_response ?? ''
47504
-
47505
- for (const entry of RECOVERY_TABLE) {
47506
- if (entry.test(response)) {
47507
- process.stderr.write(formatRecovery(entry))
47508
- process.exit(2)
47509
- }
47510
- }
47511
- } catch {}
47512
-
47513
- process.exit(0)
47514
- `;
47515
- }
47516
-
47517
- // src/cli/commands/templates/core/resources.ts
47518
- function starterTemplate() {
47519
- return `import type { DeploymentSpec } from '@elevasis/sdk'
47520
- import * as operations from './operations/index.js'
47521
- import * as example from './example/index.js'
47522
-
47523
- const org: DeploymentSpec = {
47524
- workflows: [
47525
- ...operations.workflows,
47526
- ...example.workflows,
47527
- ],
47528
- agents: [
47529
- ...operations.agents,
47530
- ...example.agents,
47531
- ],
47532
- }
47533
- export default org
47534
- `;
47535
- }
47536
- function starterWorkflowTemplate() {
47537
- return `import type { WorkflowDefinition } from '@elevasis/sdk'
47538
- import { z } from 'zod'
47539
-
47540
- const echoInput = z.object({ message: z.string() })
47541
- const echoOutput = z.object({ echo: z.string() })
47542
- type EchoInput = z.infer<typeof echoInput>
47543
-
47544
- export const echo: WorkflowDefinition = {
47545
- config: {
47546
- resourceId: 'echo',
47547
- name: 'Echo',
47548
- type: 'workflow',
47549
- description: 'Echoes the input message back',
47550
- version: '1.0.0',
47551
- status: 'dev',
47552
- },
47553
- contract: {
47554
- inputSchema: echoInput,
47555
- outputSchema: echoOutput,
47556
- },
47557
- steps: {
47558
- echo: {
47559
- id: 'echo',
47560
- name: 'Echo Message',
47561
- description: 'Returns the input message',
47562
- handler: async (input) => {
47563
- const { message } = input as EchoInput
47564
- return { echo: message }
47565
- },
47566
- inputSchema: echoInput,
47567
- outputSchema: echoOutput,
47568
- next: null,
47569
- },
47570
- },
47571
- entryPoint: 'echo',
47572
- }
47573
- `;
47574
- }
47575
- function platformStatusTemplate() {
47576
- return `import type { WorkflowDefinition } from '@elevasis/sdk'
47577
- import { StepType } from '@elevasis/sdk'
47578
- import { platform } from '@elevasis/sdk/worker'
47579
- import { llm } from '@elevasis/sdk/worker'
47580
- import { z } from 'zod'
47581
-
47582
- const input = z.object({
47583
- timeRange: z.enum(['1h', '24h', '7d']).default('24h').describe('Time window for status data'),
47584
- })
47585
-
47586
- const statusData = z.object({
47587
- raw: z.unknown().describe('Raw status overview from platform'),
47588
- })
47589
-
47590
- const output = z.object({
47591
- raw: z.unknown().describe('Raw status overview from platform'),
47592
- summary: z.string().describe('Natural language status summary'),
47593
- })
47594
-
47595
- type Input = z.infer<typeof input>
47596
-
47597
- export const platformStatus: WorkflowDefinition = {
47598
- config: {
47599
- resourceId: 'platform-status',
47600
- name: 'Platform Status',
47601
- type: 'workflow',
47602
- description: 'Gathers cross-system platform status and compiles a natural language summary',
47603
- version: '1.0.0',
47604
- status: 'dev',
47605
- },
47606
- contract: { inputSchema: input, outputSchema: output },
47607
- steps: {
47608
- 'gather-status': {
47609
- id: 'gather-status',
47610
- name: 'Gather Status',
47611
- description: 'Queries platform status overview (executions, pending items, schedules, credentials)',
47612
- handler: async (rawInput) => {
47613
- const { timeRange } = rawInput as Input
47614
- const raw = await platform.call({
47615
- tool: 'status',
47616
- method: 'overview',
47617
- params: { timeRange },
47618
- })
47619
- return { raw }
47620
- },
47621
- inputSchema: input,
47622
- outputSchema: statusData,
47623
- next: { type: StepType.LINEAR, target: 'compile-report' },
47624
- },
47625
- 'compile-report': {
47626
- id: 'compile-report',
47627
- name: 'Compile Report',
47628
- description: 'Generates a natural language summary from raw status data',
47629
- handler: async (rawInput) => {
47630
- const { raw } = rawInput as z.infer<typeof statusData>
47631
- const result = await llm.generate({
47632
- provider: 'google',
47633
- model: 'gemini-3-flash-preview',
47634
- messages: [
47635
- {
47636
- role: 'user',
47637
- content: [
47638
- 'Summarize this platform status overview in 3-5 concise bullet points.',
47639
- 'Focus on: execution health, pending items needing attention, upcoming schedules, and credential coverage.',
47640
- 'Be specific with numbers. Flag any issues.',
47641
- '',
47642
- JSON.stringify(raw, null, 2),
47643
- ].join('\\n'),
47644
- },
47645
- ],
47646
- responseSchema: {
47647
- type: 'object',
47648
- properties: {
47649
- summary: { type: 'string', description: 'Natural language status summary with bullet points' },
47650
- },
47651
- required: ['summary'],
47652
- },
47653
- temperature: 0,
47654
- })
47655
- const summary = (result as any)?.summary ?? String(result)
47656
- return { raw, summary }
47657
- },
47658
- inputSchema: statusData,
47659
- outputSchema: output,
47660
- next: null,
47661
- },
47662
- },
47663
- entryPoint: 'gather-status',
47664
- }
47665
- `;
47666
- }
47667
- function operationsBarrelTemplate() {
47668
- return `import { platformStatus } from './platform-status.js'
47669
-
47670
- export const workflows = [platformStatus]
47671
- export const agents = []
47672
- `;
47673
- }
47674
- function exampleBarrelTemplate() {
47675
- return `import { echo } from './echo.js'
47676
-
47677
- export const workflows = [echo]
47678
- export const agents = []
47679
- `;
47680
- }
47681
-
47682
- // src/cli/commands/templates/core/index.ts
47683
- function getManagedTemplates(ctx = {}) {
47684
- return {
47685
- "elevasis.config.ts": configTemplate,
47686
- ".gitignore": () => gitignoreTemplate(ctx),
47687
- "CLAUDE.md": () => claudeMdTemplate(ctx),
47688
- ".claude/settings.json": claudeSettingsTemplate,
47689
- ".claude/scripts/statusline-command.js": claudeStatuslineScriptTemplate,
47690
- ".claude/hooks/enforce-sdk-boundary.mjs": claudeSdkBoundaryHookTemplate,
47691
- ".claude/hooks/post-edit-validate.mjs": claudePostEditValidateHookTemplate,
47692
- ".claude/hooks/tool-failure-recovery.mjs": claudeToolFailureRecoveryHookTemplate,
47693
- ".claude/commands/tutorial.md": claudeTutorialCommandTemplate,
47694
- ".claude/commands/init.md": claudeInitCommandTemplate,
47695
- ".claude/commands/status.md": claudeStatusCommandTemplate,
47696
- ".claude/commands/fix.md": claudeFixCommandTemplate,
47697
- ".claude/commands/deploy.md": claudeDeployCommandTemplate,
47698
- ".claude/skills/diagnostics/SKILL.md": claudeDiagnosticsSkillTemplate,
47699
- ".claude/skills/work/SKILL.md": claudeWorkSkillTemplate,
47700
- ".claude/commands/docs.md": claudeDocsCommandTemplate,
47701
- ".claude/skills/creds/SKILL.md": claudeCredsSkillTemplate,
47702
- ".claude/rules/sdk-patterns.md": claudeSdkPatternsRuleTemplate,
47703
- ".claude/rules/docs-authoring.md": claudeDocsAuthoringRuleTemplate,
47704
- ".claude/rules/memory-conventions.md": claudeMemoryConventionsRuleTemplate,
47705
- ".claude/rules/project-map.md": claudeProjectMapRuleTemplate,
47706
- ".claude/rules/task-tracking.md": claudeTaskTrackingRuleTemplate,
47707
- ".claude/rules/logging.md": claudeLoggingRuleTemplate
47708
- };
47709
- }
47710
-
47711
- // src/cli/commands/templates/ui/files.ts
47712
- function getUIFiles(orgSlug) {
47713
- return {
47714
- "ui/package.json": uiPackageJsonTemplate(orgSlug),
47715
- "ui/index.html": uiIndexHtmlTemplate(),
47716
- "ui/vite.config.ts": uiViteConfigTemplate(),
47717
- "ui/tsconfig.json": uiTsconfigTemplate(),
47718
- "ui/src/main.tsx": uiMainTsxTemplate(),
47719
- "ui/src/App.tsx": uiAppTsxTemplate(),
47720
- "ui/src/AuthRedirect.tsx": uiAuthRedirectTemplate(),
47721
- "ui/src/vite-env.d.ts": uiViteEnvDtsTemplate(),
47722
- "ui/.env": uiEnvTemplate()
47723
- };
47724
- }
47725
- function uiPackageJsonTemplate(orgSlug) {
47726
- return JSON.stringify(
47727
- {
47728
- name: `${orgSlug}-ui`,
47729
- private: true,
47730
- type: "module",
47731
- scripts: {
47732
- dev: "vite",
47733
- build: "tsc && vite build",
47734
- preview: "vite preview"
47735
- },
47736
- dependencies: {
47737
- "@elevasis/sdk-ui": "latest",
47738
- react: "^19.0.0",
47739
- "react-dom": "^19.0.0",
47740
- "react-router-dom": "^7.0.0"
47741
- },
47742
- devDependencies: {
47743
- "@types/react": "^19.0.0",
47744
- "@types/react-dom": "^19.0.0",
47745
- "@vitejs/plugin-react": "^4.0.0",
47746
- typescript: "^5.7.0",
47747
- vite: "^6.0.0"
47748
- }
47749
- },
47750
- null,
47751
- 2
47752
- ) + "\n";
47753
- }
47754
- function uiIndexHtmlTemplate() {
47755
- return `<!doctype html>
47756
- <html lang="en">
47757
- <head>
47758
- <meta charset="UTF-8" />
47759
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
47760
- <title>Elevasis UI</title>
47761
- </head>
47762
- <body>
47763
- <div id="root"></div>
47764
- <script type="module" src="/src/main.tsx"></script>
47765
- </body>
47766
- </html>
47767
- `;
47768
- }
47769
- function uiViteConfigTemplate() {
47770
- return `import { defineConfig } from 'vite'
47771
- import react from '@vitejs/plugin-react'
47772
-
47773
- export default defineConfig({
47774
- plugins: [react()],
47775
- server: {
47776
- port: 5100,
47777
- },
47778
- })
47779
- `;
47780
- }
47781
- function uiTsconfigTemplate() {
47782
- return JSON.stringify(
47783
- {
47784
- compilerOptions: {
47785
- target: "ES2022",
47786
- lib: ["ES2022", "DOM", "DOM.Iterable"],
47787
- module: "ESNext",
47788
- moduleResolution: "bundler",
47789
- jsx: "react-jsx",
47790
- strict: true,
47791
- esModuleInterop: true,
47792
- skipLibCheck: true,
47793
- forceConsistentCasingInFileNames: true,
47794
- isolatedModules: true,
47795
- noEmit: true
47796
- },
47797
- include: ["src"]
47798
- },
47799
- null,
47800
- 2
47801
- ) + "\n";
47802
- }
47803
- function uiMainTsxTemplate() {
47804
- return `import { StrictMode } from 'react'
47805
- import { createRoot } from 'react-dom/client'
47806
- import { BrowserRouter } from 'react-router-dom'
47807
- import { App } from './App'
47808
-
47809
- createRoot(document.getElementById('root')!).render(
47810
- <StrictMode>
47811
- <BrowserRouter>
47812
- <App />
47813
- </BrowserRouter>
47814
- </StrictMode>,
47815
- )
47816
- `;
47817
- }
47818
- function uiAppTsxTemplate() {
47819
- return `import { ElevasisCoreProvider } from '@elevasis/sdk-ui'
47820
- import { Routes, Route } from 'react-router-dom'
47821
- import { AuthRedirect } from './AuthRedirect'
47822
-
47823
- export function App() {
47824
- return (
47825
- <ElevasisCoreProvider
47826
- auth={{
47827
- mode: 'oauth',
47828
- clientId: import.meta.env.VITE_WORKOS_CLIENT_ID,
47829
- redirectUri: 'http://localhost:5100/auth-redirect',
47830
- }}
47831
- apiUrl="http://localhost:5170"
47832
- theme={{
47833
- colorScheme: 'dark',
47834
- preset: 'default',
47835
- }}
47836
- >
47837
- <Routes>
47838
- <Route path="/" element={<h1>Home</h1>} />
47839
- <Route path="/auth-redirect" element={<AuthRedirect />} />
47840
- </Routes>
47841
- </ElevasisCoreProvider>
47842
- )
47843
- }
47844
- `;
47845
- }
47846
- function uiAuthRedirectTemplate() {
47847
- return `import { useEffect } from 'react'
47848
- import { useNavigate } from 'react-router-dom'
47849
- import { useAuthContext } from '@elevasis/sdk-ui/auth'
47850
-
47851
- export function AuthRedirect() {
47852
- const { user } = useAuthContext()
47853
- const navigate = useNavigate()
47854
-
47855
- useEffect(() => {
47856
- if (user) {
47857
- navigate('/', { replace: true })
47858
- }
47859
- }, [user, navigate])
47860
-
47861
- return <p>Signing in...</p>
47862
- }
47863
- `;
47864
- }
47865
- function uiViteEnvDtsTemplate() {
47866
- return `/// <reference types="vite/client" />
47867
- `;
47868
- }
47869
- function uiEnvTemplate() {
47870
- return `VITE_WORKOS_CLIENT_ID=
47871
- `;
47872
- }
47873
-
47874
- // src/cli/commands/templates/ui/index.ts
47875
- var UI_INIT_FILES = [
47876
- "ui/package.json",
47877
- "ui/index.html",
47878
- "ui/vite.config.ts",
47879
- "ui/tsconfig.json",
47880
- "ui/src/main.tsx",
47881
- "ui/src/App.tsx",
47882
- "ui/src/AuthRedirect.tsx",
47883
- "ui/src/vite-env.d.ts",
47884
- "ui/.env"
47885
- ];
47886
-
47887
- // src/cli/commands/init.ts
47888
- var INIT_ONLY_FILES = [
47889
- "package.json",
47890
- "pnpm-workspace.yaml",
47891
- "tsconfig.json",
47892
- ".env",
47893
- ".npmrc",
47894
- "src/index.ts",
47895
- "src/operations/platform-status.ts",
47896
- "src/operations/index.ts",
47897
- "src/example/echo.ts",
47898
- "src/example/index.ts",
47899
- "src/shared/.gitkeep",
47900
- "docs/index.mdx",
47901
- "docs/in-progress/.gitkeep",
47902
- ".claude/rules/workspace-patterns.md"
47903
- ];
47904
- var MANAGED_FILES = [
47905
- "elevasis.config.ts",
47906
- ".gitignore",
47907
- "CLAUDE.md",
47908
- ".claude/settings.json",
47909
- ".claude/hooks/enforce-sdk-boundary.mjs",
47910
- ".claude/hooks/post-edit-validate.mjs",
47911
- ".claude/hooks/tool-failure-recovery.mjs",
47912
- ".claude/commands/tutorial.md",
47913
- ".claude/commands/init.md",
47914
- ".claude/commands/status.md",
47915
- ".claude/commands/fix.md",
47916
- ".claude/commands/deploy.md",
47917
- ".claude/skills/diagnostics/SKILL.md",
47918
- ".claude/skills/work/SKILL.md",
47919
- ".claude/commands/docs.md",
47920
- ".claude/skills/creds/SKILL.md",
47921
- ".claude/rules/sdk-patterns.md",
47922
- ".claude/rules/docs-authoring.md",
47923
- ".claude/rules/memory-conventions.md",
47924
- ".claude/rules/project-map.md",
47925
- ".claude/rules/task-tracking.md",
47926
- ".claude/rules/logging.md",
47927
- ".claude/scripts/statusline-command.js"
47928
- ];
47929
- var SCAFFOLD_FILES = [...INIT_ONLY_FILES, ...MANAGED_FILES];
47930
- function registerInitCommand(program3) {
47931
- program3.command("init [directory]").description("Scaffold a new Elevasis workspace\n Example: elevasis-sdk init my-workspace").option("--force", "Overwrite existing files").option("--ui", "Include a Vite + React UI app in ui/").action(
47932
- wrapAction("init", async (directory, options2) => {
47933
- const targetDir = directory ? (0, import_path3.resolve)(directory) : process.cwd();
47934
- const orgSlug = toSlug((0, import_path3.basename)(targetDir));
47935
- if (!options2.force) {
47936
- const filesToCheck = options2.ui ? [...SCAFFOLD_FILES, ...UI_INIT_FILES] : SCAFFOLD_FILES;
47937
- const conflicts = [];
47938
- for (const file2 of filesToCheck) {
47939
- try {
47940
- await (0, import_promises2.access)((0, import_path3.resolve)(targetDir, file2));
47941
- conflicts.push(file2);
47942
- } catch {
47943
- }
47944
- }
47945
- if (conflicts.length > 0) {
47946
- console.error(source_default.red("Files already exist:"));
47947
- for (const f of conflicts) {
47948
- console.error(source_default.gray(` ${f}`));
47949
- }
47950
- console.error(source_default.gray("\n Use --force to overwrite."));
47951
- throw new Error("Scaffold conflict");
47952
- }
47953
- }
47954
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, "src/operations"), { recursive: true });
47955
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, "src/example"), { recursive: true });
47956
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, "src/shared"), { recursive: true });
47957
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, "docs/in-progress"), { recursive: true });
47958
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, ".claude/hooks"), { recursive: true });
47959
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, ".claude/scripts"), { recursive: true });
47960
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, ".claude/commands"), { recursive: true });
47961
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, ".claude/skills/creds"), { recursive: true });
47962
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, ".claude/rules"), { recursive: true });
47963
- if (options2.ui) {
47964
- await (0, import_promises2.mkdir)((0, import_path3.resolve)(targetDir, "ui/src"), { recursive: true });
47965
- }
47966
- const files = {
47967
- "elevasis.config.ts": configTemplate(),
47968
- "package.json": packageJsonTemplate(orgSlug),
47969
- "pnpm-workspace.yaml": pnpmWorkspaceTemplate(),
47970
- "tsconfig.json": tsconfigTemplate(),
47971
- ".env": envTemplate(),
47972
- ".npmrc": npmrcTemplate(),
47973
- ".gitignore": gitignoreTemplate({ hasUI: options2.ui }),
47974
- "src/index.ts": starterTemplate(),
47975
- "src/operations/platform-status.ts": platformStatusTemplate(),
47976
- "src/operations/index.ts": operationsBarrelTemplate(),
47977
- "src/example/echo.ts": starterWorkflowTemplate(),
47978
- "src/example/index.ts": exampleBarrelTemplate(),
47979
- "src/shared/.gitkeep": "",
47980
- "docs/index.mdx": docsIndexTemplate(orgSlug),
47981
- "docs/in-progress/.gitkeep": "",
47982
- "CLAUDE.md": claudeMdTemplate({ hasUI: options2.ui }),
47983
- ".claude/settings.json": claudeSettingsTemplate(),
47984
- ".claude/hooks/enforce-sdk-boundary.mjs": claudeSdkBoundaryHookTemplate(),
47985
- ".claude/hooks/post-edit-validate.mjs": claudePostEditValidateHookTemplate(),
47986
- ".claude/hooks/tool-failure-recovery.mjs": claudeToolFailureRecoveryHookTemplate(),
47987
- ".claude/commands/tutorial.md": claudeTutorialCommandTemplate(),
47988
- ".claude/commands/init.md": claudeInitCommandTemplate(),
47989
- ".claude/commands/status.md": claudeStatusCommandTemplate(),
47990
- ".claude/commands/fix.md": claudeFixCommandTemplate(),
47991
- ".claude/commands/deploy.md": claudeDeployCommandTemplate(),
47992
- ".claude/skills/diagnostics/SKILL.md": claudeDiagnosticsSkillTemplate(),
47993
- ".claude/skills/work/SKILL.md": claudeWorkSkillTemplate(),
47994
- ".claude/commands/docs.md": claudeDocsCommandTemplate(),
47995
- ".claude/skills/creds/SKILL.md": claudeCredsSkillTemplate(),
47996
- ".claude/rules/sdk-patterns.md": claudeSdkPatternsRuleTemplate(),
47997
- ".claude/rules/workspace-patterns.md": claudeWorkspaceRulesTemplate(),
47998
- ".claude/rules/docs-authoring.md": claudeDocsAuthoringRuleTemplate(),
47999
- ".claude/rules/memory-conventions.md": claudeMemoryConventionsRuleTemplate(),
48000
- ".claude/rules/project-map.md": claudeProjectMapRuleTemplate(),
48001
- ".claude/rules/task-tracking.md": claudeTaskTrackingRuleTemplate(),
48002
- ".claude/rules/logging.md": claudeLoggingRuleTemplate(),
48003
- ".claude/scripts/statusline-command.js": claudeStatuslineScriptTemplate()
48004
- };
48005
- if (options2.ui) {
48006
- Object.assign(files, getUIFiles(orgSlug));
48007
- }
48008
- for (const [filePath, content] of Object.entries(files)) {
48009
- await (0, import_promises2.writeFile)((0, import_path3.resolve)(targetDir, filePath), content, "utf-8");
48010
- }
48011
- console.log(source_default.green.bold(" Workspace created!"));
48012
- console.log("");
48013
- console.log(source_default.gray(" Next steps:"));
48014
- if (directory) {
48015
- console.log(source_default.gray(` cd ${directory}`));
48016
- }
48017
- console.log(source_default.gray(" pnpm install"));
48018
- console.log(source_default.gray(" # Add your API key to .env"));
48019
- console.log(source_default.gray(" elevasis-sdk check"));
48020
- console.log(source_default.gray(" elevasis-sdk deploy"));
48021
- if (options2.ui) {
48022
- console.log("");
48023
- console.log(source_default.gray(" UI app:"));
48024
- console.log(source_default.gray(" cd ui && pnpm install"));
48025
- console.log(source_default.gray(" # Set VITE_WORKOS_CLIENT_ID in ui/.env"));
48026
- console.log(source_default.gray(" pnpm dev"));
48027
- }
48028
- })
48029
- );
48030
- }
48031
- function toSlug(name) {
48032
- const slug = name.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^[^a-z]+/, "").replace(/-+/g, "-").replace(/-$/, "");
48033
- return slug.length >= 3 ? slug : "my-workspace";
48034
- }
48035
-
48036
- // src/cli/commands/update.ts
48037
- var import_path4 = require("path");
48038
- var import_promises3 = require("fs/promises");
48039
- var SDK_OWNED_SECTIONS = [
48040
- "Session Initialization",
48041
- "Identity",
48042
- "Navigation",
48043
- "Interaction Guidance",
48044
- "Commands",
48045
- "Skills",
48046
- "Maintaining Memory"
48047
- ];
48048
- function parseSections(md) {
48049
- const lines = md.split("\n");
48050
- const sections = [];
48051
- let currentHeading = "";
48052
- let currentLines = [];
48053
- for (const line of lines) {
48054
- if (line.startsWith("## ")) {
48055
- if (currentLines.length > 0 || currentHeading === "") {
48056
- sections.push({ heading: currentHeading, content: currentLines.join("\n") });
48057
- }
48058
- currentHeading = line;
48059
- currentLines = [line];
48060
- } else {
48061
- currentLines.push(line);
48062
- }
48063
- }
48064
- if (currentLines.length > 0 || currentHeading !== "") {
48065
- sections.push({ heading: currentHeading, content: currentLines.join("\n") });
48066
- }
48067
- return sections;
48068
- }
48069
- function mergeSections(existing, template, sdkOwned) {
48070
- const existingSections = parseSections(existing);
48071
- const templateSections = parseSections(template);
48072
- const updated = [];
48073
- const preserved = [];
48074
- const templateMap = /* @__PURE__ */ new Map();
48075
- for (const section of templateSections) {
48076
- templateMap.set(section.heading, section);
48077
- }
48078
- const sdkOwnedSet = new Set(sdkOwned.map((s) => `## ${s}`));
48079
- const resultSections = [];
48080
- const processedHeadings = /* @__PURE__ */ new Set();
48081
- for (const section of existingSections) {
48082
- processedHeadings.add(section.heading);
48083
- if (section.heading === "") {
48084
- resultSections.push(section);
48085
- continue;
48086
- }
48087
- if (sdkOwnedSet.has(section.heading)) {
48088
- const templateSection = templateMap.get(section.heading);
48089
- if (templateSection) {
48090
- resultSections.push(templateSection);
48091
- updated.push(section.heading.replace("## ", ""));
48092
- } else {
48093
- updated.push(section.heading.replace("## ", "") + " (removed)");
48094
- }
48095
- } else {
48096
- resultSections.push(section);
48097
- preserved.push(section.heading.replace("## ", ""));
48098
- }
48099
- }
48100
- for (const section of templateSections) {
48101
- if (section.heading !== "" && !processedHeadings.has(section.heading)) {
48102
- resultSections.push(section);
48103
- updated.push(section.heading.replace("## ", "") + " (new)");
48104
- }
48105
- }
48106
- return {
48107
- merged: resultSections.map((s) => s.content).join("\n"),
48108
- updated,
48109
- preserved
48110
- };
48111
- }
48112
- function registerUpdateCommand(program3) {
48113
- program3.command("update").description("Update project scaffold to latest template version").option("--ui", "Add a Vite + React UI app in ui/").action(
48114
- wrapAction("update", async (options2 = {}) => {
48115
- const cwd = process.cwd();
48116
- const configPath = (0, import_path4.resolve)(cwd, "elevasis.config.ts");
48117
- let currentVersion = 0;
48118
- let configContents = "";
48119
- try {
48120
- configContents = await (0, import_promises3.readFile)(configPath, "utf-8");
48121
- const match = configContents.match(/templateVersion:\s*(\d+)/);
48122
- if (match) {
48123
- currentVersion = parseInt(match[1], 10);
48124
- }
48125
- } catch {
48126
- }
48127
- const upToDate = currentVersion >= TEMPLATE_VERSION;
48128
- if (upToDate && !options2.ui) {
48129
- console.log(source_default.green(` Project is up to date (template version ${TEMPLATE_VERSION})`));
48130
- return;
48131
- }
48132
- let hasUI = !!options2.ui;
48133
- if (!hasUI) {
48134
- try {
48135
- await (0, import_promises3.access)((0, import_path4.resolve)(cwd, "ui"));
48136
- hasUI = true;
48137
- } catch {
48138
- }
48139
- }
48140
- const managedTemplates = getManagedTemplates({ hasUI });
48141
- const added = [];
48142
- const flagged = [];
48143
- const appendedGitignore = [];
48144
- const mergedUpdated = [];
48145
- const mergedPreserved = [];
48146
- const uiAffectedFiles = /* @__PURE__ */ new Set([".gitignore", "CLAUDE.md"]);
48147
- const filesToProcess = upToDate ? MANAGED_FILES.filter((f) => uiAffectedFiles.has(f)) : MANAGED_FILES;
48148
- for (const file2 of filesToProcess) {
48149
- const filePath = (0, import_path4.resolve)(cwd, file2);
48150
- const templateFn = managedTemplates[file2];
48151
- if (!templateFn) continue;
48152
- const templateContent = templateFn();
48153
- if (file2 === ".gitignore") {
48154
- try {
48155
- await (0, import_promises3.access)(filePath);
48156
- const existingContent = await (0, import_promises3.readFile)(filePath, "utf-8");
48157
- const existingLines = existingContent.split("\n");
48158
- const templateLines = templateContent.split("\n");
48159
- const linesToAppend = [];
48160
- for (const line of templateLines) {
48161
- if (line.trim() === "") continue;
48162
- if (!existingLines.includes(line)) {
48163
- linesToAppend.push(line);
48164
- }
48165
- }
48166
- if (linesToAppend.length > 0) {
48167
- const appendContent = (existingContent.endsWith("\n") ? "" : "\n") + linesToAppend.join("\n") + "\n";
48168
- await (0, import_promises3.writeFile)(filePath, existingContent + appendContent, "utf-8");
48169
- appendedGitignore.push(...linesToAppend);
48170
- }
48171
- } catch {
48172
- await (0, import_promises3.mkdir)((0, import_path4.dirname)(filePath), { recursive: true });
48173
- await (0, import_promises3.writeFile)(filePath, templateContent, "utf-8");
48174
- added.push(file2);
48175
- }
48176
- continue;
48177
- }
48178
- if (file2 === "elevasis.config.ts") {
48179
- if (configContents) {
48180
- if (/templateVersion:\s*\d+/.test(configContents)) {
48181
- const updated = configContents.replace(/templateVersion:\s*\d+/, `templateVersion: ${TEMPLATE_VERSION}`);
48182
- await (0, import_promises3.writeFile)(filePath, updated, "utf-8");
48183
- } else {
48184
- const updated = configContents.replace(
48185
- /\bexport default\s*\{/,
48186
- `export default {
48187
- templateVersion: ${TEMPLATE_VERSION},`
48188
- );
48189
- await (0, import_promises3.writeFile)(filePath, updated, "utf-8");
48190
- }
48191
- } else {
48192
- await (0, import_promises3.mkdir)((0, import_path4.dirname)(filePath), { recursive: true });
48193
- await (0, import_promises3.writeFile)(filePath, templateContent, "utf-8");
48194
- added.push(file2);
48195
- }
48196
- continue;
48197
- }
48198
- if (file2 === "CLAUDE.md") {
48199
- let existingContent = null;
48200
- try {
48201
- await (0, import_promises3.access)(filePath);
48202
- existingContent = await (0, import_promises3.readFile)(filePath, "utf-8");
48203
- } catch {
48204
- }
48205
- if (existingContent !== null) {
48206
- const {
48207
- merged,
48208
- updated: sectionUpdated,
48209
- preserved: sectionPreserved
48210
- } = mergeSections(existingContent, templateContent, SDK_OWNED_SECTIONS);
48211
- await (0, import_promises3.writeFile)(filePath, merged, "utf-8");
48212
- mergedUpdated.push(...sectionUpdated);
48213
- mergedPreserved.push(...sectionPreserved);
48214
- } else {
48215
- await (0, import_promises3.mkdir)((0, import_path4.dirname)(filePath), { recursive: true });
48216
- await (0, import_promises3.writeFile)(filePath, templateContent, "utf-8");
48217
- added.push(file2);
48218
- }
48219
- continue;
48220
- }
48221
- let exists = false;
48222
- try {
48223
- await (0, import_promises3.access)(filePath);
48224
- exists = true;
48225
- } catch {
48226
- }
48227
- if (!exists) {
48228
- await (0, import_promises3.mkdir)((0, import_path4.dirname)(filePath), { recursive: true });
48229
- await (0, import_promises3.writeFile)(filePath, templateContent, "utf-8");
48230
- added.push(file2);
48231
- } else {
48232
- const existingContent = await (0, import_promises3.readFile)(filePath, "utf-8");
48233
- const normalize = (s) => s.replace(/\r\n/g, "\n");
48234
- if (normalize(existingContent) === normalize(templateContent)) {
48235
- } else {
48236
- flagged.push(file2);
48237
- }
48238
- }
48239
- }
48240
- const OBSOLETE_FILES = [
48241
- ".claude/commands/work.md",
48242
- // v31: moved to .claude/skills/work/SKILL.md
48243
- ".claude/commands/meta.md",
48244
- // v33: split into init.md, status.md, fix.md, deploy.md, health.md
48245
- ".claude/commands/health.md"
48246
- // v33: moved to .claude/skills/diagnostics/SKILL.md
48247
- ];
48248
- const removed = [];
48249
- if (!upToDate) {
48250
- for (const file2 of OBSOLETE_FILES) {
48251
- const filePath = (0, import_path4.resolve)(cwd, file2);
48252
- try {
48253
- await (0, import_promises3.access)(filePath);
48254
- await (0, import_promises3.unlink)(filePath);
48255
- removed.push(file2);
48256
- } catch {
48257
- }
48258
- }
48259
- }
48260
- const uiAdded = [];
48261
- const uiSkipped = [];
48262
- if (options2.ui) {
48263
- const orgSlug = (0, import_path4.basename)(cwd).toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^[^a-z]+/, "").replace(/-+/g, "-").replace(/-$/, "") || "my-workspace";
48264
- await (0, import_promises3.mkdir)((0, import_path4.resolve)(cwd, "ui/src"), { recursive: true });
48265
- const uiFiles = getUIFiles(orgSlug);
48266
- for (const [file2, content] of Object.entries(uiFiles)) {
48267
- const filePath = (0, import_path4.resolve)(cwd, file2);
48268
- let exists = false;
48269
- try {
48270
- await (0, import_promises3.access)(filePath);
48271
- exists = true;
48272
- } catch {
48273
- }
48274
- if (!exists) {
48275
- await (0, import_promises3.writeFile)(filePath, content, "utf-8");
48276
- uiAdded.push(file2);
48277
- } else {
48278
- uiSkipped.push(file2);
48279
- }
48280
- }
48281
- }
48282
- console.log("");
48283
- if (upToDate) {
48284
- console.log(source_default.green.bold(` Added UI to project (template version ${TEMPLATE_VERSION})`));
48285
- } else {
48286
- console.log(source_default.green.bold(` Updated @elevasis/sdk template v${currentVersion} -> v${TEMPLATE_VERSION}`));
48287
- }
48288
- if (added.length > 0) {
48289
- console.log("");
48290
- console.log(" Added:");
48291
- for (const file2 of added) {
48292
- console.log(source_default.green(` ${file2}`));
48293
- }
48294
- }
48295
- if (removed.length > 0) {
48296
- console.log("");
48297
- console.log(" Removed (obsolete):");
48298
- for (const file2 of removed) {
48299
- console.log(source_default.red(` ${file2}`));
48300
- }
48301
- }
48302
- if (appendedGitignore.length > 0) {
48303
- console.log("");
48304
- console.log(" Appended to .gitignore:");
48305
- for (const entry of appendedGitignore) {
48306
- console.log(source_default.yellow(` ${entry}`));
48307
- }
48308
- }
48309
- if (flagged.length > 0) {
48310
- console.log("");
48311
- console.log(" Needs agent review:");
48312
- for (const file2 of flagged) {
48313
- console.log(source_default.cyan(` ${file2} (differs from template)`));
48314
- }
48315
- }
48316
- if (flagged.length > 0) {
48317
- console.log("");
48318
- console.log(source_default.gray(" Run /fix in Claude Code to verify and repair the full framework."));
48319
- }
48320
- if (mergedUpdated.length > 0 || mergedPreserved.length > 0) {
48321
- console.log("");
48322
- console.log(" CLAUDE.md sections:");
48323
- for (const section of mergedUpdated) {
48324
- console.log(source_default.green(` updated: ${section}`));
48325
- }
48326
- for (const section of mergedPreserved) {
48327
- console.log(source_default.gray(` preserved: ${section}`));
48328
- }
48329
- }
48330
- if (uiAdded.length > 0) {
48331
- console.log("");
48332
- console.log(" UI scaffold added:");
48333
- for (const file2 of uiAdded) {
48334
- console.log(source_default.green(` ${file2}`));
48335
- }
48336
- console.log("");
48337
- console.log(source_default.gray(" Next: cd ui && pnpm install"));
48338
- console.log(source_default.gray(" Set VITE_WORKOS_CLIENT_ID in ui/.env"));
48339
- }
48340
- if (uiSkipped.length > 0) {
48341
- console.log("");
48342
- console.log(" UI files already exist (skipped):");
48343
- for (const file2 of uiSkipped) {
48344
- console.log(source_default.gray(` ${file2}`));
48345
- }
48346
- }
48347
- console.log("");
48348
- })
48349
- );
48350
- }
45306
+ // src/cli/commands/creds/creds.ts
45307
+ init_config();
48351
45308
 
48352
45309
  // src/cli/commands/creds/creds-list.ts
48353
45310
  async function listCreds(apiUrl, json2) {
@@ -48498,10 +45455,10 @@ Credential renamed successfully!`));
48498
45455
  var import_readline = require("readline");
48499
45456
  function confirm(message) {
48500
45457
  const rl = (0, import_readline.createInterface)({ input: process.stdin, output: process.stdout });
48501
- return new Promise((resolve6) => {
45458
+ return new Promise((resolve4) => {
48502
45459
  rl.question(message, (answer) => {
48503
45460
  rl.close();
48504
- resolve6(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
45461
+ resolve4(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
48505
45462
  });
48506
45463
  });
48507
45464
  }
@@ -48559,6 +45516,9 @@ function registerCredsCommand(program3) {
48559
45516
  }));
48560
45517
  }
48561
45518
 
45519
+ // src/cli/commands/error/error.ts
45520
+ init_config();
45521
+
48562
45522
  // src/cli/commands/error/error-resolve.ts
48563
45523
  async function resolveError(apiUrl, errorId) {
48564
45524
  const spinner = ora("Resolving error...").start();
@@ -48595,6 +45555,7 @@ function registerErrorCommand(program3) {
48595
45555
  }
48596
45556
 
48597
45557
  // src/cli/commands/rename.ts
45558
+ init_config();
48598
45559
  function registerRenameCommand(program3) {
48599
45560
  program3.command("rename <oldResourceId>").description("Rename a resource ID across all platform tables (dry run by default)").requiredOption("--to <newResourceId>", "New resource ID").option("--execute", "Apply the rename (default: dry run preview only)").option("--prod", "Target production (overrides NODE_ENV=development)").option("--api-url <url>", "API URL").action(
48600
45561
  wrapAction("rename", async (oldResourceId, options2) => {
@@ -48632,8 +45593,638 @@ function registerRenameCommand(program3) {
48632
45593
  );
48633
45594
  }
48634
45595
 
45596
+ // src/cli/commands/project/projects.ts
45597
+ init_config();
45598
+ function registerProjectList(program3) {
45599
+ program3.command("project:list").description("List all projects\n Example: elevasis-sdk project:list --kind internal").option("--kind <kind>", "Filter by kind: client_engagement | internal | research | other").option("--status <status>", "Filter by status: active | on_track | at_risk | blocked | completed | paused").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45600
+ wrapAction("project:list", async (options2) => {
45601
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45602
+ const params = new URLSearchParams();
45603
+ if (options2.kind) params.set("kind", options2.kind);
45604
+ if (options2.status) params.set("status", options2.status);
45605
+ const qs = params.toString();
45606
+ const endpoint = `/api/external/projects${qs ? `?${qs}` : ""}`;
45607
+ const result = await apiGet(endpoint, apiUrl);
45608
+ if (options2.pretty) {
45609
+ const projects = result.projects;
45610
+ if (projects.length === 0) {
45611
+ console.log(source_default.yellow("No projects found."));
45612
+ return;
45613
+ }
45614
+ console.log(source_default.cyan(`
45615
+ Projects (${projects.length}):
45616
+ `));
45617
+ for (const p of projects) {
45618
+ console.log(` ${source_default.bold(p.name)} ${source_default.dim(p.kind)} ${source_default.gray(p.status)}`);
45619
+ console.log(source_default.gray(` ID: ${p.id}`));
45620
+ if (p.description) console.log(source_default.gray(` ${p.description}`));
45621
+ }
45622
+ console.log();
45623
+ } else {
45624
+ console.log(JSON.stringify(result, null, 2));
45625
+ }
45626
+ })
45627
+ );
45628
+ }
45629
+ function registerProjectGet(program3) {
45630
+ program3.command("project:get <id>").description("Get a project by ID\n Example: elevasis-sdk project:get <uuid>").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45631
+ wrapAction("project:get", async (id, options2) => {
45632
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45633
+ const result = await apiGet(`/api/external/projects/${id}`, apiUrl);
45634
+ if (options2.pretty) {
45635
+ const p = result.project;
45636
+ console.log(source_default.cyan(`
45637
+ Project: ${p.name}`));
45638
+ console.log(source_default.gray(` ID: ${p.id}`));
45639
+ console.log(source_default.gray(` Kind: ${p.kind}`));
45640
+ console.log(source_default.gray(` Status: ${p.status}`));
45641
+ if (p.description) console.log(source_default.gray(` Description: ${p.description}`));
45642
+ console.log();
45643
+ } else {
45644
+ console.log(JSON.stringify(result, null, 2));
45645
+ }
45646
+ })
45647
+ );
45648
+ }
45649
+ function registerProjectCreate(program3) {
45650
+ program3.command("project:create").description('Create a new project\n Example: elevasis-sdk project:create --name "My Project" --kind internal').requiredOption("--name <name>", "Project name").requiredOption("--kind <kind>", "Project kind: client_engagement | internal | research | other").option("--status <status>", "Project status: active | on_track | at_risk | blocked | completed | paused").option("--description <description>", "Project description").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45651
+ wrapAction(
45652
+ "project:create",
45653
+ async (options2) => {
45654
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45655
+ const body = {
45656
+ name: options2.name,
45657
+ kind: options2.kind
45658
+ };
45659
+ if (options2.status) body.status = options2.status;
45660
+ if (options2.description) body.description = options2.description;
45661
+ const result = await apiPost("/api/external/projects", body, apiUrl);
45662
+ if (options2.pretty) {
45663
+ const p = result.project;
45664
+ console.log(source_default.green(`
45665
+ Project created: ${p.name}`));
45666
+ console.log(source_default.gray(` ID: ${p.id}`));
45667
+ console.log(source_default.gray(` Kind: ${p.kind}`));
45668
+ console.log(source_default.gray(` Status: ${p.status}`));
45669
+ console.log();
45670
+ } else {
45671
+ console.log(JSON.stringify(result, null, 2));
45672
+ }
45673
+ }
45674
+ )
45675
+ );
45676
+ }
45677
+ function registerProjectUpdate(program3) {
45678
+ program3.command("project:update <id>").description("Update a project\n Example: elevasis-sdk project:update <uuid> --status completed").option("--name <name>", "New project name").option("--status <status>", "New status: active | on_track | at_risk | blocked | completed | paused").option("--description <description>", "New description").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45679
+ wrapAction(
45680
+ "project:update",
45681
+ async (id, options2) => {
45682
+ const body = {};
45683
+ if (options2.name !== void 0) body.name = options2.name;
45684
+ if (options2.status !== void 0) body.status = options2.status;
45685
+ if (options2.description !== void 0) body.description = options2.description;
45686
+ if (Object.keys(body).length === 0) {
45687
+ process.stderr.write(
45688
+ JSON.stringify({
45689
+ error: "At least one field must be provided (--name, --status, --description)",
45690
+ code: "MISSING_FIELDS"
45691
+ }) + "\n"
45692
+ );
45693
+ process.exit(1);
45694
+ }
45695
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45696
+ const result = await apiPatch(`/api/external/projects/${id}`, body, apiUrl);
45697
+ if (options2.pretty) {
45698
+ const p = result.project;
45699
+ console.log(source_default.green(`
45700
+ Project updated: ${p.name}`));
45701
+ console.log(source_default.gray(` Status: ${p.status}`));
45702
+ console.log();
45703
+ } else {
45704
+ console.log(JSON.stringify(result, null, 2));
45705
+ }
45706
+ }
45707
+ )
45708
+ );
45709
+ }
45710
+ function registerProjectDelete(program3) {
45711
+ program3.command("project:delete <id>").description("Delete a project\n Example: elevasis-sdk project:delete <uuid>").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45712
+ wrapAction("project:delete", async (id, options2) => {
45713
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45714
+ const result = await apiDelete(`/api/external/projects/${id}`, apiUrl);
45715
+ if (options2.pretty) {
45716
+ console.log(source_default.green(`
45717
+ Project ${id} deleted.`));
45718
+ console.log();
45719
+ } else {
45720
+ console.log(JSON.stringify(result, null, 2));
45721
+ }
45722
+ })
45723
+ );
45724
+ }
45725
+
45726
+ // src/cli/commands/project/milestones.ts
45727
+ init_config();
45728
+ function registerMilestoneList(program3) {
45729
+ program3.command("project:milestone:list").description("List milestones for a project\n Example: elevasis-sdk project:milestone:list --project <uuid>").requiredOption("--project <project-id>", "Project ID (UUID)").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45730
+ wrapAction("project:milestone:list", async (options2) => {
45731
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45732
+ const result = await apiGet(`/api/external/projects/${options2.project}/milestones`, apiUrl);
45733
+ if (options2.pretty) {
45734
+ const milestones = result.milestones;
45735
+ if (milestones.length === 0) {
45736
+ console.log(source_default.yellow("No milestones found."));
45737
+ return;
45738
+ }
45739
+ console.log(source_default.cyan(`
45740
+ Milestones (${milestones.length}):
45741
+ `));
45742
+ for (const m of milestones) {
45743
+ console.log(` ${source_default.bold(m.name)} ${source_default.gray(m.status)}`);
45744
+ console.log(source_default.gray(` ID: ${m.id}`));
45745
+ if (m.due_date) console.log(source_default.gray(` Due: ${m.due_date}`));
45746
+ }
45747
+ console.log();
45748
+ } else {
45749
+ console.log(JSON.stringify(result, null, 2));
45750
+ }
45751
+ })
45752
+ );
45753
+ }
45754
+ function registerMilestoneCreate(program3) {
45755
+ program3.command("project:milestone:create").description(
45756
+ 'Create a milestone\n Example: elevasis-sdk project:milestone:create --project <uuid> --name "Phase 1"'
45757
+ ).requiredOption("--project <project-id>", "Project ID (UUID)").requiredOption("--name <name>", "Milestone name").option("--status <status>", "Status: upcoming | in_progress | completed | overdue | blocked").option("--due-date <date>", "Due date (ISO 8601, e.g. 2026-06-01)").option("--description <description>", "Milestone description").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45758
+ wrapAction(
45759
+ "project:milestone:create",
45760
+ async (options2) => {
45761
+ const body = { name: options2.name };
45762
+ if (options2.status) body.status = options2.status;
45763
+ if (options2.dueDate) body.due_date = options2.dueDate;
45764
+ if (options2.description) body.description = options2.description;
45765
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45766
+ const result = await apiPost(
45767
+ `/api/external/projects/${options2.project}/milestones`,
45768
+ body,
45769
+ apiUrl
45770
+ );
45771
+ if (options2.pretty) {
45772
+ const m = result.milestone;
45773
+ console.log(source_default.green(`
45774
+ Milestone created: ${m.name}`));
45775
+ console.log(source_default.gray(` ID: ${m.id}`));
45776
+ console.log(source_default.gray(` Status: ${m.status}`));
45777
+ if (m.due_date) console.log(source_default.gray(` Due: ${m.due_date}`));
45778
+ console.log();
45779
+ } else {
45780
+ console.log(JSON.stringify(result, null, 2));
45781
+ }
45782
+ }
45783
+ )
45784
+ );
45785
+ }
45786
+ function registerMilestoneUpdate(program3) {
45787
+ program3.command("project:milestone:update <id>").description("Update a milestone\n Example: elevasis-sdk project:milestone:update <uuid> --status completed").option("--name <name>", "New milestone name").option("--status <status>", "New status: upcoming | in_progress | completed | overdue | blocked").option("--due-date <date>", "New due date (ISO 8601)").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45788
+ wrapAction(
45789
+ "project:milestone:update",
45790
+ async (id, options2) => {
45791
+ const body = {};
45792
+ if (options2.name !== void 0) body.name = options2.name;
45793
+ if (options2.status !== void 0) body.status = options2.status;
45794
+ if (options2.dueDate !== void 0) body.due_date = options2.dueDate;
45795
+ if (Object.keys(body).length === 0) {
45796
+ process.stderr.write(
45797
+ JSON.stringify({
45798
+ error: "At least one field must be provided (--name, --status, --due-date)",
45799
+ code: "MISSING_FIELDS"
45800
+ }) + "\n"
45801
+ );
45802
+ process.exit(1);
45803
+ }
45804
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45805
+ const result = await apiPatch(`/api/external/milestones/${id}`, body, apiUrl);
45806
+ if (options2.pretty) {
45807
+ const m = result.milestone;
45808
+ console.log(source_default.green(`
45809
+ Milestone updated: ${m.name}`));
45810
+ console.log(source_default.gray(` Status: ${m.status}`));
45811
+ console.log();
45812
+ } else {
45813
+ console.log(JSON.stringify(result, null, 2));
45814
+ }
45815
+ }
45816
+ )
45817
+ );
45818
+ }
45819
+ function registerMilestoneDelete(program3) {
45820
+ program3.command("project:milestone:delete <id>").description("Delete a milestone\n Example: elevasis-sdk project:milestone:delete <uuid>").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45821
+ wrapAction("project:milestone:delete", async (id, options2) => {
45822
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45823
+ const result = await apiDelete(`/api/external/milestones/${id}`, apiUrl);
45824
+ if (options2.pretty) {
45825
+ console.log(source_default.green(`
45826
+ Milestone ${id} deleted.`));
45827
+ console.log();
45828
+ } else {
45829
+ console.log(JSON.stringify(result, null, 2));
45830
+ }
45831
+ })
45832
+ );
45833
+ }
45834
+
45835
+ // src/cli/commands/project/tasks.ts
45836
+ init_config();
45837
+ function registerTaskList(program3) {
45838
+ program3.command("project:task:list").description(
45839
+ "List tasks for a project\n Example: elevasis-sdk project:task:list --project <uuid> --status in_progress"
45840
+ ).requiredOption("--project <project-id>", "Project ID (UUID)").option(
45841
+ "--status <status>",
45842
+ "Filter by status: planned | in_progress | blocked | completed | cancelled | submitted | approved | rejected | revision_requested"
45843
+ ).option("--milestone <milestone-id>", "Filter by milestone ID (UUID)").option("--parent <parent-task-id>", "Filter by parent task ID (UUID)").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45844
+ wrapAction(
45845
+ "project:task:list",
45846
+ async (options2) => {
45847
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45848
+ const params = new URLSearchParams();
45849
+ if (options2.status) params.set("status", options2.status);
45850
+ if (options2.milestone) params.set("milestone_id", options2.milestone);
45851
+ if (options2.parent) params.set("parent_task_id", options2.parent);
45852
+ const qs = params.toString();
45853
+ const endpoint = `/api/external/projects/${options2.project}/tasks${qs ? `?${qs}` : ""}`;
45854
+ const result = await apiGet(endpoint, apiUrl);
45855
+ if (options2.pretty) {
45856
+ const tasks = result.tasks;
45857
+ if (tasks.length === 0) {
45858
+ console.log(source_default.yellow("No tasks found."));
45859
+ return;
45860
+ }
45861
+ console.log(source_default.cyan(`
45862
+ Tasks (${tasks.length}):
45863
+ `));
45864
+ for (const t of tasks) {
45865
+ console.log(` ${source_default.bold(t.name)} ${source_default.dim(t.type ?? "")} ${source_default.gray(t.status)}`);
45866
+ console.log(source_default.gray(` ID: ${t.id}`));
45867
+ if (t.description) console.log(source_default.gray(` ${t.description}`));
45868
+ }
45869
+ console.log();
45870
+ } else {
45871
+ console.log(JSON.stringify(result, null, 2));
45872
+ }
45873
+ }
45874
+ )
45875
+ );
45876
+ }
45877
+ function registerTaskGet(program3) {
45878
+ program3.command("project:task:get <id>").description("Get a task by ID\n Example: elevasis-sdk project:task:get <uuid>").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45879
+ wrapAction("project:task:get", async (id, options2) => {
45880
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45881
+ const result = await apiGet(`/api/external/tasks/${id}`, apiUrl);
45882
+ if (options2.pretty) {
45883
+ const t = result.task;
45884
+ console.log(source_default.cyan(`
45885
+ Task: ${t.name}`));
45886
+ console.log(source_default.gray(` ID: ${t.id}`));
45887
+ console.log(source_default.gray(` Type: ${t.type ?? "other"}`));
45888
+ console.log(source_default.gray(` Status: ${t.status}`));
45889
+ if (t.description) console.log(source_default.gray(` Description: ${t.description}`));
45890
+ if (t.milestone_id) console.log(source_default.gray(` Milestone: ${t.milestone_id}`));
45891
+ console.log();
45892
+ } else {
45893
+ console.log(JSON.stringify(result, null, 2));
45894
+ }
45895
+ })
45896
+ );
45897
+ }
45898
+ function registerTaskCreate(program3) {
45899
+ program3.command("project:task:create").description(
45900
+ 'Create a task\n Example: elevasis-sdk project:task:create --project <uuid> --title "Implement feature"'
45901
+ ).requiredOption("--project <project-id>", "Project ID (UUID)").requiredOption("--title <title>", "Task title / name").option("--status <status>", "Status: planned | in_progress | blocked | completed | cancelled").option(
45902
+ "--type <type>",
45903
+ "Type: documentation | code | report | design | refactor | feature | bug | research | other"
45904
+ ).option("--milestone <milestone-id>", "Milestone ID (UUID)").option("--parent <parent-task-id>", "Parent task ID (UUID) for subtasks").option("--description <description>", "Task description").option("--checklist <json>", `Checklist items as JSON array: '[{"id":"1","label":"Step","completed":false}]'`).option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45905
+ wrapAction(
45906
+ "project:task:create",
45907
+ async (options2) => {
45908
+ const body = {
45909
+ project_id: options2.project,
45910
+ name: options2.title
45911
+ };
45912
+ if (options2.status) body.status = options2.status;
45913
+ if (options2.type) body.type = options2.type;
45914
+ if (options2.milestone) body.milestone_id = options2.milestone;
45915
+ if (options2.parent) body.parent_task_id = options2.parent;
45916
+ if (options2.description) body.description = options2.description;
45917
+ if (options2.checklist) {
45918
+ try {
45919
+ body.checklist = JSON.parse(options2.checklist);
45920
+ } catch {
45921
+ process.stderr.write(
45922
+ JSON.stringify({ error: "--checklist must be valid JSON", code: "INVALID_JSON" }) + "\n"
45923
+ );
45924
+ process.exit(1);
45925
+ }
45926
+ }
45927
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45928
+ const result = await apiPost("/api/external/tasks", body, apiUrl);
45929
+ if (options2.pretty) {
45930
+ const t = result.task;
45931
+ console.log(source_default.green(`
45932
+ Task created: ${t.name}`));
45933
+ console.log(source_default.gray(` ID: ${t.id}`));
45934
+ console.log(source_default.gray(` Status: ${t.status}`));
45935
+ console.log();
45936
+ } else {
45937
+ console.log(JSON.stringify(result, null, 2));
45938
+ }
45939
+ }
45940
+ )
45941
+ );
45942
+ }
45943
+ function registerTaskUpdate(program3) {
45944
+ program3.command("project:task:update <id>").description("Update a task\n Example: elevasis-sdk project:task:update <uuid> --status completed").option("--title <title>", "New task title").option(
45945
+ "--status <status>",
45946
+ "New status: planned | in_progress | blocked | completed | cancelled | submitted | approved | rejected | revision_requested"
45947
+ ).option("--milestone <milestone-id>", "New milestone ID (UUID)").option("--description <description>", "New description").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45948
+ wrapAction(
45949
+ "project:task:update",
45950
+ async (id, options2) => {
45951
+ const body = {};
45952
+ if (options2.title !== void 0) body.name = options2.title;
45953
+ if (options2.status !== void 0) body.status = options2.status;
45954
+ if (options2.milestone !== void 0) body.milestone_id = options2.milestone;
45955
+ if (options2.description !== void 0) body.description = options2.description;
45956
+ if (Object.keys(body).length === 0) {
45957
+ process.stderr.write(
45958
+ JSON.stringify({
45959
+ error: "At least one field must be provided (--title, --status, --milestone, --description)",
45960
+ code: "MISSING_FIELDS"
45961
+ }) + "\n"
45962
+ );
45963
+ process.exit(1);
45964
+ }
45965
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45966
+ const result = await apiPatch(`/api/external/tasks/${id}`, body, apiUrl);
45967
+ if (options2.pretty) {
45968
+ const t = result.task;
45969
+ console.log(source_default.green(`
45970
+ Task updated: ${t.name}`));
45971
+ console.log(source_default.gray(` Status: ${t.status}`));
45972
+ console.log();
45973
+ } else {
45974
+ console.log(JSON.stringify(result, null, 2));
45975
+ }
45976
+ }
45977
+ )
45978
+ );
45979
+ }
45980
+ function registerTaskDelete(program3) {
45981
+ program3.command("project:task:delete <id>").description("Delete a task\n Example: elevasis-sdk project:task:delete <uuid>").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
45982
+ wrapAction("project:task:delete", async (id, options2) => {
45983
+ const apiUrl = resolveApiUrl(options2.apiUrl);
45984
+ const result = await apiDelete(`/api/external/tasks/${id}`, apiUrl);
45985
+ if (options2.pretty) {
45986
+ console.log(source_default.green(`
45987
+ Task ${id} deleted.`));
45988
+ console.log();
45989
+ } else {
45990
+ console.log(JSON.stringify(result, null, 2));
45991
+ }
45992
+ })
45993
+ );
45994
+ }
45995
+ function registerTaskResume(program3) {
45996
+ program3.command("project:task:resume <id>").description(
45997
+ "Fetch the resume_context JSONB for a task (used by /work resume)\n Example: elevasis-sdk project:task:resume <uuid>"
45998
+ ).option("--api-url <url>", "API base URL").option("--pretty", "Render a human-readable resume briefing instead of raw JSON").action(
45999
+ wrapAction("project:task:resume", async (id, options2) => {
46000
+ const apiUrl = resolveApiUrl(options2.apiUrl);
46001
+ const result = await apiGet(`/api/external/tasks/${id}`, apiUrl);
46002
+ const task = result.task;
46003
+ const ctx = task.resume_context ?? {};
46004
+ if (options2.pretty) {
46005
+ console.log(source_default.cyan(`
46006
+ Resume briefing for task: ${task.name}`));
46007
+ console.log(source_default.gray(` Status: ${task.status}`));
46008
+ console.log();
46009
+ if (ctx.current_state) {
46010
+ console.log(source_default.bold("Current state:"));
46011
+ console.log(` ${ctx.current_state}`);
46012
+ console.log();
46013
+ }
46014
+ if (ctx.next_steps) {
46015
+ console.log(source_default.bold("Next steps:"));
46016
+ console.log(` ${ctx.next_steps}`);
46017
+ console.log();
46018
+ }
46019
+ if (Array.isArray(ctx.files_modified) && ctx.files_modified.length > 0) {
46020
+ console.log(source_default.bold("Files modified:"));
46021
+ for (const f of ctx.files_modified) console.log(` - ${f}`);
46022
+ console.log();
46023
+ }
46024
+ if (Array.isArray(ctx.key_docs) && ctx.key_docs.length > 0) {
46025
+ console.log(source_default.bold("Key docs:"));
46026
+ for (const d of ctx.key_docs) console.log(` - ${d}`);
46027
+ console.log();
46028
+ }
46029
+ if (Array.isArray(ctx.tools) && ctx.tools.length > 0) {
46030
+ console.log(source_default.bold("Tools used:"));
46031
+ for (const t of ctx.tools) console.log(` - ${t}`);
46032
+ console.log();
46033
+ }
46034
+ if (ctx.last_saved) {
46035
+ console.log(source_default.gray(`Last saved: ${ctx.last_saved}`));
46036
+ }
46037
+ } else {
46038
+ console.log(JSON.stringify(ctx, null, 2));
46039
+ }
46040
+ })
46041
+ );
46042
+ }
46043
+ function registerTaskSave(program3) {
46044
+ program3.command("project:task:save <id>").description(
46045
+ `Merge fields into resume_context for a task (used by /work save)
46046
+ Example: elevasis-sdk project:task:save <uuid> --current-state "Implemented X" --files-modified '["src/foo.ts"]'`
46047
+ ).requiredOption("--current-state <text>", "Current state description").option("--files-modified <json>", "JSON array of modified file paths").option("--next-steps <text>", "Next steps description").option("--key-docs <json>", "JSON array of key doc paths").option("--tools <json>", "JSON array of tool names used").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
46048
+ wrapAction(
46049
+ "project:task:save",
46050
+ async (id, options2) => {
46051
+ const body = {
46052
+ current_state: options2.currentState
46053
+ };
46054
+ if (options2.filesModified !== void 0) {
46055
+ try {
46056
+ body.files_modified = JSON.parse(options2.filesModified);
46057
+ } catch {
46058
+ process.stderr.write(
46059
+ JSON.stringify({ error: "--files-modified must be valid JSON array", code: "INVALID_JSON" }) + "\n"
46060
+ );
46061
+ process.exit(1);
46062
+ }
46063
+ }
46064
+ if (options2.nextSteps !== void 0) {
46065
+ body.next_steps = options2.nextSteps;
46066
+ }
46067
+ if (options2.keyDocs !== void 0) {
46068
+ try {
46069
+ body.key_docs = JSON.parse(options2.keyDocs);
46070
+ } catch {
46071
+ process.stderr.write(
46072
+ JSON.stringify({ error: "--key-docs must be valid JSON array", code: "INVALID_JSON" }) + "\n"
46073
+ );
46074
+ process.exit(1);
46075
+ }
46076
+ }
46077
+ if (options2.tools !== void 0) {
46078
+ try {
46079
+ body.tools = JSON.parse(options2.tools);
46080
+ } catch {
46081
+ process.stderr.write(
46082
+ JSON.stringify({ error: "--tools must be valid JSON array", code: "INVALID_JSON" }) + "\n"
46083
+ );
46084
+ process.exit(1);
46085
+ }
46086
+ }
46087
+ const apiUrl = resolveApiUrl(options2.apiUrl);
46088
+ const result = await apiPatch(`/api/external/tasks/${id}/resume-context`, body, apiUrl);
46089
+ if (options2.pretty) {
46090
+ console.log(source_default.green(`
46091
+ Resume context saved for task ${id}`));
46092
+ if (result.task?.resume_context) {
46093
+ const ctx = result.task.resume_context;
46094
+ if (ctx.last_saved) console.log(source_default.gray(` Saved at: ${ctx.last_saved}`));
46095
+ }
46096
+ console.log();
46097
+ } else {
46098
+ console.log(JSON.stringify(result, null, 2));
46099
+ }
46100
+ }
46101
+ )
46102
+ );
46103
+ }
46104
+
46105
+ // src/cli/commands/project/notes.ts
46106
+ init_config();
46107
+ function registerNoteList(program3) {
46108
+ program3.command("project:note:list").description("List notes for a project\n Example: elevasis-sdk project:note:list --project <uuid>").requiredOption("--project <project-id>", "Project ID (UUID)").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
46109
+ wrapAction("project:note:list", async (options2) => {
46110
+ const apiUrl = resolveApiUrl(options2.apiUrl);
46111
+ const result = await apiGet(`/api/external/projects/${options2.project}/notes`, apiUrl);
46112
+ if (options2.pretty) {
46113
+ const notes = result.notes;
46114
+ if (notes.length === 0) {
46115
+ console.log(source_default.yellow("No notes found."));
46116
+ return;
46117
+ }
46118
+ console.log(source_default.cyan(`
46119
+ Notes (${notes.length}):
46120
+ `));
46121
+ for (const n of notes) {
46122
+ console.log(` ${source_default.bold(n.type ?? "status_update")} ${source_default.gray(n.occurred_at ?? "")}`);
46123
+ console.log(source_default.gray(` ID: ${n.id}`));
46124
+ console.log(source_default.gray(` ${n.content.slice(0, 120)}${n.content.length > 120 ? "..." : ""}`));
46125
+ console.log();
46126
+ }
46127
+ } else {
46128
+ console.log(JSON.stringify(result, null, 2));
46129
+ }
46130
+ })
46131
+ );
46132
+ }
46133
+ function registerNoteCreate(program3) {
46134
+ program3.command("project:note:create").description(
46135
+ 'Create a note\n Example: elevasis-sdk project:note:create --project <uuid> --content "Status update"'
46136
+ ).requiredOption("--project <project-id>", "Project ID (UUID)").requiredOption("--content <content>", "Note content").option("--task <task-id>", "Attach to a task (UUID)").option("--milestone <milestone-id>", "Attach to a milestone (UUID)").option("--type <type>", "Note type: call_note | status_update | issue | blocker").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
46137
+ wrapAction(
46138
+ "project:note:create",
46139
+ async (options2) => {
46140
+ const body = {
46141
+ project_id: options2.project,
46142
+ content: options2.content
46143
+ };
46144
+ if (options2.task) body.task_id = options2.task;
46145
+ if (options2.milestone) body.milestone_id = options2.milestone;
46146
+ if (options2.type) body.type = options2.type;
46147
+ const apiUrl = resolveApiUrl(options2.apiUrl);
46148
+ const result = await apiPost("/api/external/notes", body, apiUrl);
46149
+ if (options2.pretty) {
46150
+ const n = result.note;
46151
+ console.log(source_default.green(`
46152
+ Note created`));
46153
+ console.log(source_default.gray(` ID: ${n.id}`));
46154
+ console.log(source_default.gray(` Type: ${n.type}`));
46155
+ console.log();
46156
+ } else {
46157
+ console.log(JSON.stringify(result, null, 2));
46158
+ }
46159
+ }
46160
+ )
46161
+ );
46162
+ }
46163
+ function registerNoteUpdate(program3) {
46164
+ program3.command("project:note:update <id>").description('Update a note\n Example: elevasis-sdk project:note:update <uuid> --content "Updated content"').requiredOption("--content <content>", "New note content").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
46165
+ wrapAction("project:note:update", async (id, options2) => {
46166
+ const apiUrl = resolveApiUrl(options2.apiUrl);
46167
+ const result = await apiPatch(`/api/external/notes/${id}`, { content: options2.content }, apiUrl);
46168
+ if (options2.pretty) {
46169
+ console.log(source_default.green(`
46170
+ Note ${id} updated.`));
46171
+ console.log();
46172
+ } else {
46173
+ console.log(JSON.stringify(result, null, 2));
46174
+ }
46175
+ })
46176
+ );
46177
+ }
46178
+ function registerNoteDelete(program3) {
46179
+ program3.command("project:note:delete <id>").description("Delete a note\n Example: elevasis-sdk project:note:delete <uuid>").option("--api-url <url>", "API base URL").option("--pretty", "Render human-readable output instead of raw JSON").action(
46180
+ wrapAction("project:note:delete", async (id, options2) => {
46181
+ const apiUrl = resolveApiUrl(options2.apiUrl);
46182
+ const result = await apiDelete(`/api/external/notes/${id}`, apiUrl);
46183
+ if (options2.pretty) {
46184
+ console.log(source_default.green(`
46185
+ Note ${id} deleted.`));
46186
+ console.log();
46187
+ } else {
46188
+ console.log(JSON.stringify(result, null, 2));
46189
+ }
46190
+ })
46191
+ );
46192
+ }
46193
+
46194
+ // src/cli/commands/project/project.ts
46195
+ function registerProjectCommands(program3) {
46196
+ registerProjectList(program3);
46197
+ registerProjectGet(program3);
46198
+ registerProjectCreate(program3);
46199
+ registerProjectUpdate(program3);
46200
+ registerProjectDelete(program3);
46201
+ registerMilestoneList(program3);
46202
+ registerMilestoneCreate(program3);
46203
+ registerMilestoneUpdate(program3);
46204
+ registerMilestoneDelete(program3);
46205
+ registerTaskList(program3);
46206
+ registerTaskGet(program3);
46207
+ registerTaskCreate(program3);
46208
+ registerTaskUpdate(program3);
46209
+ registerTaskDelete(program3);
46210
+ registerTaskResume(program3);
46211
+ registerTaskSave(program3);
46212
+ registerNoteList(program3);
46213
+ registerNoteCreate(program3);
46214
+ registerNoteUpdate(program3);
46215
+ registerNoteDelete(program3);
46216
+ }
46217
+
48635
46218
  // src/cli/index.ts
48636
- (0, import_dotenv.config)({ path: (0, import_path5.resolve)(process.cwd(), ".env"), override: true });
46219
+ init_config();
46220
+ var envPath = findEnvFile();
46221
+ if (envPath) {
46222
+ (0, import_dotenv.config)({ path: envPath, override: true });
46223
+ } else if (!process.env.ELEVASIS_PLATFORM_KEY) {
46224
+ const cwd = process.cwd();
46225
+ console.error(source_default.yellow(`\u26A0 No .env file found (searched upward from ${cwd})`));
46226
+ console.error(source_default.gray(" Set ELEVASIS_PLATFORM_KEY in a .env at your project root."));
46227
+ }
48637
46228
  var program2 = new Command();
48638
46229
  program2.name("elevasis-sdk").description(
48639
46230
  source_default.cyan("Elevasis SDK CLI") + `
@@ -48648,8 +46239,6 @@ Commands:
48648
46239
  elevasis-sdk execution <resourceId> <id> Get execution details
48649
46240
  elevasis-sdk deployments List deployments
48650
46241
  elevasis-sdk rename <id> --to <newId> [--prod] Rename resource across platform tables
48651
- elevasis-sdk update Update workspace scaffold to latest template
48652
- elevasis-sdk init [directory] Scaffold a new workspace
48653
46242
 
48654
46243
  Use "elevasis-sdk <command> --help" for more information about a command.`
48655
46244
  ).version(SDK_VERSION);
@@ -48661,11 +46250,10 @@ registerExecutionsCommand(program2);
48661
46250
  registerExecutionCommand(program2);
48662
46251
  registerDescribeCommand(program2);
48663
46252
  registerDeploymentsCommand(program2);
48664
- registerInitCommand(program2);
48665
- registerUpdateCommand(program2);
48666
46253
  registerCredsCommand(program2);
48667
46254
  registerErrorCommand(program2);
48668
46255
  registerRenameCommand(program2);
46256
+ registerProjectCommands(program2);
48669
46257
  program2.parse();
48670
46258
  /*! Bundled license information:
48671
46259