@motionskit/cli 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @motionskit/cli
2
2
 
3
- `motions init`, `check`, `test`, `push`, `pull`, `open`, `retry`, `cancel`, `help` and `--version`.
3
+ `motions init`, `check`, `test`, `run`, `push`, `pull`, `open`, `retry`, `cancel`, `help` and `--version`.
4
4
 
5
- From a directory with `tenant.yaml`, `motions push` publishes a draft and prints a link. `motions push --live` makes it the version new batches open on. `MOTIONS_URL` defaults to `https://motions.pruma.tech`. `MOTIONS_TOKEN` is an API key (`mot_…`) sent as `authorization: Bearer`.
5
+ From a directory with `tenant.yaml`, `motions push` publishes a draft and prints a link. `motions push --live` makes it the version new batches open on. `motions run [motion] <step>` runs one step in isolation on the engine (printing JSON with facts, proposals, logs, source calls and cost, without writing to the CRM or altering batches). `MOTIONS_URL` defaults to `https://motions.pruma.tech`. `MOTIONS_TOKEN` is an API key (`mot_…`) sent as `authorization: Bearer`.
6
6
 
7
7
  Inside the motions repo, `motions publish [tenant]` is `push --live` over `tenants/*` (defaulting `MOTIONS_URL` to `http://localhost:8787`).
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { FixtureEntry, SourceVersion, MotionVersion, Json, MotionHandleWarning } from '@motionskit/kernel';
1
+ import { FixtureEntry, SourceVersion, MotionVersion, CrmGrant, Caps, CalendarSpec, Json, MotionHandleWarning } from '@motionskit/kernel';
2
2
 
3
3
  /** `tenant.yaml`'s `sources.fixtures` switch and every entry of `fixtures/sources/*.json`, in the order the gateway matches them. */
4
4
  type TenantFixtures = {
@@ -49,6 +49,26 @@ declare function compileMotion(tenant: {
49
49
  timezone: string;
50
50
  }, dir: string, catalog?: Set<string>): Promise<Compiled>;
51
51
  declare function compileTenant(tenantDir: string): Promise<Tenant>;
52
+ type CompiledStep = {
53
+ tenant: string;
54
+ motion: string;
55
+ step: string;
56
+ local: {
57
+ kind: "company" | "batch";
58
+ bundle: string;
59
+ bundleSha: string;
60
+ sources: string[];
61
+ crm: CrmGrant;
62
+ cap?: Caps;
63
+ title: string;
64
+ timezone: string;
65
+ calendar: Record<string, CalendarSpec>;
66
+ reasons: string[];
67
+ rules: Record<string, Json>;
68
+ };
69
+ };
70
+ /** Compiles only one step of a local motion (its bundle + manifest metadata) for isolated execution via `motions run`. */
71
+ declare function compileStep(tenantDir: string, motionName: string, stepId: string): Promise<CompiledStep>;
52
72
 
53
73
  type PublishWarningsInput = {
54
74
  warning?: string;
@@ -58,4 +78,4 @@ type PublishWarningsInput = {
58
78
  /** Formats non-blocking warnings returned when publishing a motion version. */
59
79
  declare function formatPublishWarnings(tenant: string, motion: string, out: PublishWarningsInput): string[];
60
80
 
61
- export { type Compiled, type CompiledSource, type PublishWarningsInput, type Tenant, compileMotion, compileSource, compileSources, compileTenant, findTenantDir, formatPublishWarnings, monorepoTenants, tenantIdentity, tenantsDir };
81
+ export { type Compiled, type CompiledSource, type CompiledStep, type PublishWarningsInput, type Tenant, compileMotion, compileSource, compileSources, compileStep, compileTenant, findTenantDir, formatPublishWarnings, monorepoTenants, tenantIdentity, tenantsDir };
package/dist/index.js CHANGED
@@ -634,6 +634,74 @@ async function compileTenant(tenantDir) {
634
634
  }
635
635
  return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources, fixtures, motions };
636
636
  }
637
+ async function compileStep(tenantDir, motionName, stepId) {
638
+ const dir = resolve2(tenantDir);
639
+ const rawMeta = readYaml(join4(dir, "tenant.yaml"), "tenant.yaml");
640
+ const parsedMeta = parseTenant(rawMeta);
641
+ if (!parsedMeta.ok) {
642
+ if (parsedMeta.errors.length === 1) throw new Error(`tenant.yaml: ${parsedMeta.errors[0]}`);
643
+ throw new MotionErrors("tenant.yaml", parsedMeta.errors);
644
+ }
645
+ const meta = parsedMeta.tenant;
646
+ const tenantId2 = meta.id ?? folderName(dir);
647
+ const tenantTz = meta.timezone ?? "America/Sao_Paulo";
648
+ const motionDir = join4(dir, "motions", motionName);
649
+ const motionYamlPath = join4(motionDir, "motion.yaml");
650
+ if (!existsSync3(motionYamlPath)) {
651
+ const { motions } = tenantIdentity(dir);
652
+ throw new Error(`motion "${motionName}" does not exist in ${tenantId2}${motions.length ? ` (available: ${motions.join(", ")})` : ""}`);
653
+ }
654
+ const where2 = `${tenantId2}/${motionName}/motion.yaml`;
655
+ const parsed = parseMotion(readYaml(motionYamlPath, `motions/${motionName}/motion.yaml`));
656
+ if (!parsed.ok) throw new MotionErrors(where2, parsed.errors);
657
+ const raw = parsed.motion;
658
+ const stepDef = raw.steps.find((s) => s.id === stepId);
659
+ if (!stepDef) {
660
+ const runnable = raw.steps.filter((s) => (s.kind ?? "company") === "company" || s.kind === "batch").map((s) => s.id);
661
+ throw new Error(`step "${stepId}" is not in ${tenantId2}/${motionName}${runnable.length ? ` (runnable: ${runnable.join(", ")})` : ""}`);
662
+ }
663
+ const kind = stepDef.kind ?? "company";
664
+ if (kind !== "company" && kind !== "batch") {
665
+ throw new Error(`step "${stepId}" is a ${kind} step; only company and batch steps can be run`);
666
+ }
667
+ const file = resolve2(motionDir, stepDef.run);
668
+ if (!existsSync3(file)) throw new MotionErrors(where2, [`${stepDef.run} does not exist`]);
669
+ const { code, inputs } = await bundle(file, dir);
670
+ const bundleSha = sha2562(code);
671
+ const bundleProblem = bundleUploadProblem2(bundleSha, code);
672
+ const root = resolve2(motionDir);
673
+ const stepFiles = {};
674
+ for (const input of inputs) {
675
+ const rel = relative2(root, input);
676
+ if (!rel.startsWith("..") && !isAbsolute2(rel) && !rel.split(sep2).includes("node_modules")) {
677
+ stepFiles[rel.split(sep2).join("/")] = readFileSync3(input, "utf8");
678
+ }
679
+ }
680
+ const reasons = raw.reasons ?? [];
681
+ const problems = [...bundleProblem ? [bundleProblem] : [], ...optionReasonProblems(reasons, stepFiles)];
682
+ if (problems.length) throw new MotionErrors(where2, problems);
683
+ const rulesPath = join4(motionDir, "rules.yaml");
684
+ const rules = existsSync3(rulesPath) ? readYaml(rulesPath, `motions/${motionName}/rules.yaml`) ?? {} : {};
685
+ const motion = raw.motion ?? motionName;
686
+ return {
687
+ tenant: tenantId2,
688
+ motion,
689
+ step: stepId,
690
+ local: {
691
+ kind,
692
+ bundle: code,
693
+ bundleSha,
694
+ sources: stepDef.sources ?? [],
695
+ crm: grant(stepDef.crm),
696
+ ...stepDef.cap ? { cap: stepDef.cap } : {},
697
+ title: raw.title ?? motion,
698
+ timezone: raw.timezone ?? tenantTz,
699
+ calendar: raw.calendar ?? {},
700
+ reasons,
701
+ rules
702
+ }
703
+ };
704
+ }
637
705
 
638
706
  // src/publish.ts
639
707
  function formatPublishWarnings(tenant, motion, out) {
@@ -653,6 +721,7 @@ export {
653
721
  compileMotion,
654
722
  compileSource,
655
723
  compileSources,
724
+ compileStep,
656
725
  compileTenant,
657
726
  findTenantDir,
658
727
  formatPublishWarnings,
package/dist/main.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/main.ts
4
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
5
- import { basename as basename2, dirname as dirname6, join as join9, resolve as resolve6 } from "path";
4
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync4 } from "fs";
5
+ import { basename as basename2, dirname as dirname6, join as join9, resolve as resolve7 } from "path";
6
6
  import { createInterface } from "readline/promises";
7
7
  import { parseArgs } from "util";
8
8
 
@@ -197,7 +197,21 @@ function formatDetails(details) {
197
197
  }
198
198
  return "";
199
199
  }
200
- function describeFailure(path, status, text) {
200
+ var ApiError = class extends Error {
201
+ constructor(message, status, code, apiMessage, details) {
202
+ super(message);
203
+ this.status = status;
204
+ this.code = code;
205
+ this.apiMessage = apiMessage;
206
+ this.details = details;
207
+ this.name = "ApiError";
208
+ }
209
+ status;
210
+ code;
211
+ apiMessage;
212
+ details;
213
+ };
214
+ function parseFailure(status, text) {
201
215
  let code;
202
216
  let message = text.trim();
203
217
  let details;
@@ -210,6 +224,10 @@ function describeFailure(path, status, text) {
210
224
  }
211
225
  } catch {
212
226
  }
227
+ return { code, message, details };
228
+ }
229
+ function describeFailure(path, status, text) {
230
+ const { code, message, details } = parseFailure(status, text);
213
231
  const extra = formatDetails(details);
214
232
  if (status === 401) return `${code ? `unauthorized (${code}): ${message}` : `unauthorized: ${message}`}${extra}`;
215
233
  if (status === 403) return `${code ? `forbidden (${code}): ${message}` : `forbidden: ${message}`}${extra}`;
@@ -232,10 +250,14 @@ async function api(url2, path, body, tenant) {
232
250
  } catch (e) {
233
251
  const cause = e?.cause;
234
252
  const reason = cause?.message ?? cause?.code ?? (e instanceof Error ? e.message : String(e));
235
- throw new Error(`could not reach ${base} (${path}): ${reason}. Set MOTIONS_URL or pass --url if the server is elsewhere.`);
253
+ const msg = `could not reach ${base} (${path}): ${reason}. Set MOTIONS_URL or pass --url if the server is elsewhere.`;
254
+ throw new ApiError(msg, 0, "network", msg);
236
255
  }
237
256
  const text = await res.text();
238
- if (!res.ok) throw new Error(describeFailure(path, res.status, text));
257
+ if (!res.ok) {
258
+ const parsed2 = parseFailure(res.status, text);
259
+ throw new ApiError(describeFailure(path, res.status, text), res.status, parsed2.code ?? `http_${res.status}`, parsed2.message, parsed2.details);
260
+ }
239
261
  return text ? JSON.parse(text) : {};
240
262
  }
241
263
 
@@ -955,6 +977,74 @@ function tenantCrmProblems(tenant, systems = CRM_WRITES) {
955
977
  }
956
978
  return problems;
957
979
  }
980
+ async function compileStep(tenantDir, motionName, stepId) {
981
+ const dir = resolve2(tenantDir);
982
+ const rawMeta = readYaml(join5(dir, "tenant.yaml"), "tenant.yaml");
983
+ const parsedMeta = parseTenant(rawMeta);
984
+ if (!parsedMeta.ok) {
985
+ if (parsedMeta.errors.length === 1) throw new Error(`tenant.yaml: ${parsedMeta.errors[0]}`);
986
+ throw new MotionErrors("tenant.yaml", parsedMeta.errors);
987
+ }
988
+ const meta = parsedMeta.tenant;
989
+ const tenantId2 = meta.id ?? folderName(dir);
990
+ const tenantTz = meta.timezone ?? "America/Sao_Paulo";
991
+ const motionDir = join5(dir, "motions", motionName);
992
+ const motionYamlPath = join5(motionDir, "motion.yaml");
993
+ if (!existsSync4(motionYamlPath)) {
994
+ const { motions } = tenantIdentity(dir);
995
+ throw new Error(`motion "${motionName}" does not exist in ${tenantId2}${motions.length ? ` (available: ${motions.join(", ")})` : ""}`);
996
+ }
997
+ const where2 = `${tenantId2}/${motionName}/motion.yaml`;
998
+ const parsed2 = parseMotion(readYaml(motionYamlPath, `motions/${motionName}/motion.yaml`));
999
+ if (!parsed2.ok) throw new MotionErrors(where2, parsed2.errors);
1000
+ const raw = parsed2.motion;
1001
+ const stepDef = raw.steps.find((s) => s.id === stepId);
1002
+ if (!stepDef) {
1003
+ const runnable = raw.steps.filter((s) => (s.kind ?? "company") === "company" || s.kind === "batch").map((s) => s.id);
1004
+ throw new Error(`step "${stepId}" is not in ${tenantId2}/${motionName}${runnable.length ? ` (runnable: ${runnable.join(", ")})` : ""}`);
1005
+ }
1006
+ const kind = stepDef.kind ?? "company";
1007
+ if (kind !== "company" && kind !== "batch") {
1008
+ throw new Error(`step "${stepId}" is a ${kind} step; only company and batch steps can be run`);
1009
+ }
1010
+ const file2 = resolve2(motionDir, stepDef.run);
1011
+ if (!existsSync4(file2)) throw new MotionErrors(where2, [`${stepDef.run} does not exist`]);
1012
+ const { code, inputs } = await bundle(file2, dir);
1013
+ const bundleSha = sha2562(code);
1014
+ const bundleProblem = bundleUploadProblem2(bundleSha, code);
1015
+ const root = resolve2(motionDir);
1016
+ const stepFiles = {};
1017
+ for (const input of inputs) {
1018
+ const rel = relative2(root, input);
1019
+ if (!rel.startsWith("..") && !isAbsolute2(rel) && !rel.split(sep2).includes("node_modules")) {
1020
+ stepFiles[rel.split(sep2).join("/")] = readFileSync4(input, "utf8");
1021
+ }
1022
+ }
1023
+ const reasons = raw.reasons ?? [];
1024
+ const problems = [...bundleProblem ? [bundleProblem] : [], ...optionReasonProblems(reasons, stepFiles)];
1025
+ if (problems.length) throw new MotionErrors(where2, problems);
1026
+ const rulesPath = join5(motionDir, "rules.yaml");
1027
+ const rules = existsSync4(rulesPath) ? readYaml(rulesPath, `motions/${motionName}/rules.yaml`) ?? {} : {};
1028
+ const motion = raw.motion ?? motionName;
1029
+ return {
1030
+ tenant: tenantId2,
1031
+ motion,
1032
+ step: stepId,
1033
+ local: {
1034
+ kind,
1035
+ bundle: code,
1036
+ bundleSha,
1037
+ sources: stepDef.sources ?? [],
1038
+ crm: grant(stepDef.crm),
1039
+ ...stepDef.cap ? { cap: stepDef.cap } : {},
1040
+ title: raw.title ?? motion,
1041
+ timezone: raw.timezone ?? tenantTz,
1042
+ calendar: raw.calendar ?? {},
1043
+ reasons,
1044
+ rules
1045
+ }
1046
+ };
1047
+ }
958
1048
 
959
1049
  // src/init.ts
960
1050
  import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
@@ -1200,20 +1290,358 @@ function formatPublishWarnings(tenant, motion, out) {
1200
1290
  return lines;
1201
1291
  }
1202
1292
 
1293
+ // src/run.ts
1294
+ import { readFileSync as readFileSync6 } from "fs";
1295
+ import { resolve as resolve4 } from "path";
1296
+ import {
1297
+ upstreamOf
1298
+ } from "@motionskit/kernel";
1299
+ function isRecord(v) {
1300
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1301
+ }
1302
+ function parseJsonObjectArg(raw, flag, readText = (p) => readFileSync6(p, "utf8")) {
1303
+ const trimmed = raw.trim();
1304
+ if (!trimmed) throw new Error(`${flag} needs a JSON object or @file path`);
1305
+ let text;
1306
+ if (trimmed.startsWith("@")) {
1307
+ const filePath = trimmed.slice(1);
1308
+ if (!filePath) throw new Error(`${flag} needs a file path after @`);
1309
+ try {
1310
+ text = readText(filePath);
1311
+ } catch (e) {
1312
+ throw new Error(`${flag}: could not read ${filePath}: ${e.message}`);
1313
+ }
1314
+ } else {
1315
+ text = trimmed;
1316
+ }
1317
+ let parsed2;
1318
+ try {
1319
+ parsed2 = JSON.parse(text);
1320
+ } catch (e) {
1321
+ throw new Error(`${flag}: invalid JSON: ${e.message}`);
1322
+ }
1323
+ if (!isRecord(parsed2)) throw new Error(`${flag} must be a JSON object`);
1324
+ return parsed2;
1325
+ }
1326
+ function readInputPayload(source, readText = (p) => readFileSync6(p, "utf8"), readStdin = () => readFileSync6(0, "utf8")) {
1327
+ let text;
1328
+ try {
1329
+ text = source === "-" ? readStdin() : readText(source);
1330
+ } catch (e) {
1331
+ throw new Error(`--input: could not read ${source === "-" ? "stdin" : source}: ${e.message}`);
1332
+ }
1333
+ let parsed2;
1334
+ try {
1335
+ parsed2 = JSON.parse(text);
1336
+ } catch (e) {
1337
+ throw new Error(`--input: invalid JSON: ${e.message}`);
1338
+ }
1339
+ if (!isRecord(parsed2)) throw new Error("--input must contain a JSON object");
1340
+ return parsed2;
1341
+ }
1342
+ function mergeCompanyInput(base, overlay) {
1343
+ if (!base) return overlay ? { ...overlay } : {};
1344
+ if (!overlay) return { ...base };
1345
+ const mergedCore = base.core || overlay.core ? {
1346
+ ...base.core,
1347
+ ...overlay.core,
1348
+ ...base.core?.crm || overlay.core?.crm ? { crm: { ...base.core?.crm, ...overlay.core?.crm } } : {}
1349
+ } : void 0;
1350
+ return {
1351
+ ...base,
1352
+ ...overlay,
1353
+ ...mergedCore ? { core: mergedCore } : {},
1354
+ ...base.fields || overlay.fields ? { fields: { ...base.fields, ...overlay.fields } } : {},
1355
+ ...base.input || overlay.input ? { input: { ...base.input, ...overlay.input } } : {},
1356
+ ...base.facts || overlay.facts ? { facts: { ...base.facts, ...overlay.facts } } : {},
1357
+ ...base.answers || overlay.answers ? { answers: { ...base.answers, ...overlay.answers } } : {}
1358
+ };
1359
+ }
1360
+ function findBatchCompany(companies, query) {
1361
+ return companies.find((c) => c.key === query) ?? companies.find((c) => c.key.endsWith(`:${query}`));
1362
+ }
1363
+ function extractFromBatch(snap, stepId, opts) {
1364
+ const opened = snap.events.find((e) => e.type === "batch.opened");
1365
+ const records = /* @__PURE__ */ new Map();
1366
+ for (const e of snap.events) {
1367
+ if (e.type === "company.added") records.set(e.company, e.record);
1368
+ }
1369
+ const up = upstreamOf(snap.motion.steps);
1370
+ const excluded = /* @__PURE__ */ new Set([stepId]);
1371
+ for (const s of snap.motion.steps) {
1372
+ if (up.get(s.id)?.includes(stepId)) excluded.add(s.id);
1373
+ }
1374
+ const toInput = (key) => {
1375
+ const statusCo = snap.status.companies.find((c) => c.key === key);
1376
+ const rec = records.get(key);
1377
+ const facts = {};
1378
+ for (const [k, v] of Object.entries(statusCo?.facts ?? {})) {
1379
+ if (!excluded.has(k)) facts[k] = v;
1380
+ }
1381
+ const answers = snap.status.answers[key]?.[stepId] ?? {};
1382
+ return {
1383
+ key,
1384
+ ...rec ? {
1385
+ core: { ...rec.core, crm: { ...rec.core.crm } },
1386
+ fields: { ...rec.fields },
1387
+ ...rec.input ? { input: { ...rec.input } } : {}
1388
+ } : {},
1389
+ facts,
1390
+ ...Object.keys(answers).length ? { answers: { ...answers } } : {}
1391
+ };
1392
+ };
1393
+ const stepDef = snap.motion.steps.find((s) => s.id === stepId);
1394
+ const effectiveKind = opts.kind ?? (stepDef && (stepDef.kind === "company" || stepDef.kind === "batch") ? stepDef.kind : "company");
1395
+ const calendar = opened?.calendar ?? {};
1396
+ const openedAt = opened?.at ?? snap.status.openedAt;
1397
+ if (opts.companies?.length) {
1398
+ const matched = opts.companies.map((q) => {
1399
+ const found = findBatchCompany(snap.status.companies, q);
1400
+ if (!found) throw new Error(`no company ${q} in batch ${snap.status.batch}`);
1401
+ return toInput(found.key);
1402
+ });
1403
+ return { companies: matched, calendar, openedAt };
1404
+ }
1405
+ if (opts.company) {
1406
+ const found = findBatchCompany(snap.status.companies, opts.company);
1407
+ if (!found) throw new Error(`no company ${opts.company} in batch ${snap.status.batch}`);
1408
+ return effectiveKind === "batch" ? { companies: [toInput(found.key)], calendar, openedAt } : { company: toInput(found.key), calendar, openedAt };
1409
+ }
1410
+ if (effectiveKind === "batch") {
1411
+ return { companies: snap.status.companies.map((c) => toInput(c.key)), calendar, openedAt };
1412
+ }
1413
+ const examples = snap.status.companies.slice(0, 5).map((c) => c.key).join(", ");
1414
+ throw new Error(`--from-batch needs --company <id> for a company step${examples ? ` (e.g. ${examples})` : ""}`);
1415
+ }
1416
+ function stepRunFailed(res) {
1417
+ if (res.kind === "company") return res.result?.status === "failed";
1418
+ return Object.values(res.results ?? {}).some((r) => r.status === "failed");
1419
+ }
1420
+ function formatCliErrorJson(err) {
1421
+ if (err instanceof ApiError) {
1422
+ return JSON.stringify(
1423
+ {
1424
+ error: {
1425
+ code: err.code,
1426
+ message: err.apiMessage,
1427
+ ...err.status ? { status: err.status } : {},
1428
+ ...err.details !== void 0 ? { details: err.details } : {}
1429
+ }
1430
+ },
1431
+ null,
1432
+ 2
1433
+ );
1434
+ }
1435
+ if (err instanceof MotionErrors) {
1436
+ return JSON.stringify(
1437
+ {
1438
+ error: {
1439
+ code: "compile_error",
1440
+ message: `${err.where}: ${err.errors[0] ?? err.message}`,
1441
+ details: { where: err.where, errors: err.errors }
1442
+ }
1443
+ },
1444
+ null,
1445
+ 2
1446
+ );
1447
+ }
1448
+ const message = err instanceof Error ? err.message : String(err);
1449
+ return JSON.stringify({ error: { code: "cli_error", message } }, null, 2);
1450
+ }
1451
+ async function resolveSha(call, tenant, motion, version) {
1452
+ if (/^[0-9a-f]{64}$/.test(version)) return version;
1453
+ const listed = await call(
1454
+ `/api/tenants/${encodeURIComponent(tenant)}/motions/${encodeURIComponent(motion)}/versions`,
1455
+ void 0,
1456
+ tenant
1457
+ );
1458
+ const matches = listed.versions.filter((v) => v.sha.startsWith(version));
1459
+ if (matches.length === 1) return matches[0].sha;
1460
+ if (!matches.length) throw new Error(`no version ${version} of ${tenant}/${motion}`);
1461
+ throw new Error(`${version} matches ${matches.length} versions of ${tenant}/${motion}; pass a longer prefix`);
1462
+ }
1463
+ function parseCompanyList(raw) {
1464
+ const ids = raw.split(",").map((s) => s.trim()).filter(Boolean);
1465
+ if (!ids.length) throw new Error("--companies needs at least one company id");
1466
+ return ids;
1467
+ }
1468
+ async function runStepCommand(call, opts) {
1469
+ if (opts.args.length < 1 || opts.args.length > 2) {
1470
+ throw new Error("usage: motions run [motion] <step> [--company <id> | --companies <id,id>] [--input <file|->] [--from-batch <batch>]");
1471
+ }
1472
+ if (opts.live && opts.sha) throw new Error("pass --live or --sha, not both");
1473
+ if (opts.company !== void 0 && opts.companies !== void 0) throw new Error("pass --company or --companies, not both");
1474
+ let motionArg;
1475
+ let stepId;
1476
+ if (opts.args.length === 2) {
1477
+ [motionArg, stepId] = opts.args;
1478
+ if (opts.motion && opts.motion !== motionArg) {
1479
+ throw new Error(`motion "${motionArg}" conflicts with --motion "${opts.motion}"`);
1480
+ }
1481
+ } else {
1482
+ stepId = opts.args[0];
1483
+ motionArg = opts.motion;
1484
+ }
1485
+ const cwd = opts.cwd ?? process.cwd();
1486
+ let tenantDir = null;
1487
+ let tenantId2;
1488
+ let localMotions = [];
1489
+ if (opts.tenant) {
1490
+ const found = findTenantDir(resolve4(cwd, opts.tenant));
1491
+ if (found) {
1492
+ tenantDir = found;
1493
+ const ident = tenantIdentity(found);
1494
+ tenantId2 = ident.id;
1495
+ localMotions = ident.motions;
1496
+ } else {
1497
+ tenantId2 = opts.tenant;
1498
+ }
1499
+ } else {
1500
+ const found = findTenantDir(cwd);
1501
+ if (found) {
1502
+ tenantDir = found;
1503
+ const ident = tenantIdentity(found);
1504
+ tenantId2 = ident.id;
1505
+ localMotions = ident.motions;
1506
+ }
1507
+ }
1508
+ let batchSnap;
1509
+ if (opts.fromBatch) {
1510
+ batchSnap = await call(`/api/batches/${encodeURIComponent(opts.fromBatch)}`, void 0, tenantId2);
1511
+ if (tenantId2 && tenantId2 !== batchSnap.status.tenant) {
1512
+ throw new Error(`batch ${opts.fromBatch} belongs to tenant "${batchSnap.status.tenant}", not "${tenantId2}"`);
1513
+ }
1514
+ tenantId2 = batchSnap.status.tenant;
1515
+ if (motionArg && motionArg !== batchSnap.status.motion) {
1516
+ throw new Error(`batch ${opts.fromBatch} belongs to motion "${batchSnap.status.motion}", not "${motionArg}"`);
1517
+ }
1518
+ motionArg = batchSnap.status.motion;
1519
+ }
1520
+ if (!tenantId2) {
1521
+ throw new Error("no tenant.yaml found from the current directory; pass --tenant <dir-or-id> or --from-batch <batch>");
1522
+ }
1523
+ if (!motionArg) {
1524
+ if (localMotions.length === 1) motionArg = localMotions[0];
1525
+ else if (localMotions.length > 1) {
1526
+ throw new Error(
1527
+ `this tenant has ${localMotions.length} motions (${localMotions.join(", ")}); run \`motions run <motion> ${stepId}\` or pass --motion <id>`
1528
+ );
1529
+ } else {
1530
+ throw new Error(`pass the motion id: \`motions run <motion> ${stepId}\` or --motion <id>`);
1531
+ }
1532
+ }
1533
+ const usePublished = Boolean(opts.live || opts.sha || !tenantDir);
1534
+ let compiledKind;
1535
+ let localPayload;
1536
+ let resolvedVersion;
1537
+ if (!usePublished && tenantDir) {
1538
+ const compiled = await compileStep(tenantDir, motionArg, stepId);
1539
+ compiledKind = compiled.local.kind;
1540
+ localPayload = compiled.local;
1541
+ motionArg = compiled.motion;
1542
+ } else if (opts.sha) {
1543
+ resolvedVersion = await resolveSha(call, tenantId2, motionArg, opts.sha);
1544
+ }
1545
+ const body = {};
1546
+ if (localPayload) body.local = localPayload;
1547
+ if (resolvedVersion) body.version = resolvedVersion;
1548
+ let company;
1549
+ let companies;
1550
+ if (batchSnap) {
1551
+ const extracted = extractFromBatch(batchSnap, stepId, {
1552
+ company: opts.company?.trim() || void 0,
1553
+ companies: opts.companies ? parseCompanyList(opts.companies) : void 0,
1554
+ kind: compiledKind
1555
+ });
1556
+ company = extracted.company;
1557
+ companies = extracted.companies;
1558
+ if (Object.keys(extracted.calendar).length) body.calendar = { ...extracted.calendar };
1559
+ body.batch = { openedAt: extracted.openedAt };
1560
+ }
1561
+ if (opts.input) {
1562
+ const file2 = readInputPayload(opts.input, opts.readText, opts.readStdin);
1563
+ if (file2.company && file2.companies) throw new Error("--input cannot contain both company and companies");
1564
+ if (file2.company) {
1565
+ company = mergeCompanyInput(company, file2.company);
1566
+ if (companies && companies.length === 1) {
1567
+ companies = [mergeCompanyInput(companies[0], file2.company)];
1568
+ company = void 0;
1569
+ }
1570
+ }
1571
+ if (file2.companies) {
1572
+ companies = file2.companies;
1573
+ company = void 0;
1574
+ }
1575
+ if (file2.rerun) body.rerun = file2.rerun;
1576
+ if (file2.rules) body.rules = file2.rules;
1577
+ if (file2.calendar) body.calendar = { ...body.calendar ?? {}, ...file2.calendar };
1578
+ if (file2.now !== void 0) body.now = file2.now;
1579
+ if (file2.batch) body.batch = { ...body.batch ?? {}, ...file2.batch };
1580
+ if (file2.cache !== void 0) body.cache = file2.cache;
1581
+ }
1582
+ if (!batchSnap) {
1583
+ if (opts.company !== void 0) {
1584
+ const id2 = opts.company.trim();
1585
+ if (!id2) throw new Error("--company needs a company id");
1586
+ company = mergeCompanyInput({ crmId: id2 }, company);
1587
+ } else if (opts.companies !== void 0) {
1588
+ companies = parseCompanyList(opts.companies).map((crmId) => ({ crmId }));
1589
+ company = void 0;
1590
+ }
1591
+ }
1592
+ if (opts.facts !== void 0) {
1593
+ const parsedFacts = parseJsonObjectArg(opts.facts, "--facts", opts.readText);
1594
+ if (companies && companies.length > 1) throw new Error("--facts applies to a single company; use --input for batch steps with multiple companies");
1595
+ if (companies && companies.length === 1) {
1596
+ companies = [mergeCompanyInput(companies[0], { facts: parsedFacts })];
1597
+ } else {
1598
+ company = mergeCompanyInput(company, { facts: parsedFacts });
1599
+ }
1600
+ }
1601
+ if (opts.answers !== void 0) {
1602
+ const parsedAnswers = parseJsonObjectArg(opts.answers, "--answers", opts.readText);
1603
+ const answers = {};
1604
+ for (const [k, v] of Object.entries(parsedAnswers)) {
1605
+ if (typeof v !== "string") throw new Error(`--answers.${k} must be a string option id`);
1606
+ answers[k] = v;
1607
+ }
1608
+ if (companies && companies.length > 1) throw new Error("--answers applies to a single company; use --input for batch steps with multiple companies");
1609
+ if (companies && companies.length === 1) {
1610
+ companies = [mergeCompanyInput(companies[0], { answers })];
1611
+ } else {
1612
+ company = mergeCompanyInput(company, { answers });
1613
+ }
1614
+ }
1615
+ if (opts.now !== void 0) {
1616
+ const trimmed = opts.now.trim();
1617
+ if (!trimmed) throw new Error("--now needs an ISO timestamp or epoch milliseconds");
1618
+ body.now = /^\d+$/.test(trimmed) ? Number(trimmed) : trimmed;
1619
+ }
1620
+ if (opts.noCache) body.cache = false;
1621
+ if (companies) body.companies = companies;
1622
+ else if (company) body.company = company;
1623
+ const response = await call(
1624
+ `/api/tenants/${encodeURIComponent(tenantId2)}/motions/${encodeURIComponent(motionArg)}/steps/${encodeURIComponent(stepId)}/run`,
1625
+ body,
1626
+ tenantId2
1627
+ );
1628
+ return { response, failed: stepRunFailed(response) };
1629
+ }
1630
+
1203
1631
  // src/tree.ts
1204
- import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
1205
- import { join as join7, relative as relative3, resolve as resolve4, sep as sep3 } from "path";
1632
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
1633
+ import { join as join7, relative as relative3, resolve as resolve5, sep as sep3 } from "path";
1206
1634
  function fromRoot(root, repoPath) {
1207
1635
  const top = git(root, "rev-parse", "--show-toplevel");
1208
1636
  if (!top) return repoPath;
1209
- const prefix = relative3(resolve4(top), resolve4(root)).split(sep3).join("/");
1637
+ const prefix = relative3(resolve5(top), resolve5(root)).split(sep3).join("/");
1210
1638
  if (!prefix || prefix.startsWith("..")) return repoPath;
1211
1639
  return repoPath.startsWith(`${prefix}/`) ? repoPath.slice(prefix.length + 1) : repoPath;
1212
1640
  }
1213
1641
  function blockedOverwrites(root, writes) {
1214
1642
  const changed = writes.filter((w) => {
1215
1643
  const dest = join7(root, w.rel);
1216
- return existsSync6(dest) && readFileSync6(dest, "utf8") !== w.next;
1644
+ return existsSync6(dest) && readFileSync7(dest, "utf8") !== w.next;
1217
1645
  });
1218
1646
  if (!changed.length) return [];
1219
1647
  const status = git(root, "status", "--porcelain", "--untracked-files=all", "--", ...changed.map((w) => w.rel));
@@ -1223,18 +1651,18 @@ function blockedOverwrites(root, writes) {
1223
1651
  return changed.map((w) => w.rel).filter((rel) => dirty.some((d) => d === rel));
1224
1652
  }
1225
1653
  function inside(root, rel) {
1226
- const dest = resolve4(root, rel);
1227
- const base = resolve4(root);
1654
+ const dest = resolve5(root, rel);
1655
+ const base = resolve5(root);
1228
1656
  if (dest !== base && !dest.startsWith(base + sep3)) throw new Error(`refusing to write ${rel}`);
1229
1657
  return dest;
1230
1658
  }
1231
1659
 
1232
1660
  // src/vitest.ts
1233
1661
  import { spawnSync } from "child_process";
1234
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
1235
- import { dirname as dirname5, join as join8, resolve as resolve5, sep as sep4 } from "path";
1662
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
1663
+ import { dirname as dirname5, join as join8, resolve as resolve6, sep as sep4 } from "path";
1236
1664
  function findVitestPackage(dir) {
1237
- for (let at = resolve5(dir); ; ) {
1665
+ for (let at = resolve6(dir); ; ) {
1238
1666
  const candidate = join8(at, "node_modules", "vitest", "package.json");
1239
1667
  if (existsSync7(candidate)) return candidate;
1240
1668
  const parent = dirname5(at);
@@ -1246,9 +1674,9 @@ function resolveVitest(dir) {
1246
1674
  const pkgPath = findVitestPackage(dir);
1247
1675
  if (pkgPath) {
1248
1676
  try {
1249
- const pkg = JSON.parse(readFileSync7(pkgPath, "utf8"));
1677
+ const pkg = JSON.parse(readFileSync8(pkgPath, "utf8"));
1250
1678
  const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.vitest ?? "./vitest.mjs";
1251
- const entry = resolve5(dirname5(pkgPath), rel);
1679
+ const entry = resolve6(dirname5(pkgPath), rel);
1252
1680
  if (existsSync7(entry)) return entry;
1253
1681
  } catch {
1254
1682
  }
@@ -1256,7 +1684,7 @@ function resolveVitest(dir) {
1256
1684
  throw new Error(`${dir} has no vitest. Add it to devDependencies and install.`);
1257
1685
  }
1258
1686
  function vitestConfig(dir) {
1259
- const root = resolve5(dir);
1687
+ const root = resolve6(dir);
1260
1688
  const folder = join8(root, "node_modules", ".motions");
1261
1689
  mkdirSync3(folder, { recursive: true });
1262
1690
  const stub = join8(folder, "workers-stub.js");
@@ -1296,13 +1724,14 @@ function runTenantTests(dirs, spawn = spawnSync) {
1296
1724
  // src/main.ts
1297
1725
  var DEFAULT_URL = "https://motions.pruma.tech";
1298
1726
  var LOCAL_URL = "http://localhost:8787";
1299
- var USAGE = `usage: motions <check|push|pull|test|open|retry|cancel|init|publish|help> \u2026
1727
+ var USAGE = `usage: motions <check|push|pull|test|run|open|retry|cancel|init|publish|help> \u2026
1300
1728
  check [tenant] compile and validate the tenant in this directory, or every tenant in this repo
1301
1729
  push [--live] [--draft] [-m message] [--reseed]
1302
1730
  publish a draft (or go live with --live) and print a link
1303
1731
  pull <version> [--motion id] [--force]
1304
1732
  pull a published motion version's files into this tenant
1305
1733
  test [tenant] run motions/*/tests with the tenant's vitest
1734
+ run [motion] <step> [options] run one step in isolation (JSON output, no CRM writes or batch changes)
1306
1735
  open <tenant> <motion> [--list id-or-name | --companies id,id] [--label text] [--again]
1307
1736
  open a batch on the motion's live version
1308
1737
  retry <batch> [--company id] [--step id]
@@ -1353,6 +1782,32 @@ Run motions/*/tests using the tenant's local Vitest installation.
1353
1782
  options:
1354
1783
  --tenant <dir> path to a tenant directory containing tenant.yaml
1355
1784
  -h, --help print this help`,
1785
+ run: `usage: motions run [motion] <step> [options]
1786
+
1787
+ Run one runnable step (company or batch) in isolation on the engine and print JSON to stdout.
1788
+ Uses real sources (with source cache and cost tracking) and read-only CRM reads/proposals.
1789
+ Never writes to the CRM, never creates or modifies a batch, and never publishes drafts.
1790
+ Runs your local step code when invoked inside a tenant directory unless --live or --sha is set.
1791
+
1792
+ options:
1793
+ --motion <id> motion id (or pass as first positional: motions run <motion> <step>)
1794
+ --tenant <dir-or-id> tenant directory containing tenant.yaml, or tenant id for published runs
1795
+ --input, -i <file|-> JSON input file (or "-" for stdin) with company/companies, facts, rules, calendar, now
1796
+ --company <id> CRM company id to load from the CRM (or select from --from-batch)
1797
+ --companies <id,id> comma-separated CRM company ids for a batch step
1798
+ --from-batch <batch> seed company record, upstream facts, answers and calendar read-only from a batch
1799
+ --facts <json|@file> JSON object (or @file) of upstream step facts merged into the company
1800
+ --answers <json|@file> JSON object (or @file) of answers for this step merged into the company
1801
+ --now <iso|ms> pin ctx.now() to an ISO 8601 timestamp or epoch milliseconds
1802
+ --live run the motion's live published version instead of local files
1803
+ --sha <prefix-or-sha> run a specific published version (draft or live) instead of local files
1804
+ --no-cache bypass source_cache for this run (does not read or write cached source replies)
1805
+ --url <url> Motions server URL (defaults to MOTIONS_URL or ${DEFAULT_URL})
1806
+ -h, --help print this help
1807
+
1808
+ exit codes:
1809
+ 0 step ran without status "failed" (result JSON on stdout)
1810
+ 1 step returned status "failed" (result JSON on stdout) or command/API error (error JSON on stderr)`,
1356
1811
  open: `usage: motions open <tenant> <motion> [--list <id-or-name> | --companies <id,id>] [--label <text>] [--again] [--url <url>]
1357
1812
 
1358
1813
  Open a batch on the motion's live version and print its link.
@@ -1426,14 +1881,26 @@ var parsed = (() => {
1426
1881
  label: { type: "string" },
1427
1882
  reseed: { type: "boolean", default: false },
1428
1883
  approver: { type: "string" },
1884
+ input: { type: "string", short: "i" },
1885
+ "from-batch": { type: "string" },
1886
+ facts: { type: "string" },
1887
+ answers: { type: "string" },
1888
+ now: { type: "string" },
1889
+ sha: { type: "string" },
1890
+ "no-cache": { type: "boolean", default: false },
1429
1891
  version: { type: "boolean", short: "v", default: false },
1430
1892
  help: { type: "boolean", short: "h", default: false }
1431
1893
  }
1432
1894
  });
1433
1895
  } catch (e) {
1434
- console.error(`${e.message.split(". ")[0]}
1896
+ const msg = e.message.split(". ")[0];
1897
+ if (process.argv[2] === "run") {
1898
+ console.error(formatCliErrorJson(new Error(msg)));
1899
+ } else {
1900
+ console.error(`${msg}
1435
1901
 
1436
1902
  ${USAGE}`);
1903
+ }
1437
1904
  process.exit(1);
1438
1905
  }
1439
1906
  })();
@@ -1462,12 +1929,12 @@ var [command, ...args] = positionals;
1462
1929
  var url = (values.url ?? process.env.MOTIONS_URL ?? (command === "publish" ? LOCAL_URL : DEFAULT_URL)).replace(/\/$/, "");
1463
1930
  function resolveTenants(positional, fallbackAll) {
1464
1931
  if (values.tenant) {
1465
- const found = findTenantDir(resolve6(values.tenant));
1932
+ const found = findTenantDir(resolve7(values.tenant));
1466
1933
  if (!found) throw new Error(`no tenant.yaml in ${values.tenant}`);
1467
1934
  return [found];
1468
1935
  }
1469
1936
  if (positional) {
1470
- const direct = findTenantDir(resolve6(positional));
1937
+ const direct = findTenantDir(resolve7(positional));
1471
1938
  if (existsSync8(positional) && direct) return [direct];
1472
1939
  const match = monorepoTenants()?.find((dir) => folderName(dir) === positional);
1473
1940
  if (match) return [match];
@@ -1576,7 +2043,7 @@ async function publish(only) {
1576
2043
  if (only && !dirs.length) throw new Error(`no tenant ${only}`);
1577
2044
  await pushDirs(dirs, !values.draft);
1578
2045
  }
1579
- async function resolveSha(tenant, motion, version) {
2046
+ async function resolveSha2(tenant, motion, version) {
1580
2047
  if (/^[0-9a-f]{64}$/.test(version)) return version;
1581
2048
  const listed = await api(url, `/api/tenants/${tenant}/motions/${motion}/versions`);
1582
2049
  const matches = listed.versions.filter((v) => v.sha.startsWith(version));
@@ -1591,7 +2058,7 @@ async function pull(version) {
1591
2058
  const { id: id2, motions } = tenantIdentity(dir);
1592
2059
  const motion = values.motion ?? (motions.length === 1 ? motions[0] : void 0);
1593
2060
  if (!motion) throw new Error(`this tenant has ${motions.length} motions; pass --motion <id>`);
1594
- const sha = await resolveSha(id2, motion, version);
2061
+ const sha = await resolveSha2(id2, motion, version);
1595
2062
  const { files } = await api(url, `/api/tenants/${id2}/motions/${motion}/versions/${sha}/files`);
1596
2063
  const motionDir = join9(dir, "motions", motion);
1597
2064
  const writes = Object.entries(files).map(([path, next]) => ({ rel: join9("motions", motion, path), path, next }));
@@ -1606,7 +2073,7 @@ async function pull(version) {
1606
2073
  for (const write of writes.sort((a, b) => a.rel < b.rel ? -1 : 1)) {
1607
2074
  const dest = inside(motionDir, write.path);
1608
2075
  const existed = existsSync8(dest);
1609
- const same = existed && readFileSync8(dest, "utf8") === write.next;
2076
+ const same = existed && readFileSync9(dest, "utf8") === write.next;
1610
2077
  if (!same) {
1611
2078
  mkdirSync4(dirname6(dest), { recursive: true });
1612
2079
  writeFileSync4(dest, write.next);
@@ -1626,7 +2093,7 @@ async function test(only) {
1626
2093
  }
1627
2094
  function optionalTenant() {
1628
2095
  if (values.tenant) {
1629
- const found = findTenantDir(resolve6(values.tenant));
2096
+ const found = findTenantDir(resolve7(values.tenant));
1630
2097
  return found ? tenantIdentity(found).id : values.tenant;
1631
2098
  }
1632
2099
  const here = findTenantDir(process.cwd());
@@ -1699,11 +2166,31 @@ async function cancel(batch, extra) {
1699
2166
  console.log(`canceled batch ${batch}`);
1700
2167
  console.log(` ${url}/t/${out.tenant}/batches/${batch}`);
1701
2168
  }
2169
+ async function runStep(...stepArgs) {
2170
+ const { response, failed } = await runStepCommand((path, body, t) => api(url, path, body, t), {
2171
+ args: stepArgs,
2172
+ motion: values.motion,
2173
+ tenant: values.tenant,
2174
+ live: values.live,
2175
+ sha: values.sha,
2176
+ company: values.company,
2177
+ companies: values.companies,
2178
+ fromBatch: values["from-batch"],
2179
+ input: values.input,
2180
+ facts: values.facts,
2181
+ answers: values.answers,
2182
+ now: values.now,
2183
+ noCache: values["no-cache"]
2184
+ });
2185
+ console.log(JSON.stringify(response, null, 2));
2186
+ if (failed) process.exit(1);
2187
+ }
1702
2188
  var commands = {
1703
2189
  check,
1704
2190
  push,
1705
2191
  pull,
1706
2192
  test,
2193
+ run: runStep,
1707
2194
  open,
1708
2195
  retry,
1709
2196
  cancel,
@@ -1711,7 +2198,7 @@ var commands = {
1711
2198
  let approver = values.approver ?? handleFrom(process.env.MOTIONS_APPROVER) ?? void 0;
1712
2199
  if (!approver && process.env.MOTIONS_TOKEN) {
1713
2200
  try {
1714
- const tenantId2 = basename2(resolve6(dir ?? "."));
2201
+ const tenantId2 = basename2(resolve7(dir ?? "."));
1715
2202
  const me = await api(url, "/api/me", void 0, tenantId2);
1716
2203
  const match = me.memberships?.find((m) => m.tenant === tenantId2) ?? me.memberships?.[0];
1717
2204
  approver = handleFrom(match?.handle) ?? void 0;
@@ -1731,6 +2218,7 @@ if (!run) {
1731
2218
  process.exit(1);
1732
2219
  }
1733
2220
  Promise.resolve(run(...args)).catch((e) => {
1734
- console.error(e.message);
2221
+ if (command === "run") console.error(formatCliErrorJson(e));
2222
+ else console.error(e.message);
1735
2223
  process.exit(1);
1736
2224
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionskit/cli",
3
- "version": "0.2.8",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "esbuild": "^0.28.2",
30
30
  "yaml": "^2.9.1",
31
31
  "zod": "^4.6.7",
32
- "@motionskit/kernel": "0.2.7"
32
+ "@motionskit/kernel": "0.2.9"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^22.19.0",