@indigoai-us/hq-cli 5.52.0 → 5.53.1

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.
@@ -0,0 +1,132 @@
1
+ import { Command } from "commander";
2
+ import chalk from "chalk";
3
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
4
+ import { vaultApiFetch, getEntityUid } from "../utils/vault-api.js";
5
+
6
+ /**
7
+ * `hq company settings set` — owner-only per-company settings toggles
8
+ * (agency group-grants US-007 / hq-native-crm US-003). Wraps
9
+ * `PUT /company-settings`, setting the runtime-flippable `crmEnabled` /
10
+ * `ontologyEnabled` flags so an owner can enable the native CRM (and the
11
+ * ontology gardener) for a company without a redeploy.
12
+ *
13
+ * Conventions mirror `secrets.ts`: ensureCognitoToken() → getEntityUid() →
14
+ * vaultApiFetch() → error-check → chalk output.
15
+ */
16
+
17
+ interface SettingsSetFlags {
18
+ crmEnabled?: string;
19
+ ontologyEnabled?: string;
20
+ }
21
+
22
+ /**
23
+ * Parse a `--flag <true|false>` string into a boolean, or throw. Commander
24
+ * passes the raw string; we validate strictly so a typo never silently writes
25
+ * the wrong value.
26
+ */
27
+ function parseBoolFlag(value: string, flag: string): boolean {
28
+ const v = value.trim().toLowerCase();
29
+ if (v === "true") return true;
30
+ if (v === "false") return false;
31
+ throw new Error(`${flag} must be 'true' or 'false' (got '${value}')`);
32
+ }
33
+
34
+ export function registerCompanyCommand(program: Command): void {
35
+ const company = program
36
+ .command("company")
37
+ .description("Company-level settings")
38
+ .option("--company <slug>", "Company slug (resolves to companyUid)");
39
+
40
+ const settings = company
41
+ .command("settings")
42
+ .description("Per-company settings (owner-only)");
43
+
44
+ settings
45
+ .command("set")
46
+ .description(
47
+ "Set per-company settings (PUT /company-settings). Require at least one " +
48
+ "of --crm-enabled / --ontology-enabled.",
49
+ )
50
+ .option(
51
+ "--crm-enabled <true|false>",
52
+ "Enable/disable the native CRM for this company",
53
+ )
54
+ .option(
55
+ "--ontology-enabled <true|false>",
56
+ "Enable/disable the ontology gardener for this company",
57
+ )
58
+ .action(async (opts: SettingsSetFlags) => {
59
+ try {
60
+ const companySlug = company.opts().company as string | undefined;
61
+ if (!companySlug) {
62
+ console.error(chalk.red("Error: --company <slug> is required."));
63
+ process.exit(1);
64
+ }
65
+ if (opts.crmEnabled === undefined && opts.ontologyEnabled === undefined) {
66
+ console.error(
67
+ chalk.red(
68
+ "Error: provide at least one of --crm-enabled / --ontology-enabled.",
69
+ ),
70
+ );
71
+ process.exit(1);
72
+ }
73
+
74
+ const body: Record<string, unknown> = {};
75
+ if (opts.crmEnabled !== undefined) {
76
+ body.crmEnabled = parseBoolFlag(opts.crmEnabled, "--crm-enabled");
77
+ }
78
+ if (opts.ontologyEnabled !== undefined) {
79
+ body.ontologyEnabled = parseBoolFlag(
80
+ opts.ontologyEnabled,
81
+ "--ontology-enabled",
82
+ );
83
+ }
84
+
85
+ const token = await ensureCognitoToken();
86
+ const companyUid = await getEntityUid(token, { companySlug });
87
+ body.companyUid = companyUid;
88
+
89
+ const res = await vaultApiFetch({
90
+ token,
91
+ path: "/company-settings",
92
+ method: "PUT",
93
+ body,
94
+ });
95
+
96
+ if (!res.ok) {
97
+ const errBody = (await res.json().catch(() => ({}))) as Record<
98
+ string,
99
+ unknown
100
+ >;
101
+ if (res.status === 403) {
102
+ console.error(
103
+ chalk.red(
104
+ "Requires owner role on this company to change its settings.",
105
+ ),
106
+ );
107
+ process.exit(1);
108
+ }
109
+ console.error(
110
+ chalk.red(
111
+ `Failed to update company settings: ${(errBody.error as string) ?? res.statusText}`,
112
+ ),
113
+ );
114
+ process.exit(1);
115
+ }
116
+
117
+ const applied = Object.entries(body)
118
+ .filter(([k]) => k !== "companyUid")
119
+ .map(([k, v]) => `${k}=${v}`)
120
+ .join(", ");
121
+ console.log(
122
+ chalk.green(`Company settings updated for ${companySlug}: ${applied}`),
123
+ );
124
+ } catch (err) {
125
+ console.error(
126
+ chalk.red("Error:"),
127
+ err instanceof Error ? err.message : String(err),
128
+ );
129
+ process.exit(1);
130
+ }
131
+ });
132
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Unit tests for `hq crm entity upsert` (crm.ts).
3
+ *
4
+ * Mirrors members.test.ts: mock ensureCognitoToken + getEntityUid, spy on
5
+ * global fetch (vaultApiFetch's transport), drive the command through a
6
+ * Commander program, and assert the request shape + output / exit behavior.
7
+ */
8
+
9
+ import { Command } from "commander";
10
+ import {
11
+ afterEach,
12
+ beforeEach,
13
+ describe,
14
+ expect,
15
+ it,
16
+ vi,
17
+ type MockInstance,
18
+ } from "vitest";
19
+
20
+ vi.mock("../utils/cognito-session.js", async (importOriginal) => {
21
+ const original =
22
+ await importOriginal<typeof import("../utils/cognito-session.js")>();
23
+ return {
24
+ ...original,
25
+ ensureCognitoToken: vi.fn(async () => "test-token"),
26
+ };
27
+ });
28
+
29
+ vi.mock("../utils/vault-api.js", async (importOriginal) => {
30
+ const original = await importOriginal<typeof import("../utils/vault-api.js")>();
31
+ return {
32
+ ...original,
33
+ getEntityUid: vi.fn(async () => "cmp_acme"),
34
+ };
35
+ });
36
+
37
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
38
+ import { getEntityUid } from "../utils/vault-api.js";
39
+ import { registerCrmCommand } from "./crm.js";
40
+
41
+ function jsonResponse(status: number, body: unknown): Response {
42
+ return new Response(JSON.stringify(body), {
43
+ status,
44
+ headers: { "Content-Type": "application/json" },
45
+ });
46
+ }
47
+
48
+ let fetchSpy: MockInstance<typeof fetch>;
49
+ let exitSpy: MockInstance<typeof process.exit>;
50
+ const mockEnsureCognitoToken = vi.mocked(ensureCognitoToken);
51
+ const mockGetEntityUid = vi.mocked(getEntityUid);
52
+
53
+ beforeEach(() => {
54
+ vi.clearAllMocks();
55
+ fetchSpy = vi.spyOn(globalThis, "fetch");
56
+ mockEnsureCognitoToken.mockResolvedValue("test-token");
57
+ mockGetEntityUid.mockResolvedValue("cmp_acme");
58
+ // process.exit(1) on the error paths — throw so the test can assert instead
59
+ // of tearing down the worker.
60
+ exitSpy = vi
61
+ .spyOn(process, "exit")
62
+ .mockImplementation((code?: number) => {
63
+ throw new Error(`process.exit(${code})`);
64
+ }) as unknown as MockInstance<typeof process.exit>;
65
+ vi.spyOn(console, "log").mockImplementation(() => {});
66
+ vi.spyOn(console, "error").mockImplementation(() => {});
67
+ });
68
+
69
+ afterEach(() => {
70
+ vi.restoreAllMocks();
71
+ });
72
+
73
+ function buildProgram(): Command {
74
+ const program = new Command();
75
+ program.name("hq").exitOverride();
76
+ registerCrmCommand(program);
77
+ return program;
78
+ }
79
+
80
+ async function run(args: string[]): Promise<void> {
81
+ await buildProgram().parseAsync(["node", "hq", ...args]);
82
+ }
83
+
84
+ describe("hq crm entity upsert", () => {
85
+ it("flag form: POSTs a single entity to /crm/entities with external_ids", async () => {
86
+ fetchSpy.mockResolvedValueOnce(
87
+ jsonResponse(200, {
88
+ status: "written",
89
+ created: 1,
90
+ updated: 0,
91
+ skipped: 0,
92
+ errors: [],
93
+ }),
94
+ );
95
+
96
+ await run([
97
+ "crm",
98
+ "entity",
99
+ "upsert",
100
+ "--company",
101
+ "acme",
102
+ "--type",
103
+ "contact",
104
+ "--name",
105
+ "Jane Prospect",
106
+ "--attio-id",
107
+ "rec_jane",
108
+ ]);
109
+
110
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
111
+ const [url, init] = fetchSpy.mock.calls[0];
112
+ expect(String(url)).toContain("/crm/entities");
113
+ expect(init?.method).toBe("POST");
114
+ const sent = JSON.parse(init?.body as string);
115
+ expect(sent.companyUid).toBe("cmp_acme");
116
+ expect(sent.entities).toHaveLength(1);
117
+ expect(sent.entities[0]).toMatchObject({
118
+ type: "contact",
119
+ canonical_name: "Jane Prospect",
120
+ external_ids: { attio: "rec_jane" },
121
+ });
122
+ });
123
+
124
+ it("exits 1 with a helpful message on 403 CRM_DISABLED", async () => {
125
+ fetchSpy.mockResolvedValueOnce(
126
+ jsonResponse(403, {
127
+ error: "the native CRM is not enabled for this company",
128
+ code: "CRM_DISABLED",
129
+ }),
130
+ );
131
+
132
+ await expect(
133
+ run([
134
+ "crm",
135
+ "entity",
136
+ "upsert",
137
+ "--company",
138
+ "acme",
139
+ "--type",
140
+ "contact",
141
+ "--name",
142
+ "Jane",
143
+ ]),
144
+ ).rejects.toThrow("process.exit(1)");
145
+ expect(exitSpy).toHaveBeenCalledWith(1);
146
+ });
147
+
148
+ it("requires --company", async () => {
149
+ await expect(
150
+ run(["crm", "entity", "upsert", "--type", "contact", "--name", "Jane"]),
151
+ ).rejects.toThrow("process.exit(1)");
152
+ // Never made the request — failed before token resolution.
153
+ expect(fetchSpy).not.toHaveBeenCalled();
154
+ });
155
+
156
+ it("requires --type when no --json is given", async () => {
157
+ await expect(
158
+ run(["crm", "entity", "upsert", "--company", "acme", "--name", "Jane"]),
159
+ ).rejects.toThrow("process.exit(1)");
160
+ expect(fetchSpy).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it("rejects an unknown --type", async () => {
164
+ await expect(
165
+ run([
166
+ "crm",
167
+ "entity",
168
+ "upsert",
169
+ "--company",
170
+ "acme",
171
+ "--type",
172
+ "widget",
173
+ "--name",
174
+ "Jane",
175
+ ]),
176
+ ).rejects.toThrow("process.exit(1)");
177
+ expect(fetchSpy).not.toHaveBeenCalled();
178
+ });
179
+ });
@@ -0,0 +1,236 @@
1
+ import { Command } from "commander";
2
+ import chalk from "chalk";
3
+ import { readFileSync } from "node:fs";
4
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
5
+ import { vaultApiFetch, getEntityUid } from "../utils/vault-api.js";
6
+
7
+ /**
8
+ * `hq crm entity upsert` — agent-facing controlled entity upsert
9
+ * (hq-native-crm US-002). Wraps `POST /crm/entities`, which fronts the ontology
10
+ * write gate so an authenticated company MEMBER (or higher) can create/update
11
+ * canonical CRM entities in their company's vault.
12
+ *
13
+ * Conventions mirror `secrets.ts`: ensureCognitoToken() → getEntityUid() →
14
+ * vaultApiFetch() → error-check → chalk output.
15
+ */
16
+
17
+ /** The CRM/ontology entity types the upsert route accepts via `--type`. */
18
+ const CRM_ENTITY_TYPES = [
19
+ "contact",
20
+ "deal",
21
+ "contract",
22
+ "invoice",
23
+ "company",
24
+ ] as const;
25
+ type CrmEntityType = (typeof CRM_ENTITY_TYPES)[number];
26
+
27
+ /** A minimal entity payload in the write-gate ExtractedEntity shape. */
28
+ interface CrmEntityInput {
29
+ type: string;
30
+ canonical_name: string;
31
+ aliases?: string[];
32
+ confidence?: number;
33
+ domain?: string[];
34
+ relationships?: unknown[];
35
+ external_ids?: Record<string, string>;
36
+ web_domains?: string[];
37
+ }
38
+
39
+ interface UpsertFlags {
40
+ type?: string;
41
+ name?: string;
42
+ attioId?: string;
43
+ stripeId?: string;
44
+ pandadocId?: string;
45
+ neonId?: string;
46
+ json?: string;
47
+ }
48
+
49
+ /**
50
+ * Read the `--json <file|->` payload: a single entity object or an array of
51
+ * entities. `-` reads from stdin. Returns the entities array (always
52
+ * normalized to an array) or throws a descriptive Error.
53
+ */
54
+ function readJsonEntities(source: string): CrmEntityInput[] {
55
+ const raw =
56
+ source === "-"
57
+ ? readFileSync(0, "utf8") // fd 0 = stdin
58
+ : readFileSync(source, "utf8");
59
+ let parsed: unknown;
60
+ try {
61
+ parsed = JSON.parse(raw);
62
+ } catch (err) {
63
+ throw new Error(
64
+ `--json payload is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
65
+ );
66
+ }
67
+ const entities = Array.isArray(parsed) ? parsed : [parsed];
68
+ if (entities.length === 0) {
69
+ throw new Error("--json payload contained no entities");
70
+ }
71
+ for (const e of entities) {
72
+ if (!e || typeof e !== "object") {
73
+ throw new Error("--json entities must be objects");
74
+ }
75
+ const obj = e as Record<string, unknown>;
76
+ if (typeof obj.type !== "string" || typeof obj.canonical_name !== "string") {
77
+ throw new Error(
78
+ "each --json entity needs a string `type` and `canonical_name`",
79
+ );
80
+ }
81
+ }
82
+ return entities as CrmEntityInput[];
83
+ }
84
+
85
+ /**
86
+ * Build a single entity from the flag form (`--type` + `--name` + optional
87
+ * external-id flags). The route fills the additive defaults (aliases/domain/
88
+ * relationships/confidence) when omitted, but we send a complete minimal shape.
89
+ */
90
+ function buildEntityFromFlags(opts: UpsertFlags): CrmEntityInput {
91
+ const externalIds: Record<string, string> = {};
92
+ if (opts.attioId) externalIds.attio = opts.attioId;
93
+ if (opts.stripeId) externalIds.stripe = opts.stripeId;
94
+ if (opts.pandadocId) externalIds.pandadoc = opts.pandadocId;
95
+ if (opts.neonId) externalIds.neon = opts.neonId;
96
+
97
+ const entity: CrmEntityInput = {
98
+ type: opts.type as CrmEntityType,
99
+ canonical_name: opts.name as string,
100
+ aliases: [],
101
+ confidence: 1,
102
+ domain: [],
103
+ relationships: [],
104
+ };
105
+ if (Object.keys(externalIds).length > 0) {
106
+ entity.external_ids = externalIds;
107
+ }
108
+ return entity;
109
+ }
110
+
111
+ export function registerCrmCommand(program: Command): void {
112
+ const crm = program
113
+ .command("crm")
114
+ .description("Native CRM — upsert canonical entities into a company vault")
115
+ .option("--company <slug>", "Company slug (resolves to companyUid)");
116
+
117
+ const entity = crm
118
+ .command("entity")
119
+ .description("CRM entity operations");
120
+
121
+ entity
122
+ .command("upsert")
123
+ .description(
124
+ "Create or update a canonical CRM entity (POST /crm/entities). " +
125
+ "Use --type/--name (+ optional external-id flags) or --json <file|-> " +
126
+ "to pass a full entity/array.",
127
+ )
128
+ .option(
129
+ "--type <type>",
130
+ `Entity type: ${CRM_ENTITY_TYPES.join(" | ")}`,
131
+ )
132
+ .option("--name <canonical_name>", "Canonical entity name")
133
+ .option("--attio-id <id>", "Attio record id → external_ids.attio")
134
+ .option("--stripe-id <id>", "Stripe object id → external_ids.stripe")
135
+ .option("--pandadoc-id <id>", "PandaDoc document id → external_ids.pandadoc")
136
+ .option("--neon-id <id>", "Neon row id → external_ids.neon")
137
+ .option(
138
+ "--json <file|->",
139
+ "Path to a JSON file (or '-' for stdin) with a full entity object or array",
140
+ )
141
+ .action(async (opts: UpsertFlags) => {
142
+ try {
143
+ const companySlug = crm.opts().company as string | undefined;
144
+ if (!companySlug) {
145
+ console.error(
146
+ chalk.red("Error: --company <slug> is required."),
147
+ );
148
+ process.exit(1);
149
+ }
150
+
151
+ // Resolve the entity payload: --json is the alternative to flags.
152
+ let entities: CrmEntityInput[];
153
+ if (opts.json) {
154
+ entities = readJsonEntities(opts.json);
155
+ } else {
156
+ if (!opts.type) {
157
+ console.error(
158
+ chalk.red(
159
+ `Error: --type <${CRM_ENTITY_TYPES.join("|")}> is required (or pass --json).`,
160
+ ),
161
+ );
162
+ process.exit(1);
163
+ }
164
+ if (!CRM_ENTITY_TYPES.includes(opts.type as CrmEntityType)) {
165
+ console.error(
166
+ chalk.red(
167
+ `Error: --type must be one of ${CRM_ENTITY_TYPES.join(", ")}.`,
168
+ ),
169
+ );
170
+ process.exit(1);
171
+ }
172
+ if (!opts.name) {
173
+ console.error(
174
+ chalk.red("Error: --name <canonical_name> is required (or pass --json)."),
175
+ );
176
+ process.exit(1);
177
+ }
178
+ entities = [buildEntityFromFlags(opts)];
179
+ }
180
+
181
+ const token = await ensureCognitoToken();
182
+ const companyUid = await getEntityUid(token, { companySlug });
183
+
184
+ const res = await vaultApiFetch({
185
+ token,
186
+ path: "/crm/entities",
187
+ method: "POST",
188
+ body: { companyUid, entities },
189
+ });
190
+
191
+ if (!res.ok) {
192
+ const body = (await res.json().catch(() => ({}))) as Record<
193
+ string,
194
+ unknown
195
+ >;
196
+ // CrmDisabledError surfaces as a 403 with a helpful message.
197
+ if (res.status === 403 && body.code === "CRM_DISABLED") {
198
+ console.error(
199
+ chalk.red(
200
+ "CRM is not enabled for this company. Enable it first: " +
201
+ `hq company settings set --company ${companySlug} --crm-enabled true`,
202
+ ),
203
+ );
204
+ process.exit(1);
205
+ }
206
+ console.error(
207
+ chalk.red(
208
+ `Failed to upsert entities: ${(body.error as string) ?? res.statusText}`,
209
+ ),
210
+ );
211
+ process.exit(1);
212
+ }
213
+
214
+ const result = (await res.json().catch(() => ({}))) as {
215
+ created?: number;
216
+ updated?: number;
217
+ skipped?: number;
218
+ status?: string;
219
+ };
220
+ console.log(
221
+ chalk.green(
222
+ `Upsert ${result.status ?? "ok"}: ` +
223
+ `${result.created ?? 0} created, ` +
224
+ `${result.updated ?? 0} updated, ` +
225
+ `${result.skipped ?? 0} skipped.`,
226
+ ),
227
+ );
228
+ } catch (err) {
229
+ console.error(
230
+ chalk.red("Error:"),
231
+ err instanceof Error ? err.message : String(err),
232
+ );
233
+ process.exit(1);
234
+ }
235
+ });
236
+ }
@@ -398,3 +398,87 @@ describe("hq files delete — server error mapping", () => {
398
398
  expect(formatFilesDeleteError(new FilesDeleteHttpError(500, "boom"), "p")).toMatch(/Server error: boom/);
399
399
  });
400
400
  });
401
+
402
+ describe("hq files delete — --personal (personal vault scope)", () => {
403
+ // Body parser tolerant of both scope shapes (company vs personal).
404
+ function bodies(): Array<Record<string, unknown>> {
405
+ return deleteCalls().map((c) => JSON.parse((c[1]?.body as string) ?? "{}"));
406
+ }
407
+
408
+ it("--dry-run sends { personal: true } with NO company membership lookup", async () => {
409
+ // First (and only) fetch is the delete preview — getCompanyUid is skipped.
410
+ fetchSpy.mockResolvedValueOnce(
411
+ deleteResponse({
412
+ dryRun: true,
413
+ matched: 2,
414
+ keys: ["installer/a.txt", "installer/b.txt"],
415
+ }),
416
+ );
417
+
418
+ const program = buildProgram();
419
+ await program.parseAsync(
420
+ ["files", "delete", "installer/", "--personal", "--dry-run"],
421
+ { from: "user" },
422
+ );
423
+
424
+ const b = bodies();
425
+ expect(b).toHaveLength(1);
426
+ expect(b[0]).toEqual({ personal: true, prefix: "installer/*", dryRun: true });
427
+ expect(b[0]).not.toHaveProperty("company");
428
+ expect(printed()).toContain("[dry-run]");
429
+ expect(exitSpy).not.toHaveBeenCalled();
430
+ });
431
+
432
+ it("real delete with --yes previews then deletes, both bodies personal-scoped", async () => {
433
+ fetchSpy.mockResolvedValueOnce(
434
+ deleteResponse({ dryRun: true, matched: 2, keys: ["installer/a.txt", "installer/b.txt"] }),
435
+ );
436
+ fetchSpy.mockResolvedValueOnce(
437
+ deleteResponse({ dryRun: false, matched: 2, deleted: 2, tombstoned: 2 }),
438
+ );
439
+
440
+ const program = buildProgram();
441
+ await program.parseAsync(
442
+ ["files", "delete", "installer/*", "--personal", "--yes"],
443
+ { from: "user" },
444
+ );
445
+
446
+ const b = bodies();
447
+ expect(b).toHaveLength(2);
448
+ expect(b[0]).toEqual({ personal: true, prefix: "installer/*", dryRun: true });
449
+ expect(b[1]).toEqual({ personal: true, prefix: "installer/*", dryRun: false });
450
+ expect(printed()).toContain("Deleted 2 objects");
451
+ });
452
+
453
+ it("confirmation copy says 'your personal vault' (not the shared-vault wording)", async () => {
454
+ fetchSpy.mockResolvedValueOnce(
455
+ deleteResponse({ dryRun: true, matched: 1, keys: ["installer/a.txt"] }),
456
+ );
457
+ let prompt = "";
458
+ await runFilesDelete(
459
+ { prefix: "installer/*", dryRun: false, yes: false, personal: true, companySlug: undefined },
460
+ {
461
+ confirm: async (m) => {
462
+ prompt = m;
463
+ return false;
464
+ },
465
+ },
466
+ );
467
+ expect(prompt).toContain("your personal vault");
468
+ expect(prompt).not.toContain("shared vault");
469
+ // Declined → no real delete (only the preview fetch happened).
470
+ expect(bodies()).toHaveLength(1);
471
+ });
472
+
473
+ it("rejects --personal combined with --company before any network call", async () => {
474
+ const program = buildProgram();
475
+ await expect(
476
+ program.parseAsync(
477
+ ["files", "--company", "acme", "delete", "installer/*", "--personal"],
478
+ { from: "user" },
479
+ ),
480
+ ).rejects.toThrow(/__EXIT__:1/);
481
+ expect(printedErr()).toContain("Pass either --personal or --company");
482
+ expect(deleteCalls()).toHaveLength(0);
483
+ });
484
+ });