@motionskit/cli 0.2.4 → 0.2.5

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` and `retry`.
3
+ `motions init`, `check`, `test`, `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 `http://localhost:8787`. `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_URL` defaults to `https://motions.pruma.tech`. `MOTIONS_TOKEN` is an API key (`mot_…`) sent as `authorization: Bearer`.
6
6
 
7
- Inside the motions repo, `motions publish [tenant]` is `push --live` over `tenants/*`.
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
@@ -47,7 +47,7 @@ type Compiled = {
47
47
  declare function compileMotion(tenant: {
48
48
  id: string;
49
49
  timezone: string;
50
- }, dir: string): Promise<Compiled>;
50
+ }, dir: string, catalog?: Set<string>): Promise<Compiled>;
51
51
  declare function compileTenant(tenantDir: string): Promise<Tenant>;
52
52
 
53
53
  type PublishWarningsInput = {
package/dist/index.js CHANGED
@@ -4,11 +4,13 @@ import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as
4
4
  import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
5
5
  import { fileURLToPath } from "url";
6
6
  import {
7
+ BUILTIN_SOURCE_OPS,
7
8
  CRM_WRITES,
8
9
  crmProblems,
9
10
  rulesVersion,
10
11
  STEP_BUILD,
11
12
  STEP_ENTRY_FILE,
13
+ seedProblems,
12
14
  stepEntry,
13
15
  unknownCrmSystem,
14
16
  validateManifest,
@@ -470,7 +472,7 @@ var MotionErrors = class extends Error {
470
472
  where;
471
473
  errors;
472
474
  };
473
- async function compileMotion(tenant, dir) {
475
+ async function compileMotion(tenant, dir, catalog = new Set(BUILTIN_SOURCE_OPS)) {
474
476
  const tenantDir = findTenantDir(dir);
475
477
  if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
476
478
  const folder = folderName(dir);
@@ -528,7 +530,7 @@ async function compileMotion(tenant, dir) {
528
530
  steps,
529
531
  queues
530
532
  };
531
- const errors = validateManifest(manifest);
533
+ const errors = validateManifest(manifest, catalog);
532
534
  if (errors.length) throw new MotionErrors(where2, errors);
533
535
  return { dir: root, manifest: { ...manifest, sha: versionId2(manifest, files) }, bundles, files };
534
536
  }
@@ -550,12 +552,17 @@ async function compileTenant(tenantDir) {
550
552
  const seedPath = join4(dir, "crm-seed.json");
551
553
  const seed = existsSync3(seedPath) ? JSON.parse(readFileSync3(seedPath, "utf8")) : null;
552
554
  const fixtures = readTenantFixtures(dir, meta.sources);
555
+ const sources = await compileSources(dir, id2);
556
+ const catalog = /* @__PURE__ */ new Set([
557
+ ...BUILTIN_SOURCE_OPS,
558
+ ...sources.flatMap((s) => Object.keys(s.manifest.ops).map((op) => `${s.manifest.source}.${op}`))
559
+ ]);
553
560
  const motionsDir = join4(dir, "motions");
554
561
  const motions = [];
555
562
  for (const name of readdirSync3(motionsDir).sort()) {
556
- if (existsSync3(join4(motionsDir, name, "motion.yaml"))) motions.push(await compileMotion({ id: id2, timezone }, join4(motionsDir, name)));
563
+ if (existsSync3(join4(motionsDir, name, "motion.yaml"))) motions.push(await compileMotion({ id: id2, timezone }, join4(motionsDir, name), catalog));
557
564
  }
558
- return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources: await compileSources(dir, id2), fixtures, motions };
565
+ return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources, fixtures, motions };
559
566
  }
560
567
 
561
568
  // src/publish.ts
package/dist/main.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // src/main.ts
4
4
  import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
5
5
  import { dirname as dirname6, join as join9, resolve as resolve6 } from "path";
6
+ import { createInterface } from "readline/promises";
6
7
  import { parseArgs } from "util";
7
8
 
8
9
  // src/batches.ts
@@ -61,6 +62,7 @@ function findCompany(companies, query) {
61
62
  return companies.find((c) => c.key === query) ?? companies.find((c) => c.key.endsWith(`:${query}`));
62
63
  }
63
64
  function selectRetries(snap, batch, options2 = {}) {
65
+ if (snap.status.canceled) throw new Error(`${batch} was canceled`);
64
66
  const runnable = runnableSteps(snap.motion);
65
67
  const step2 = options2.step?.trim();
66
68
  const company = options2.company?.trim();
@@ -98,6 +100,32 @@ async function retryBatch(call, input) {
98
100
  }
99
101
  return { tenant, retried: targets };
100
102
  }
103
+ function describeCancel(snap, batch) {
104
+ const { status: st } = snap;
105
+ const incomplete = st.lanes.active + st.lanes.waiting + st.lanes.parked;
106
+ const openQuestions = st.questions.filter((q) => q.state === "open").length;
107
+ const approvals = st.changesets.filter((c) => c.state === "approval").length;
108
+ const parts = [
109
+ `${incomplete} incomplete ${incomplete === 1 ? "company" : "companies"}`,
110
+ ...openQuestions ? [`${openQuestions} open ${openQuestions === 1 ? "question" : "questions"}`] : [],
111
+ ...approvals ? [`${approvals} pending ${approvals === 1 ? "approval" : "approvals"}`] : []
112
+ ];
113
+ return `Cancel ${batch} ("${st.label}", ${parts.join(", ")})?`;
114
+ }
115
+ async function cancelBatch(call, input) {
116
+ const snap = await call(`/api/batches/${encodeURIComponent(input.batch)}`, void 0, input.tenant);
117
+ const { status: st } = snap;
118
+ if (st.canceled) throw new Error(`batch ${input.batch} is already canceled`);
119
+ if (st.done) throw new Error(`batch ${input.batch} is already done`);
120
+ const writing = st.changesets.find((c) => c.state === "writing");
121
+ if (writing) throw new Error(`cannot cancel ${input.batch} while changeset ${writing.sha.slice(0, 8)} is writing to the CRM`);
122
+ if (input.confirm && !await input.confirm(describeCancel(snap, input.batch))) {
123
+ return { tenant: st.tenant, canceled: false };
124
+ }
125
+ const trimmed = input.reason?.trim();
126
+ await call(`/api/batches/${encodeURIComponent(input.batch)}/cancel`, trimmed ? { reason: trimmed } : {}, st.tenant);
127
+ return { tenant: st.tenant, canceled: true };
128
+ }
101
129
 
102
130
  // src/client.ts
103
131
  import { existsSync, readFileSync } from "fs";
@@ -144,20 +172,36 @@ function tokenFor(tenant, url2, batch) {
144
172
  }
145
173
  return void 0;
146
174
  }
175
+ function formatDetails(details) {
176
+ if (details === void 0 || details === null) return "";
177
+ if (typeof details === "string") return details.trim() ? `
178
+ ${details.trim()}` : "";
179
+ if (Array.isArray(details)) return details.length ? `
180
+ ${details.map(String).join("\n ")}` : "";
181
+ if (typeof details === "object") {
182
+ const errors = details.errors;
183
+ if (Array.isArray(errors) && errors.length) return `
184
+ ${errors.map(String).join("\n ")}`;
185
+ }
186
+ return "";
187
+ }
147
188
  function describeFailure(path, status, text) {
148
189
  let code;
149
190
  let message = text.trim();
191
+ let details;
150
192
  try {
151
193
  const body = JSON.parse(text);
152
194
  if (typeof body.error?.message === "string") {
153
195
  code = body.error.code;
154
196
  message = body.error.message;
197
+ details = body.error.details;
155
198
  }
156
199
  } catch {
157
200
  }
158
- if (status === 401) return code ? `unauthorized (${code}): ${message}` : `unauthorized: ${message}`;
159
- if (status === 403) return code ? `forbidden (${code}): ${message}` : `forbidden: ${message}`;
160
- return `${path} \u2192 ${status}${code ? ` ${code}` : ""}: ${message}`;
201
+ const extra = formatDetails(details);
202
+ if (status === 401) return `${code ? `unauthorized (${code}): ${message}` : `unauthorized: ${message}`}${extra}`;
203
+ if (status === 403) return `${code ? `forbidden (${code}): ${message}` : `forbidden: ${message}`}${extra}`;
204
+ return `${path} \u2192 ${status}${code ? ` ${code}` : ""}: ${message}${extra}`;
161
205
  }
162
206
  async function api(url2, path, body, tenant) {
163
207
  const pathTenant = tenant ?? path.match(/\/api\/tenants\/([^/]+)/)?.[1];
@@ -165,11 +209,19 @@ async function api(url2, path, body, tenant) {
165
209
  const key = tokenFor(pathTenant ? decodeURIComponent(pathTenant) : void 0, url2, batch ? decodeURIComponent(batch) : void 0);
166
210
  const headers = { accept: "application/json", ...key ? { authorization: `Bearer ${key}` } : {} };
167
211
  if (body !== void 0) headers["content-type"] = "application/json";
168
- const res = await fetch(`${url2.replace(/\/$/, "")}${path}`, {
169
- method: body === void 0 ? "GET" : "POST",
170
- headers,
171
- body: body === void 0 ? void 0 : JSON.stringify(body)
172
- });
212
+ const base = url2.replace(/\/$/, "");
213
+ let res;
214
+ try {
215
+ res = await fetch(`${base}${path}`, {
216
+ method: body === void 0 ? "GET" : "POST",
217
+ headers,
218
+ body: body === void 0 ? void 0 : JSON.stringify(body)
219
+ });
220
+ } catch (e) {
221
+ const cause = e?.cause;
222
+ const reason = cause?.message ?? cause?.code ?? (e instanceof Error ? e.message : String(e));
223
+ throw new Error(`could not reach ${base} (${path}): ${reason}. Set MOTIONS_URL or pass --url if the server is elsewhere.`);
224
+ }
173
225
  const text = await res.text();
174
226
  if (!res.ok) throw new Error(describeFailure(path, res.status, text));
175
227
  return text ? JSON.parse(text) : {};
@@ -181,11 +233,13 @@ import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as
181
233
  import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
182
234
  import { fileURLToPath as fileURLToPath2 } from "url";
183
235
  import {
236
+ BUILTIN_SOURCE_OPS,
184
237
  CRM_WRITES,
185
238
  crmProblems,
186
239
  rulesVersion,
187
240
  STEP_BUILD,
188
241
  STEP_ENTRY_FILE,
242
+ seedProblems,
189
243
  stepEntry,
190
244
  unknownCrmSystem,
191
245
  validateManifest,
@@ -699,7 +753,7 @@ var MotionErrors = class extends Error {
699
753
  where;
700
754
  errors;
701
755
  };
702
- async function compileMotion(tenant, dir) {
756
+ async function compileMotion(tenant, dir, catalog = new Set(BUILTIN_SOURCE_OPS)) {
703
757
  const tenantDir = findTenantDir(dir);
704
758
  if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
705
759
  const folder = folderName(dir);
@@ -757,7 +811,7 @@ async function compileMotion(tenant, dir) {
757
811
  steps,
758
812
  queues
759
813
  };
760
- const errors = validateManifest(manifest);
814
+ const errors = validateManifest(manifest, catalog);
761
815
  if (errors.length) throw new MotionErrors(where2, errors);
762
816
  return { dir: root, manifest: { ...manifest, sha: versionId2(manifest, files) }, bundles, files };
763
817
  }
@@ -779,38 +833,83 @@ async function compileTenant(tenantDir) {
779
833
  const seedPath = join5(dir, "crm-seed.json");
780
834
  const seed = existsSync4(seedPath) ? JSON.parse(readFileSync4(seedPath, "utf8")) : null;
781
835
  const fixtures = readTenantFixtures(dir, meta.sources);
836
+ const sources = await compileSources(dir, id2);
837
+ const catalog = /* @__PURE__ */ new Set([
838
+ ...BUILTIN_SOURCE_OPS,
839
+ ...sources.flatMap((s) => Object.keys(s.manifest.ops).map((op) => `${s.manifest.source}.${op}`))
840
+ ]);
782
841
  const motionsDir = join5(dir, "motions");
783
842
  const motions = [];
784
843
  for (const name of readdirSync3(motionsDir).sort()) {
785
- if (existsSync4(join5(motionsDir, name, "motion.yaml"))) motions.push(await compileMotion({ id: id2, timezone }, join5(motionsDir, name)));
844
+ if (existsSync4(join5(motionsDir, name, "motion.yaml"))) motions.push(await compileMotion({ id: id2, timezone }, join5(motionsDir, name), catalog));
845
+ }
846
+ return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources, fixtures, motions };
847
+ }
848
+ function escapeRegExp(s) {
849
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
850
+ }
851
+ function unusedQueueWarnings(manifest, files) {
852
+ const keys = Object.keys(manifest.queues);
853
+ if (!keys.length) return [];
854
+ const code = Object.entries(files).filter(([path]) => path !== "motion.yaml" && path !== "rules.yaml").map(([, content]) => content).join("\n");
855
+ const warnings = [];
856
+ for (const key of keys) {
857
+ const escaped = escapeRegExp(key);
858
+ const mentioned = new RegExp(`(["'\`])${escaped}\\1|\\.answers\\.${escaped}\\b`).test(code);
859
+ if (!mentioned) {
860
+ warnings.push(`warning: ${manifest.motion}: queue "${key}" is declared in motion.yaml but not referenced by any step (does it match a ctx.ask type?)`);
861
+ }
786
862
  }
787
- return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources: await compileSources(dir, id2), fixtures, motions };
863
+ return warnings;
788
864
  }
789
865
  function tenantCrmProblems(tenant, systems = CRM_WRITES) {
866
+ const problems = [];
790
867
  const system = tenant.connection?.system;
791
868
  const unknown = unknownCrmSystem(system, systems);
792
- if (unknown) return [`crm.yaml: ${unknown}`];
793
- return tenant.motions.flatMap(({ manifest }) => crmProblems(system, manifest.steps, systems).map((p) => `${manifest.motion}: ${p}`));
869
+ if (unknown) problems.push(`crm.yaml: ${unknown}`);
870
+ else problems.push(...tenant.motions.flatMap(({ manifest }) => crmProblems(system, manifest.steps, systems).map((p) => `${manifest.motion}: ${p}`)));
871
+ if (tenant.seed !== void 0 && tenant.seed !== null) {
872
+ problems.push(...seedProblems(tenant.seed).map((p) => `crm-seed.json: ${p}`));
873
+ }
874
+ return problems;
794
875
  }
795
876
 
796
877
  // src/init.ts
878
+ import { execFileSync } from "child_process";
797
879
  import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
798
880
  import { basename, dirname as dirname4, join as join6, resolve as resolve3 } from "path";
799
881
  import { fileURLToPath as fileURLToPath3 } from "url";
800
882
  var TENANT_ID = /^[a-z][a-z0-9_-]{0,62}$/;
883
+ var HANDLE = /^[a-z][a-z0-9_-]{0,31}$/;
801
884
  function cliVersion() {
802
885
  return JSON.parse(readFileSync5(fileURLToPath3(new URL("../package.json", import.meta.url)), "utf8")).version;
803
886
  }
887
+ function handleFrom(raw) {
888
+ if (!raw) return null;
889
+ const base = raw.trim().split("@")[0].toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 28);
890
+ return HANDLE.test(base) ? base : null;
891
+ }
892
+ function defaultApprover() {
893
+ try {
894
+ const email = execFileSync("git", ["config", "user.email"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
895
+ const fromGit = handleFrom(email);
896
+ if (fromGit) return fromGit;
897
+ } catch {
898
+ }
899
+ return handleFrom(process.env.USER ?? process.env.USERNAME) ?? "member";
900
+ }
804
901
  var file = (dir, path, contents) => {
805
902
  const dest = join6(dir, path);
806
903
  mkdirSync2(dirname4(dest), { recursive: true });
807
904
  writeFileSync2(dest, contents);
808
905
  };
809
- function init(target = ".") {
906
+ function init(target = ".", options2 = {}) {
810
907
  const dir = resolve3(target);
811
908
  const id2 = basename(dir);
812
909
  if (!TENANT_ID.test(id2)) throw new Error(`${id2} is not a tenant id: lowercase letters, digits, - and _, starting with a letter`);
813
910
  if (existsSync5(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
911
+ const approver = options2.approver ?? defaultApprover();
912
+ if (!HANDLE.test(approver)) throw new Error(`${approver} is not a member handle: lowercase letters, digits, - and _, starting with a letter`);
814
913
  mkdirSync2(dir, { recursive: true });
815
914
  const version = cliVersion();
816
915
  file(dir, "tenant.yaml", `id: ${id2}
@@ -818,10 +917,37 @@ title: ${id2}
818
917
  timezone: America/Sao_Paulo
819
918
  `);
820
919
  file(dir, "crm.yaml", "system: memory\nmode: read_write\ncompanies:\n core: { name: name, domain: domain }\n");
920
+ file(
921
+ dir,
922
+ "crm-seed.json",
923
+ `${JSON.stringify(
924
+ {
925
+ companies: [
926
+ { id: "1001", properties: { name: "Aurora Industrial", domain: "aurora.example" } },
927
+ { id: "1002", properties: { name: "Serra Verde Alimentos", domain: "" } }
928
+ ],
929
+ lists: { weekly: ["1001", "1002"] }
930
+ },
931
+ null,
932
+ 2
933
+ )}
934
+ `
935
+ );
821
936
  file(
822
937
  dir,
823
938
  "motions/example/motion.yaml",
824
- "title: Example\napprovers: [owner]\nreasons: [no_domain]\n\nsteps:\n - id: greet\n title: Record the domain\n run: steps/greet.ts\n"
939
+ `title: Example
940
+ approvers: [${approver}]
941
+ reasons: [no_domain]
942
+
943
+ input:
944
+ list: weekly
945
+
946
+ steps:
947
+ - id: greet
948
+ title: Record the domain
949
+ run: steps/greet.ts
950
+ `
825
951
  );
826
952
  file(
827
953
  dir,
@@ -839,30 +965,20 @@ export default defineStep({
839
965
  file(
840
966
  dir,
841
967
  "motions/example/tests/greet.test.ts",
842
- `import { serve } from "@motionskit/sdk/harness";
968
+ `import { runStep } from "@motionskit/sdk/testing";
843
969
  import { expect, test } from "vitest";
844
970
  import greet from "../steps/greet.ts";
845
971
 
846
- const input = (domain: string | null) => ({
847
- kind: "company" as const,
848
- batch: { id: "b", tenant: ${JSON.stringify(id2)}, motion: "example", version: "v", label: "t", openedAt: 0 },
849
- step: "greet",
850
- rules: {},
851
- clock: Date.parse("2026-11-02T12:00:00Z"),
852
- calendar: {},
853
- companies: [{ record: { key: "co", core: { name: "Acme", domain, country: null, tax_id: null, crm: { system: "memory", object: "company" as const, id: "1", owner_id: null } }, fields: {} }, facts: {}, answers: {}, attempt: "a" }],
854
- });
855
-
856
- const caps = { sources: { call: async () => ({ ok: true as const, data: null }) }, crm: { read: async () => ({ ok: true as const, data: null }), prepare: async () => ({ ok: true as const, data: { before: null } }) } };
972
+ const now = "2026-11-02T12:00:00Z";
857
973
 
858
974
  test("drops a company that has no domain", async () => {
859
- const out = await new (serve(greet))().run(input(null), caps);
860
- expect(out.co).toMatchObject({ status: "ok", outcome: { lane: "drop", reason: "no_domain" } });
975
+ const out = await runStep(greet, { company: { core: { name: "Serra Verde", domain: null } }, fixtures: [], now });
976
+ expect(out).toMatchObject({ status: "ok", outcome: { lane: "drop", reason: "no_domain" } });
861
977
  });
862
978
 
863
979
  test("records the domain", async () => {
864
- const out = await new (serve(greet))().run(input("acme.com"), caps);
865
- expect(out.co).toMatchObject({ status: "ok", facts: { domain: "acme.com" } });
980
+ const out = await runStep(greet, { company: { core: { name: "Aurora Industrial", domain: "aurora.example" } }, fixtures: [], now });
981
+ expect(out).toMatchObject({ status: "ok", facts: { domain: "aurora.example" } });
866
982
  });
867
983
  `
868
984
  );
@@ -918,7 +1034,9 @@ npm run typecheck
918
1034
  npx motions test
919
1035
  \`\`\`
920
1036
 
921
- \`motions push\` publishes a draft and prints a link. \`motions push --live\` makes it the version new batches open on. Set \`MOTIONS_URL\` (default \`http://localhost:8787\`) and \`MOTIONS_TOKEN\` (an API key, \`mot_\u2026\`).
1037
+ \`motions push\` publishes a draft and prints a link. \`motions push --live\` makes it the version new batches open on. Set \`MOTIONS_TOKEN\` (an API key, \`mot_\u2026\`), and \`MOTIONS_URL\` only if you run against another server (defaults to \`https://motions.pruma.tech\`).
1038
+
1039
+ Make sure the handle in \`motions/example/motion.yaml\` (\`approvers: [${approver}]\`) matches a member in Settings -> Members before promoting live. \`crm-seed.json\` holds sample companies for the in-memory CRM; company ids are digits only.
922
1040
 
923
1041
  GitHub: pull requests run \`check\`, \`typecheck\` and \`test\`. Pushes to \`main\` run the Motions action, which publishes live. Add the \`MOTIONS_TOKEN\` secret and the \`MOTIONS_URL\` variable to the repo.
924
1042
  `
@@ -962,10 +1080,10 @@ jobs:
962
1080
  }
963
1081
 
964
1082
  // src/origin.ts
965
- import { execFileSync } from "child_process";
1083
+ import { execFileSync as execFileSync2 } from "child_process";
966
1084
  function git(dir, ...args2) {
967
1085
  try {
968
- return execFileSync("git", ["-C", dir, ...args2], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trimEnd();
1086
+ return execFileSync2("git", ["-C", dir, ...args2], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trimEnd();
969
1087
  } catch {
970
1088
  return void 0;
971
1089
  }
@@ -1092,21 +1210,26 @@ function runTenantTests(dirs, spawn = spawnSync) {
1092
1210
  }
1093
1211
 
1094
1212
  // src/main.ts
1095
- var USAGE = `usage: motions <check|push|pull|test|open|retry|init|publish> \u2026
1213
+ var DEFAULT_URL = "https://motions.pruma.tech";
1214
+ var LOCAL_URL = "http://localhost:8787";
1215
+ var USAGE = `usage: motions <check|push|pull|test|open|retry|cancel|init|publish|help> \u2026
1096
1216
  check [tenant] compile the tenant in this directory, or every tenant in this repo
1097
1217
  push [--live] [-m message] publish a draft (or go live with --live) and print a link
1098
1218
  pull <version> [--motion id] [--force]
1099
1219
  test run motions/*/tests with the tenant's vitest
1100
1220
  open <tenant> <motion> [--list id-or-name | --companies id,id] [--label text] [--again]
1101
1221
  retry <batch> [--company id] [--step id]
1102
- init [dir] scaffold a tenant repo
1103
- publish [tenant] from this repo, push --live over tenants/*`;
1222
+ cancel <batch> [--reason text] [--yes]
1223
+ init [dir] [--approver handle] scaffold a tenant repo
1224
+ publish [tenant] from this repo, push --live over tenants/*
1225
+ help print this usage text
1226
+ --version, -v print the CLI version`;
1104
1227
  var parsed = (() => {
1105
1228
  try {
1106
1229
  return parseArgs({
1107
1230
  allowPositionals: true,
1108
1231
  options: {
1109
- url: { type: "string", default: process.env.MOTIONS_URL ?? "http://localhost:8787" },
1232
+ url: { type: "string" },
1110
1233
  tenant: { type: "string" },
1111
1234
  live: { type: "boolean", default: false },
1112
1235
  draft: { type: "boolean", default: false },
@@ -1117,9 +1240,13 @@ var parsed = (() => {
1117
1240
  companies: { type: "string" },
1118
1241
  company: { type: "string" },
1119
1242
  step: { type: "string" },
1243
+ reason: { type: "string" },
1244
+ yes: { type: "boolean", short: "y", default: false },
1120
1245
  again: { type: "boolean", default: false },
1121
1246
  label: { type: "string" },
1122
1247
  reseed: { type: "boolean", default: false },
1248
+ approver: { type: "string" },
1249
+ version: { type: "boolean", short: "v", default: false },
1123
1250
  help: { type: "boolean", short: "h", default: false }
1124
1251
  }
1125
1252
  });
@@ -1131,12 +1258,16 @@ ${USAGE}`);
1131
1258
  }
1132
1259
  })();
1133
1260
  var { positionals, values } = parsed;
1134
- if (values.help) {
1261
+ if (values.version) {
1262
+ console.log(cliVersion());
1263
+ process.exit(0);
1264
+ }
1265
+ if (values.help || positionals[0] === "help") {
1135
1266
  console.log(USAGE);
1136
1267
  process.exit(0);
1137
1268
  }
1138
1269
  var [command, ...args] = positionals;
1139
- var url = values.url.replace(/\/$/, "");
1270
+ var url = (values.url ?? process.env.MOTIONS_URL ?? (command === "publish" ? LOCAL_URL : DEFAULT_URL)).replace(/\/$/, "");
1140
1271
  function resolveTenants(positional, fallbackAll) {
1141
1272
  if (values.tenant) {
1142
1273
  const found = findTenantDir(resolve6(values.tenant));
@@ -1162,8 +1293,33 @@ function versionLink(tenant, motion, sha) {
1162
1293
  return `${url}/t/${tenant}/motions/${motion}/versions/${sha}`;
1163
1294
  }
1164
1295
  async function pushDirs(dirs, live) {
1296
+ const compiled = [];
1165
1297
  for (const dir of dirs) {
1166
1298
  const tenant = await compileTenant(dir);
1299
+ const refused = tenantCrmProblems(tenant);
1300
+ if (refused.length) throw new Error(`${tenant.id}:
1301
+ ${refused.join("\n ")}`);
1302
+ compiled.push(tenant);
1303
+ }
1304
+ for (const tenant of compiled) {
1305
+ await api(url, `/api/tenants/${tenant.id}`, { ...upsertBody(tenant, values.reseed), dryRun: true });
1306
+ const extraSources = tenant.sources.flatMap((s) => Object.keys(s.manifest.ops).map((op) => `${s.manifest.source}.${op}`));
1307
+ const crmSystem = tenant.connection?.system;
1308
+ for (const { dir: motionDir, manifest, bundles, files } of tenant.motions) {
1309
+ await api(url, `/api/tenants/${tenant.id}/motions/${manifest.motion}/versions`, {
1310
+ manifest,
1311
+ bundles,
1312
+ files,
1313
+ origin: origin(motionDir),
1314
+ live,
1315
+ ...values.message ? { message: values.message } : {},
1316
+ dryRun: true,
1317
+ ...extraSources.length ? { extraSources } : {},
1318
+ ...crmSystem ? { crmSystem } : {}
1319
+ });
1320
+ }
1321
+ }
1322
+ for (const tenant of compiled) {
1167
1323
  const upserted = await api(url, `/api/tenants/${tenant.id}`, upsertBody(tenant, values.reseed));
1168
1324
  if (upserted.seeded) console.log(`seeded ${tenant.id}'s CRM with ${upserted.seeded} records`);
1169
1325
  if (upserted.fixtures !== void 0) console.log(`${tenant.id} is in fixture mode: built-in sources answer from ${upserted.fixtures} fixtures`);
@@ -1179,6 +1335,7 @@ async function pushDirs(dirs, live) {
1179
1335
  });
1180
1336
  console.log(`${tenant.id}/${manifest.motion} @ ${manifest.sha.slice(0, 10)} (${out.created ? "new" : "unchanged"}, ${out.live ? "live" : "draft"})`);
1181
1337
  console.log(` ${versionLink(tenant.id, manifest.motion, manifest.sha)}`);
1338
+ for (const line of unusedQueueWarnings(manifest, files)) console.log(` ${line}`);
1182
1339
  for (const line of formatPublishWarnings(tenant.id, manifest.motion, out)) console.log(line);
1183
1340
  }
1184
1341
  }
@@ -1193,7 +1350,7 @@ async function check(only) {
1193
1350
  });
1194
1351
  if (!tenant) continue;
1195
1352
  console.log(`${tenant.id} (${tenant.timezone})`);
1196
- for (const { manifest, bundles } of tenant.motions) {
1353
+ for (const { manifest, bundles, files } of tenant.motions) {
1197
1354
  const kb = Object.values(bundles).reduce((n, code) => n + code.length, 0) / 1024;
1198
1355
  console.log(
1199
1356
  ` ${manifest.motion} @ ${manifest.sha.slice(0, 10)} ${manifest.steps.length} steps, ${Object.keys(bundles).length} bundles (${kb.toFixed(0)} KB), ${manifest.rulesVersion}`
@@ -1202,6 +1359,7 @@ async function check(only) {
1202
1359
  const detail = "bundle" in s ? ` ${s.bundle.slice(0, 8)} sources=[${s.sources.join(", ")}]` : "";
1203
1360
  console.log(` ${s.kind.padEnd(10)} ${s.id}${detail}`);
1204
1361
  }
1362
+ for (const line of unusedQueueWarnings(manifest, files)) console.log(` ${line}`);
1205
1363
  }
1206
1364
  const fixtures = fixturesLine(tenant.fixtures);
1207
1365
  if (fixtures) console.log(fixtures);
@@ -1320,6 +1478,35 @@ async function retry(batch, extra) {
1320
1478
  }
1321
1479
  console.log(` ${url}/t/${tenant}/batches/${batch}`);
1322
1480
  }
1481
+ async function cancel(batch, extra) {
1482
+ if (!batch || extra) {
1483
+ throw new Error("usage: motions cancel <batch> [--reason text] [--yes]");
1484
+ }
1485
+ const confirm = values.yes ? void 0 : async (summary) => {
1486
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1487
+ throw new Error(`refusing to cancel ${batch} without confirmation (pass --yes)`);
1488
+ }
1489
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1490
+ try {
1491
+ const answer = await rl.question(`${summary} [y/N] `);
1492
+ return /^y(es)?$/i.test(answer.trim());
1493
+ } finally {
1494
+ rl.close();
1495
+ }
1496
+ };
1497
+ const out = await cancelBatch((path, body, t) => api(url, path, body, t), {
1498
+ batch,
1499
+ reason: values.reason,
1500
+ tenant: optionalTenant(),
1501
+ confirm
1502
+ });
1503
+ if (!out.canceled) {
1504
+ console.log("aborted");
1505
+ return;
1506
+ }
1507
+ console.log(`canceled batch ${batch}`);
1508
+ console.log(` ${url}/t/${out.tenant}/batches/${batch}`);
1509
+ }
1323
1510
  var commands = {
1324
1511
  check,
1325
1512
  push,
@@ -1327,9 +1514,12 @@ var commands = {
1327
1514
  test,
1328
1515
  open,
1329
1516
  retry,
1517
+ cancel,
1330
1518
  init: (dir) => {
1331
- const created = init(dir);
1519
+ const approver = values.approver ?? defaultApprover();
1520
+ const created = init(dir, { approver });
1332
1521
  console.log(`created ${created}`);
1522
+ console.log(` approver set to "${approver}" in motions/example/motion.yaml (match your handle in Settings -> Members)`);
1333
1523
  },
1334
1524
  publish
1335
1525
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionskit/cli",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
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.4"
32
+ "@motionskit/kernel": "0.2.5"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^22.19.0",