@dench.com/cli 3.12.31-staging.1469 → 3.12.33-staging.1478

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/crm-columns.ts ADDED
@@ -0,0 +1,982 @@
1
+ /**
2
+ * `dench crm columns …`
3
+ *
4
+ * Thin CLI dispatcher over `functions/crm/columns` (staging lists + typed AI
5
+ * Research columns — 2 AI credits/row, zero autorun, explicit run scope and
6
+ * optional hard credit stop ceiling).
7
+ *
8
+ * Deliberately does NOT import from `../../convex/` because `@dench.com/cli`
9
+ * ships as a standalone npm package.
10
+ */
11
+
12
+ import { makeFunctionReference } from "convex/server";
13
+ import {
14
+ assertNoUnknownFlags,
15
+ type CrmCliContext,
16
+ CrmCliError,
17
+ callAction,
18
+ callMutation,
19
+ callQuery,
20
+ out,
21
+ shift,
22
+ } from "./crm";
23
+ import { CliArgError, getFlag, hasFlag, parseJson } from "./lib/cli-args";
24
+ import { closestMatch } from "./lib/levenshtein";
25
+
26
+ const api = {
27
+ listStagingLists: makeFunctionReference<"query">(
28
+ "functions/crm/columns:listStagingLists",
29
+ ),
30
+ createStagingList: makeFunctionReference<"mutation">(
31
+ "functions/crm/columns:createStagingList",
32
+ ),
33
+ deleteStagingListCascade: makeFunctionReference<"mutation">(
34
+ "functions/crm/columns:deleteStagingListCascade",
35
+ ),
36
+ createAi: makeFunctionReference<"mutation">("functions/crm/columns:createAi"),
37
+ updateAi: makeFunctionReference<"mutation">("functions/crm/columns:updateAi"),
38
+ deleteAi: makeFunctionReference<"mutation">("functions/crm/columns:deleteAi"),
39
+ estimateRun: makeFunctionReference<"query">(
40
+ "functions/crm/columns:estimateRun",
41
+ ),
42
+ startRun: makeFunctionReference<"mutation">("functions/crm/columns:startRun"),
43
+ pauseRun: makeFunctionReference<"mutation">("functions/crm/columns:pauseRun"),
44
+ resumeRun: makeFunctionReference<"mutation">(
45
+ "functions/crm/columns:resumeRun",
46
+ ),
47
+ stopRun: makeFunctionReference<"mutation">("functions/crm/columns:stopRun"),
48
+ getRunStatus: makeFunctionReference<"query">(
49
+ "functions/crm/columns:getRunStatus",
50
+ ),
51
+ overrideCell: makeFunctionReference<"mutation">(
52
+ "functions/crm/columns:overrideCell",
53
+ ),
54
+ rerunSingleCell: makeFunctionReference<"action">(
55
+ "functions/crm/columns:rerunSingleCell",
56
+ ),
57
+ getCellProvenanceBatch: makeFunctionReference<"query">(
58
+ "functions/crm/columns:getCellProvenanceBatch",
59
+ ),
60
+ getStagingTriageSummary: makeFunctionReference<"query">(
61
+ "functions/crm/columns:getStagingTriageSummary",
62
+ ),
63
+ };
64
+
65
+ // Local Wave 1 bounds & enums (mirrored from convex/functions/crm/columns.ts;
66
+ // strictly 5 output shapes — NO "boolean", NO `runCondition`).
67
+ export const AI_COLUMN_OUTPUT_KINDS = [
68
+ "fit_check",
69
+ "text",
70
+ "enum",
71
+ "number",
72
+ "url",
73
+ ] as const;
74
+ export type AiColumnOutputKind = (typeof AI_COLUMN_OUTPUT_KINDS)[number];
75
+
76
+ export const AI_COLUMN_RUN_SCOPES = ["selected", "empty", "all"] as const;
77
+ export type AiColumnRunScope = (typeof AI_COLUMN_RUN_SCOPES)[number];
78
+
79
+ export const STAGING_ENTITY_KINDS = ["company", "person"] as const;
80
+ export type StagingEntityKind = (typeof STAGING_ENTITY_KINDS)[number];
81
+
82
+ export const MAX_STAGING_DISPLAY_NAME_LENGTH = 120;
83
+ export const MAX_AI_COLUMN_NAME_LENGTH = 100;
84
+ export const MAX_AI_COLUMN_PROMPT_LENGTH = 2_000;
85
+ export const MAX_AI_COLUMN_ENUM_VALUES = 20;
86
+ export const MAX_AI_COLUMN_ENUM_OPTION_LENGTH = 80;
87
+ export const MAX_PROVENANCE_BATCH_ENTRIES = 100;
88
+ export const MAX_AI_COLUMN_TARGET_ENTRIES = 2_000;
89
+ export const AI_COLUMN_CREDITS_PER_ROW = 2;
90
+
91
+ export const CRM_COLUMNS_VERBS = [
92
+ "lists",
93
+ "create-list",
94
+ "delete-list",
95
+ "create-ai",
96
+ "update-ai",
97
+ "delete-ai",
98
+ "estimate-run",
99
+ "start-run",
100
+ "pause-run",
101
+ "resume-run",
102
+ "stop-run",
103
+ "run-status",
104
+ "override-cell",
105
+ "rerun-cell",
106
+ "provenance",
107
+ "summary",
108
+ ] as const;
109
+
110
+ const COLUMN_USAGE_LINES: Record<(typeof CRM_COLUMNS_VERBS)[number], string> = {
111
+ lists: " dench crm columns lists [--json]",
112
+ "create-list":
113
+ " dench crm columns create-list <displayName> [--entity-kind company|person] [--json]",
114
+ "delete-list": " dench crm columns delete-list <objectName> [--json]",
115
+ "create-ai":
116
+ " dench crm columns create-ai <object> <name> --prompt <text> --output-kind fit_check|text|enum|number|url [--enum-values '<JSON>'] [--description <text>] [--required-input-fields <ids>] [--json]",
117
+ "update-ai":
118
+ " dench crm columns update-ai <object> <field> [--prompt <text>] [--enum-values '<JSON>'] [--description <text>] [--required-input-fields <ids>] [--json]",
119
+ "delete-ai": " dench crm columns delete-ai <object> <field> [--json]",
120
+ "estimate-run":
121
+ " dench crm columns estimate-run <object> <field> --scope selected|empty|all [--entry-ids <id1,id2>] [--include-unknown-and-failed|--no-include-unknown-and-failed] [--limit <1..2000>] [--json]",
122
+ "start-run":
123
+ " dench crm columns start-run <object> <field> --scope selected|empty|all [--entry-ids <id1,id2>] [--include-unknown-and-failed|--no-include-unknown-and-failed] [--limit <1..2000>] [--credit-stop-ceiling <N|null>|--clear-credit-stop-ceiling] [--json]",
124
+ "pause-run": " dench crm columns pause-run <runId> [--json]",
125
+ "resume-run":
126
+ " dench crm columns resume-run <runId> [--credit-stop-ceiling <N|null>|--clear-credit-stop-ceiling] [--json]",
127
+ "stop-run": " dench crm columns stop-run <runId> [--json]",
128
+ "run-status":
129
+ " dench crm columns run-status <object> [--field <field>] [--run-id <runId>] [--json]",
130
+ "override-cell":
131
+ " dench crm columns override-cell <object> <entryId> <field> (--value <JSON|text> | --clear) [--json]",
132
+ "rerun-cell":
133
+ " dench crm columns rerun-cell <object> <entryId> <field> [--unlock-override] [--json]",
134
+ provenance:
135
+ " dench crm columns provenance <object> --entry-ids <id1,id2> [--json]",
136
+ summary: " dench crm columns summary <object> [--json]",
137
+ };
138
+
139
+ export function columnsHelpText(verb?: string): string {
140
+ if (verb && Object.hasOwn(COLUMN_USAGE_LINES, verb)) {
141
+ const line = COLUMN_USAGE_LINES[verb as keyof typeof COLUMN_USAGE_LINES];
142
+ return `Usage:\n${line}\n\nGlobal flags:\n --json Output raw JSON.`;
143
+ }
144
+ const group = (title: string, verbs: (typeof CRM_COLUMNS_VERBS)[number][]) =>
145
+ `${title}:\n${verbs.map((v) => COLUMN_USAGE_LINES[v]).join("\n")}`;
146
+ return [
147
+ "Usage: dench crm columns <subcommand> [options]",
148
+ "",
149
+ "Flow: 1) Find companies (--into-list) -> 2) create-ai -> 3) start-run (--limit 5, then all) -> 4) summary -> dench leads find --company-list <list> --fit-only",
150
+ "",
151
+ group("Lists", ["lists", "create-list", "delete-list", "summary"]),
152
+ group("AI columns (2 AI credits/row, zero autorun)", [
153
+ "create-ai",
154
+ "update-ai",
155
+ "delete-ai",
156
+ ]),
157
+ group("Runs", [
158
+ "estimate-run",
159
+ "start-run",
160
+ "run-status",
161
+ "pause-run",
162
+ "resume-run",
163
+ "stop-run",
164
+ ]),
165
+ group("Cells & citations", ["provenance", "override-cell", "rerun-cell"]),
166
+ "",
167
+ "Global flags:\n --json Output raw JSON.",
168
+ ].join("\n");
169
+ }
170
+
171
+ function argError(message: string): CrmCliError {
172
+ const cause = new CliArgError(message);
173
+ return new CrmCliError(message, { cause });
174
+ }
175
+
176
+ function readFlag(args: string[], name: string): string | undefined {
177
+ try {
178
+ return getFlag(args, name);
179
+ } catch (error) {
180
+ if (error instanceof CliArgError) {
181
+ throw new CrmCliError(error.message, { cause: error });
182
+ }
183
+ throw error;
184
+ }
185
+ }
186
+
187
+ function shiftName(args: string[], expected: string, usage: string): string {
188
+ const value = shift(args, expected).trim();
189
+ if (!value) {
190
+ throw argError(`Missing ${expected}. Usage: ${usage}`);
191
+ }
192
+ if (value.startsWith("--")) {
193
+ const label = expected.charAt(0).toUpperCase() + expected.slice(1);
194
+ throw argError(
195
+ `${label} cannot start with "--". The name is positional: ${usage}`,
196
+ );
197
+ }
198
+ return value;
199
+ }
200
+
201
+ function assertNoLeftoverArgs(args: readonly string[], command: string): void {
202
+ assertNoUnknownFlags(args, command);
203
+ if (args.length > 0) {
204
+ throw argError(
205
+ `Unexpected argument for ${command}: ${args[0]}. Run \`dench ${command} --help\` for usage.`,
206
+ );
207
+ }
208
+ }
209
+
210
+ export function parseOutputKind(raw: string | undefined): AiColumnOutputKind {
211
+ if (!raw || !raw.trim()) {
212
+ throw argError(
213
+ `Missing --output-kind. Expected one of: ${AI_COLUMN_OUTPUT_KINDS.join(" | ")}.`,
214
+ );
215
+ }
216
+ const normalized = raw.trim();
217
+ if (normalized === "boolean") {
218
+ throw argError(
219
+ `--output-kind "boolean" is not supported. Use "fit_check" or one of: ${AI_COLUMN_OUTPUT_KINDS.join(" | ")}.`,
220
+ );
221
+ }
222
+ if (!(AI_COLUMN_OUTPUT_KINDS as readonly string[]).includes(normalized)) {
223
+ throw argError(
224
+ `--output-kind must be one of ${AI_COLUMN_OUTPUT_KINDS.join(" | ")}, got "${raw}".`,
225
+ );
226
+ }
227
+ return normalized as AiColumnOutputKind;
228
+ }
229
+
230
+ export function parseEntityKind(
231
+ raw: string | undefined,
232
+ ): StagingEntityKind | undefined {
233
+ if (raw === undefined) return undefined;
234
+ const normalized = raw.trim();
235
+ if (!(STAGING_ENTITY_KINDS as readonly string[]).includes(normalized)) {
236
+ throw argError(
237
+ `--entity-kind must be one of ${STAGING_ENTITY_KINDS.join(" | ")}, got "${raw}".`,
238
+ );
239
+ }
240
+ return normalized as StagingEntityKind;
241
+ }
242
+
243
+ export function parseScope(raw: string | undefined): AiColumnRunScope {
244
+ if (!raw || !raw.trim()) {
245
+ throw argError(
246
+ `Missing --scope. Expected one of: ${AI_COLUMN_RUN_SCOPES.join(" | ")}.`,
247
+ );
248
+ }
249
+ const normalized = raw.trim();
250
+ if (!(AI_COLUMN_RUN_SCOPES as readonly string[]).includes(normalized)) {
251
+ throw argError(
252
+ `--scope must be one of ${AI_COLUMN_RUN_SCOPES.join(" | ")}, got "${raw}".`,
253
+ );
254
+ }
255
+ return normalized as AiColumnRunScope;
256
+ }
257
+
258
+ export function parseStringListFlag(
259
+ raw: string,
260
+ flagName: string,
261
+ opts: {
262
+ allowEmpty?: boolean;
263
+ maxItems?: number;
264
+ maxItemLength?: number;
265
+ dedupe?: boolean;
266
+ } = {},
267
+ ): string[] {
268
+ const trimmed = raw.trim();
269
+ let items: string[];
270
+ if (trimmed.startsWith("[")) {
271
+ let parsed: unknown;
272
+ try {
273
+ parsed = parseJson(trimmed);
274
+ } catch (error) {
275
+ if (error instanceof CliArgError) {
276
+ throw new CrmCliError(
277
+ `${flagName} must be valid JSON array or comma-separated list: ${error.message}`,
278
+ {
279
+ cause: error,
280
+ },
281
+ );
282
+ }
283
+ throw error;
284
+ }
285
+ if (!Array.isArray(parsed)) {
286
+ throw argError(`${flagName} must be a JSON array of strings.`);
287
+ }
288
+ items = [];
289
+ for (const item of parsed) {
290
+ if (typeof item !== "string") {
291
+ throw argError(`${flagName} items must all be non-empty strings.`);
292
+ }
293
+ const clean = item.trim();
294
+ if (!clean) {
295
+ throw argError(`${flagName} items cannot be empty.`);
296
+ }
297
+ items.push(clean);
298
+ }
299
+ } else if (trimmed.startsWith("{")) {
300
+ throw argError(
301
+ `${flagName} must be a JSON string array or comma-separated list, not an object.`,
302
+ );
303
+ } else if (trimmed.length === 0) {
304
+ items = [];
305
+ } else {
306
+ items = trimmed
307
+ .split(",")
308
+ .map((part) => part.trim())
309
+ .filter((part) => part.length > 0);
310
+ }
311
+
312
+ if (opts.dedupe) {
313
+ items = [...new Set(items)];
314
+ }
315
+
316
+ if (!opts.allowEmpty && items.length === 0) {
317
+ throw argError(`${flagName} requires at least one non-empty value.`);
318
+ }
319
+ if (opts.maxItems !== undefined && items.length > opts.maxItems) {
320
+ throw argError(
321
+ `${flagName} accepts at most ${opts.maxItems} values (got ${items.length}).`,
322
+ );
323
+ }
324
+ if (opts.maxItemLength !== undefined) {
325
+ for (const item of items) {
326
+ if (item.length > opts.maxItemLength) {
327
+ throw argError(
328
+ `${flagName} item "${item.slice(0, 32)}..." exceeds ${opts.maxItemLength} characters.`,
329
+ );
330
+ }
331
+ }
332
+ }
333
+ return items;
334
+ }
335
+
336
+ function resolveIncludeUnknownAndFailed(
337
+ includeFlag: boolean,
338
+ excludeFlag: boolean,
339
+ ): boolean | undefined {
340
+ if (includeFlag && excludeFlag) {
341
+ throw argError(
342
+ "Pass either --include-unknown-and-failed or --no-include-unknown-and-failed, not both.",
343
+ );
344
+ }
345
+ if (includeFlag) return true;
346
+ if (excludeFlag) return false;
347
+ return undefined;
348
+ }
349
+
350
+ export function parseIncludeUnknownAndFailed(
351
+ args: string[],
352
+ ): boolean | undefined {
353
+ const includeFlag = hasFlag(args, "--include-unknown-and-failed");
354
+ const excludeFlag = hasFlag(args, "--no-include-unknown-and-failed");
355
+ return resolveIncludeUnknownAndFailed(includeFlag, excludeFlag);
356
+ }
357
+
358
+ export function parseRunLimit(raw: string | undefined): number | undefined {
359
+ if (raw === undefined) return undefined;
360
+ const trimmed = raw.trim();
361
+ const value = Number(trimmed);
362
+ if (
363
+ trimmed.length === 0 ||
364
+ !Number.isFinite(value) ||
365
+ !Number.isInteger(value) ||
366
+ value < 1 ||
367
+ value > MAX_AI_COLUMN_TARGET_ENTRIES
368
+ ) {
369
+ throw argError(
370
+ `--limit must be an integer between 1 and ${MAX_AI_COLUMN_TARGET_ENTRIES}, got "${raw}".`,
371
+ );
372
+ }
373
+ return value;
374
+ }
375
+
376
+ function resolveCreditStopCeiling(
377
+ raw: string | undefined,
378
+ clear: boolean,
379
+ ): number | null | undefined {
380
+ if (raw !== undefined && clear) {
381
+ throw argError(
382
+ "Pass either --credit-stop-ceiling or --clear-credit-stop-ceiling, not both.",
383
+ );
384
+ }
385
+ if (clear) return null;
386
+ if (raw === undefined) return undefined;
387
+ const trimmed = raw.trim().toLowerCase();
388
+ if (trimmed === "null" || trimmed === "none") {
389
+ return null;
390
+ }
391
+ const value = Number(trimmed);
392
+ if (
393
+ trimmed.length === 0 ||
394
+ !Number.isFinite(value) ||
395
+ value < AI_COLUMN_CREDITS_PER_ROW
396
+ ) {
397
+ throw argError(
398
+ `--credit-stop-ceiling must be a finite number >= ${AI_COLUMN_CREDITS_PER_ROW} or "null", got "${raw}".`,
399
+ );
400
+ }
401
+ return value;
402
+ }
403
+
404
+ export function parseCreditStopCeiling(
405
+ args: string[],
406
+ ): number | null | undefined {
407
+ const raw = readFlag(args, "--credit-stop-ceiling");
408
+ const clear = hasFlag(args, "--clear-credit-stop-ceiling");
409
+ return resolveCreditStopCeiling(raw, clear);
410
+ }
411
+
412
+ function parseEnumValuesFlag(raw: string): string[] {
413
+ const values = parseStringListFlag(raw, "--enum-values", {
414
+ allowEmpty: false,
415
+ maxItems: MAX_AI_COLUMN_ENUM_VALUES,
416
+ maxItemLength: MAX_AI_COLUMN_ENUM_OPTION_LENGTH,
417
+ });
418
+ const seenLower = new Set<string>();
419
+ for (const value of values) {
420
+ const key = value.toLowerCase();
421
+ if (seenLower.has(key)) {
422
+ throw argError(
423
+ `--enum-values contains duplicate option "${value}" (case-insensitive).`,
424
+ );
425
+ }
426
+ seenLower.add(key);
427
+ }
428
+ return values;
429
+ }
430
+
431
+ export function resolveOverrideValue(
432
+ raw: string | undefined,
433
+ clear: boolean,
434
+ ): string | number | null {
435
+ if (raw !== undefined && clear) {
436
+ throw argError("Pass either --value or --clear, not both.");
437
+ }
438
+ if (raw === undefined && !clear) {
439
+ throw argError(
440
+ "override-cell requires either --value <JSON|text> or --clear.",
441
+ );
442
+ }
443
+ if (clear) return null;
444
+ const text = raw as string;
445
+ try {
446
+ const parsed = JSON.parse(text) as unknown;
447
+ if (parsed === null) return null;
448
+ if (typeof parsed === "string") return parsed;
449
+ if (typeof parsed === "number" && Number.isFinite(parsed)) return parsed;
450
+ throw argError(
451
+ `--value must be a string, finite number, or null (booleans, objects, and arrays are not supported), got "${text}".`,
452
+ );
453
+ } catch (error) {
454
+ if (error instanceof CrmCliError) throw error;
455
+ return text;
456
+ }
457
+ }
458
+
459
+ export function parseOverrideValue(args: string[]): string | number | null {
460
+ const raw = readFlag(args, "--value");
461
+ const clear = hasFlag(args, "--clear");
462
+ return resolveOverrideValue(raw, clear);
463
+ }
464
+
465
+ function validatePrompt(raw: string, flagName = "--prompt"): string {
466
+ const trimmed = raw.trim();
467
+ if (!trimmed) {
468
+ throw argError(`${flagName} cannot be empty.`);
469
+ }
470
+ if (trimmed.length > MAX_AI_COLUMN_PROMPT_LENGTH) {
471
+ throw argError(
472
+ `${flagName} exceeds ${MAX_AI_COLUMN_PROMPT_LENGTH} characters (got ${trimmed.length}).`,
473
+ );
474
+ }
475
+ return trimmed;
476
+ }
477
+
478
+ export async function runColumnsCommand(ctx: CrmCliContext): Promise<void> {
479
+ // Drain `--json` safely when `runColumnsCommand` is invoked standalone.
480
+ if (hasFlag(ctx.args, "--json")) {
481
+ ctx.jsonOutput = true;
482
+ }
483
+
484
+ // Handle offline help before shifting or touching `ctx.convex`.
485
+ if (ctx.args.length === 0) {
486
+ console.log(columnsHelpText());
487
+ return;
488
+ }
489
+ if (ctx.args[0] === "help") {
490
+ console.log(columnsHelpText(ctx.args[1]));
491
+ return;
492
+ }
493
+ if (ctx.args.includes("--help") || ctx.args.includes("-h")) {
494
+ const candidate = ctx.args.find((token) => !token.startsWith("-"));
495
+ console.log(columnsHelpText(candidate));
496
+ return;
497
+ }
498
+
499
+ const verb = ctx.args.shift();
500
+ switch (verb) {
501
+ case "lists": {
502
+ assertNoLeftoverArgs(ctx.args, "crm columns lists");
503
+ const result = await callQuery(ctx, api.listStagingLists, {});
504
+ out(ctx, result);
505
+ return;
506
+ }
507
+
508
+ case "create-list": {
509
+ const rawEntityKind = readFlag(ctx.args, "--entity-kind");
510
+ assertNoUnknownFlags(ctx.args, "crm columns create-list");
511
+ const displayName = shiftName(
512
+ ctx.args,
513
+ "displayName",
514
+ "dench crm columns create-list <displayName> [--entity-kind company|person]",
515
+ );
516
+ assertNoLeftoverArgs(ctx.args, "crm columns create-list");
517
+ const entityKind = parseEntityKind(rawEntityKind);
518
+ if (displayName.length > MAX_STAGING_DISPLAY_NAME_LENGTH) {
519
+ throw argError(
520
+ `displayName must be 1..${MAX_STAGING_DISPLAY_NAME_LENGTH} characters.`,
521
+ );
522
+ }
523
+ const result = await callMutation(ctx, api.createStagingList, {
524
+ displayName,
525
+ ...(entityKind ? { entityKind } : {}),
526
+ });
527
+ out(ctx, result);
528
+ return;
529
+ }
530
+
531
+ case "delete-list": {
532
+ assertNoUnknownFlags(ctx.args, "crm columns delete-list");
533
+ const objectName = shiftName(
534
+ ctx.args,
535
+ "objectName",
536
+ "dench crm columns delete-list <objectName>",
537
+ );
538
+ assertNoLeftoverArgs(ctx.args, "crm columns delete-list");
539
+ const result = await callMutation(ctx, api.deleteStagingListCascade, {
540
+ objectName,
541
+ });
542
+ out(ctx, result);
543
+ return;
544
+ }
545
+
546
+ case "create-ai": {
547
+ const usage =
548
+ "dench crm columns create-ai <object> <name> --prompt <text> --output-kind fit_check|text|enum|number|url";
549
+ const rawPrompt = readFlag(ctx.args, "--prompt");
550
+ const rawOutputKind = readFlag(ctx.args, "--output-kind");
551
+ const rawEnumValues = readFlag(ctx.args, "--enum-values");
552
+ const description = readFlag(ctx.args, "--description");
553
+ const rawRequiredInputFields = readFlag(
554
+ ctx.args,
555
+ "--required-input-fields",
556
+ );
557
+ assertNoUnknownFlags(ctx.args, "crm columns create-ai");
558
+ const objectName = shiftName(ctx.args, "objectName", usage);
559
+ const name = shiftName(ctx.args, "name", usage);
560
+ assertNoLeftoverArgs(ctx.args, "crm columns create-ai");
561
+
562
+ if (name.length > MAX_AI_COLUMN_NAME_LENGTH) {
563
+ throw argError(
564
+ `Column name must be 1..${MAX_AI_COLUMN_NAME_LENGTH} characters.`,
565
+ );
566
+ }
567
+ if (rawPrompt === undefined) {
568
+ throw argError("Missing --prompt for crm columns create-ai.");
569
+ }
570
+ const prompt = validatePrompt(rawPrompt);
571
+ const outputKind = parseOutputKind(rawOutputKind);
572
+
573
+ let enumValues: string[] | undefined;
574
+ if (rawEnumValues !== undefined) {
575
+ if (outputKind !== "enum") {
576
+ throw argError(
577
+ `--enum-values is only valid when --output-kind is "enum" (got "${outputKind}").`,
578
+ );
579
+ }
580
+ enumValues = parseEnumValuesFlag(rawEnumValues);
581
+ } else if (outputKind === "enum") {
582
+ throw argError(
583
+ '--enum-values is required when --output-kind is "enum".',
584
+ );
585
+ }
586
+
587
+ const requiredInputFieldIds =
588
+ rawRequiredInputFields !== undefined
589
+ ? parseStringListFlag(
590
+ rawRequiredInputFields,
591
+ "--required-input-fields",
592
+ { allowEmpty: true },
593
+ )
594
+ : undefined;
595
+
596
+ const result = await callMutation(ctx, api.createAi, {
597
+ objectName,
598
+ name,
599
+ prompt,
600
+ outputKind,
601
+ ...(enumValues ? { enumValues } : {}),
602
+ ...(description !== undefined ? { description } : {}),
603
+ ...(requiredInputFieldIds !== undefined
604
+ ? { requiredInputFieldIds }
605
+ : {}),
606
+ });
607
+ out(ctx, result);
608
+ return;
609
+ }
610
+
611
+ case "update-ai": {
612
+ const usage =
613
+ "dench crm columns update-ai <object> <field> [--prompt <text>] [--enum-values '<JSON>'] [--description <text>] [--required-input-fields <ids>]";
614
+ const rawPrompt = readFlag(ctx.args, "--prompt");
615
+ const rawEnumValues = readFlag(ctx.args, "--enum-values");
616
+ const description = readFlag(ctx.args, "--description");
617
+ const rawRequiredInputFields = readFlag(
618
+ ctx.args,
619
+ "--required-input-fields",
620
+ );
621
+ assertNoUnknownFlags(ctx.args, "crm columns update-ai");
622
+ const objectName = shiftName(ctx.args, "objectName", usage);
623
+ const fieldName = shiftName(ctx.args, "fieldName", usage);
624
+ assertNoLeftoverArgs(ctx.args, "crm columns update-ai");
625
+
626
+ const prompt =
627
+ rawPrompt !== undefined ? validatePrompt(rawPrompt) : undefined;
628
+ const enumValues =
629
+ rawEnumValues !== undefined
630
+ ? parseEnumValuesFlag(rawEnumValues)
631
+ : undefined;
632
+ const requiredInputFieldIds =
633
+ rawRequiredInputFields !== undefined
634
+ ? parseStringListFlag(
635
+ rawRequiredInputFields,
636
+ "--required-input-fields",
637
+ { allowEmpty: true },
638
+ )
639
+ : undefined;
640
+
641
+ if (
642
+ prompt === undefined &&
643
+ enumValues === undefined &&
644
+ description === undefined &&
645
+ requiredInputFieldIds === undefined
646
+ ) {
647
+ throw argError(
648
+ "Provide at least one of --prompt, --enum-values, --description, or --required-input-fields.",
649
+ );
650
+ }
651
+
652
+ const result = await callMutation(ctx, api.updateAi, {
653
+ objectName,
654
+ fieldName,
655
+ ...(prompt !== undefined ? { prompt } : {}),
656
+ ...(enumValues !== undefined ? { enumValues } : {}),
657
+ ...(description !== undefined ? { description } : {}),
658
+ ...(requiredInputFieldIds !== undefined
659
+ ? { requiredInputFieldIds }
660
+ : {}),
661
+ });
662
+ out(ctx, result);
663
+ return;
664
+ }
665
+
666
+ case "delete-ai": {
667
+ const usage = "dench crm columns delete-ai <object> <field>";
668
+ assertNoUnknownFlags(ctx.args, "crm columns delete-ai");
669
+ const objectName = shiftName(ctx.args, "objectName", usage);
670
+ const fieldName = shiftName(ctx.args, "fieldName", usage);
671
+ assertNoLeftoverArgs(ctx.args, "crm columns delete-ai");
672
+ const result = await callMutation(ctx, api.deleteAi, {
673
+ objectName,
674
+ fieldName,
675
+ });
676
+ out(ctx, result);
677
+ return;
678
+ }
679
+
680
+ case "estimate-run": {
681
+ const usage =
682
+ "dench crm columns estimate-run <object> <field> --scope selected|empty|all";
683
+ const rawScope = readFlag(ctx.args, "--scope");
684
+ const rawEntryIds = readFlag(ctx.args, "--entry-ids");
685
+ const rawLimit = readFlag(ctx.args, "--limit");
686
+ const includeFlag = hasFlag(ctx.args, "--include-unknown-and-failed");
687
+ const excludeFlag = hasFlag(ctx.args, "--no-include-unknown-and-failed");
688
+ assertNoUnknownFlags(ctx.args, "crm columns estimate-run");
689
+ const objectName = shiftName(ctx.args, "objectName", usage);
690
+ const fieldName = shiftName(ctx.args, "fieldName", usage);
691
+ assertNoLeftoverArgs(ctx.args, "crm columns estimate-run");
692
+
693
+ const includeUnknownAndFailed = resolveIncludeUnknownAndFailed(
694
+ includeFlag,
695
+ excludeFlag,
696
+ );
697
+ const limit = parseRunLimit(rawLimit);
698
+ const scope = parseScope(rawScope);
699
+ let entryIds: string[] | undefined;
700
+ if (scope === "selected") {
701
+ if (rawEntryIds === undefined) {
702
+ throw argError('--entry-ids is required when --scope is "selected".');
703
+ }
704
+ entryIds = parseStringListFlag(rawEntryIds, "--entry-ids", {
705
+ allowEmpty: false,
706
+ });
707
+ } else if (rawEntryIds !== undefined) {
708
+ throw argError(
709
+ `--entry-ids is only allowed when --scope is "selected" (got --scope "${scope}").`,
710
+ );
711
+ }
712
+
713
+ const result = await callQuery(ctx, api.estimateRun, {
714
+ objectName,
715
+ fieldName,
716
+ scope,
717
+ ...(entryIds ? { entryIds } : {}),
718
+ ...(includeUnknownAndFailed !== undefined
719
+ ? { includeUnknownAndFailed }
720
+ : {}),
721
+ ...(limit !== undefined ? { limit } : {}),
722
+ });
723
+ out(ctx, result);
724
+ return;
725
+ }
726
+
727
+ case "start-run": {
728
+ const usage =
729
+ "dench crm columns start-run <object> <field> --scope selected|empty|all";
730
+ const rawScope = readFlag(ctx.args, "--scope");
731
+ const rawEntryIds = readFlag(ctx.args, "--entry-ids");
732
+ const rawLimit = readFlag(ctx.args, "--limit");
733
+ const includeFlag = hasFlag(ctx.args, "--include-unknown-and-failed");
734
+ const excludeFlag = hasFlag(ctx.args, "--no-include-unknown-and-failed");
735
+ const rawCreditStopCeiling = readFlag(ctx.args, "--credit-stop-ceiling");
736
+ const clearCreditStopCeiling = hasFlag(
737
+ ctx.args,
738
+ "--clear-credit-stop-ceiling",
739
+ );
740
+ assertNoUnknownFlags(ctx.args, "crm columns start-run");
741
+ const objectName = shiftName(ctx.args, "objectName", usage);
742
+ const fieldName = shiftName(ctx.args, "fieldName", usage);
743
+ assertNoLeftoverArgs(ctx.args, "crm columns start-run");
744
+
745
+ const includeUnknownAndFailed = resolveIncludeUnknownAndFailed(
746
+ includeFlag,
747
+ excludeFlag,
748
+ );
749
+ const limit = parseRunLimit(rawLimit);
750
+ const creditStopCeiling = resolveCreditStopCeiling(
751
+ rawCreditStopCeiling,
752
+ clearCreditStopCeiling,
753
+ );
754
+ const scope = parseScope(rawScope);
755
+ let entryIds: string[] | undefined;
756
+ if (scope === "selected") {
757
+ if (rawEntryIds === undefined) {
758
+ throw argError('--entry-ids is required when --scope is "selected".');
759
+ }
760
+ entryIds = parseStringListFlag(rawEntryIds, "--entry-ids", {
761
+ allowEmpty: false,
762
+ });
763
+ } else if (rawEntryIds !== undefined) {
764
+ throw argError(
765
+ `--entry-ids is only allowed when --scope is "selected" (got --scope "${scope}").`,
766
+ );
767
+ }
768
+
769
+ const result = await callMutation(ctx, api.startRun, {
770
+ objectName,
771
+ fieldName,
772
+ scope,
773
+ ...(entryIds ? { entryIds } : {}),
774
+ ...(includeUnknownAndFailed !== undefined
775
+ ? { includeUnknownAndFailed }
776
+ : {}),
777
+ ...(limit !== undefined ? { limit } : {}),
778
+ ...(creditStopCeiling !== undefined ? { creditStopCeiling } : {}),
779
+ });
780
+ out(ctx, result);
781
+ return;
782
+ }
783
+
784
+ case "pause-run": {
785
+ assertNoUnknownFlags(ctx.args, "crm columns pause-run");
786
+ const runId = shiftName(
787
+ ctx.args,
788
+ "runId",
789
+ "dench crm columns pause-run <runId>",
790
+ );
791
+ assertNoLeftoverArgs(ctx.args, "crm columns pause-run");
792
+ const result = await callMutation(ctx, api.pauseRun, { runId });
793
+ out(ctx, result);
794
+ return;
795
+ }
796
+
797
+ case "resume-run": {
798
+ const rawCreditStopCeiling = readFlag(ctx.args, "--credit-stop-ceiling");
799
+ const clearCreditStopCeiling = hasFlag(
800
+ ctx.args,
801
+ "--clear-credit-stop-ceiling",
802
+ );
803
+ assertNoUnknownFlags(ctx.args, "crm columns resume-run");
804
+ const runId = shiftName(
805
+ ctx.args,
806
+ "runId",
807
+ "dench crm columns resume-run <runId> [--credit-stop-ceiling <N|null>|--clear-credit-stop-ceiling]",
808
+ );
809
+ assertNoLeftoverArgs(ctx.args, "crm columns resume-run");
810
+ const creditStopCeiling = resolveCreditStopCeiling(
811
+ rawCreditStopCeiling,
812
+ clearCreditStopCeiling,
813
+ );
814
+ const result = await callMutation(ctx, api.resumeRun, {
815
+ runId,
816
+ ...(creditStopCeiling !== undefined ? { creditStopCeiling } : {}),
817
+ });
818
+ out(ctx, result);
819
+ return;
820
+ }
821
+
822
+ case "stop-run": {
823
+ assertNoUnknownFlags(ctx.args, "crm columns stop-run");
824
+ const runId = shiftName(
825
+ ctx.args,
826
+ "runId",
827
+ "dench crm columns stop-run <runId>",
828
+ );
829
+ assertNoLeftoverArgs(ctx.args, "crm columns stop-run");
830
+ const result = await callMutation(ctx, api.stopRun, { runId });
831
+ out(ctx, result);
832
+ return;
833
+ }
834
+
835
+ case "run-status": {
836
+ const rawFieldName = readFlag(ctx.args, "--field");
837
+ const rawRunId = readFlag(ctx.args, "--run-id");
838
+ assertNoUnknownFlags(ctx.args, "crm columns run-status");
839
+ const objectName = shiftName(
840
+ ctx.args,
841
+ "objectName",
842
+ "dench crm columns run-status <object> [--field <field>] [--run-id <runId>]",
843
+ );
844
+ assertNoLeftoverArgs(ctx.args, "crm columns run-status");
845
+ const fieldName = rawFieldName?.trim();
846
+ if (rawFieldName !== undefined && !fieldName) {
847
+ throw argError("--field cannot be empty.");
848
+ }
849
+ const runId = rawRunId?.trim();
850
+ if (rawRunId !== undefined && !runId) {
851
+ throw argError("--run-id cannot be empty.");
852
+ }
853
+ const result = await callQuery(ctx, api.getRunStatus, {
854
+ objectName,
855
+ ...(fieldName !== undefined ? { fieldName } : {}),
856
+ ...(runId !== undefined ? { runId } : {}),
857
+ });
858
+ out(ctx, result);
859
+ return;
860
+ }
861
+
862
+ case "override-cell": {
863
+ const usage =
864
+ "dench crm columns override-cell <object> <entryId> <field> (--value <JSON|text> | --clear)";
865
+ const rawValue = readFlag(ctx.args, "--value");
866
+ const clear = hasFlag(ctx.args, "--clear");
867
+ assertNoUnknownFlags(ctx.args, "crm columns override-cell");
868
+ const objectName = shiftName(ctx.args, "objectName", usage);
869
+ const entryId = shiftName(ctx.args, "entryId", usage);
870
+ const fieldName = shiftName(ctx.args, "fieldName", usage);
871
+ assertNoLeftoverArgs(ctx.args, "crm columns override-cell");
872
+ const value = resolveOverrideValue(rawValue, clear);
873
+ const result = await callMutation(ctx, api.overrideCell, {
874
+ objectName,
875
+ entryId,
876
+ fieldName,
877
+ value,
878
+ });
879
+ out(ctx, result);
880
+ return;
881
+ }
882
+
883
+ case "rerun-cell": {
884
+ const usage =
885
+ "dench crm columns rerun-cell <object> <entryId> <field> [--unlock-override]";
886
+ const unlockOverride = hasFlag(ctx.args, "--unlock-override");
887
+ assertNoUnknownFlags(ctx.args, "crm columns rerun-cell");
888
+ const objectName = shiftName(ctx.args, "objectName", usage);
889
+ const entryId = shiftName(ctx.args, "entryId", usage);
890
+ const fieldName = shiftName(ctx.args, "fieldName", usage);
891
+ assertNoLeftoverArgs(ctx.args, "crm columns rerun-cell");
892
+ const result = await callAction(ctx, api.rerunSingleCell, {
893
+ objectName,
894
+ entryId,
895
+ fieldName,
896
+ ...(unlockOverride ? { unlockOverride: true } : {}),
897
+ });
898
+ out(ctx, result);
899
+ return;
900
+ }
901
+
902
+ case "provenance": {
903
+ const usage =
904
+ "dench crm columns provenance <object> --entry-ids <id1,id2>";
905
+ const rawEntryIds = readFlag(ctx.args, "--entry-ids");
906
+ assertNoUnknownFlags(ctx.args, "crm columns provenance");
907
+ const objectName = shiftName(ctx.args, "objectName", usage);
908
+ assertNoLeftoverArgs(ctx.args, "crm columns provenance");
909
+ if (rawEntryIds === undefined) {
910
+ throw argError("Missing --entry-ids for crm columns provenance.");
911
+ }
912
+ const entryIds = parseStringListFlag(rawEntryIds, "--entry-ids", {
913
+ allowEmpty: false,
914
+ maxItems: MAX_PROVENANCE_BATCH_ENTRIES,
915
+ dedupe: true,
916
+ });
917
+ const result = await callQuery(ctx, api.getCellProvenanceBatch, {
918
+ objectName,
919
+ entryIds,
920
+ });
921
+ out(ctx, result);
922
+ return;
923
+ }
924
+
925
+ case "summary": {
926
+ const usage = "dench crm columns summary <object>";
927
+ assertNoUnknownFlags(ctx.args, "crm columns summary");
928
+ const objectName = shiftName(ctx.args, "objectName", usage);
929
+ assertNoLeftoverArgs(ctx.args, "crm columns summary");
930
+ const result = (await callQuery(ctx, api.getStagingTriageSummary, {
931
+ objectName,
932
+ })) as {
933
+ totalCount: number;
934
+ countsTruncated: boolean;
935
+ fitColumns: Array<{
936
+ fieldName: string;
937
+ fits: number;
938
+ doesNotFit: number;
939
+ unknown: number;
940
+ notRun: number;
941
+ }>;
942
+ fitQualifiedCount: number;
943
+ fitQualifiedWithDomainCount: number;
944
+ fitQualifiedSkippedNoDomain: number;
945
+ };
946
+ if (ctx.jsonOutput) {
947
+ out(ctx, result);
948
+ return;
949
+ }
950
+ console.log(
951
+ `${objectName} (${result.totalCount}${result.countsTruncated ? "+" : ""} rows)`,
952
+ );
953
+ if (result.fitColumns.length === 0) {
954
+ console.log(" No Fit Check columns yet.");
955
+ } else {
956
+ for (const col of result.fitColumns) {
957
+ console.log(
958
+ ` ${col.fieldName}: ${col.fits} Fits · ${col.doesNotFit} Does not fit · ${col.unknown} Unknown · ${col.notRun} Not run`,
959
+ );
960
+ }
961
+ console.log(
962
+ ` Ready for Find people: ${result.fitQualifiedWithDomainCount} fits with website` +
963
+ (result.fitQualifiedSkippedNoDomain > 0
964
+ ? ` (${result.fitQualifiedSkippedNoDomain} missing website)`
965
+ : ""),
966
+ );
967
+ }
968
+ return;
969
+ }
970
+
971
+ default: {
972
+ const suggestion = verb
973
+ ? closestMatch(verb, CRM_COLUMNS_VERBS)
974
+ : undefined;
975
+ throw argError(
976
+ `Unknown columns verb: ${verb ?? "(none)"}` +
977
+ `${suggestion ? `. Did you mean "${suggestion}"?` : ""}` +
978
+ " Run `dench crm columns --help` for usage.",
979
+ );
980
+ }
981
+ }
982
+ }