@indigoai-us/hq-cli 5.50.1 → 5.51.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.
Files changed (61) hide show
  1. package/dist/bin/hq-auth-refresh.d.ts +1 -1
  2. package/dist/bin/hq-auth-refresh.js +5 -2
  3. package/dist/commands/members.d.ts +17 -0
  4. package/dist/commands/members.js +65 -28
  5. package/dist/commands/onboard-warning.d.ts +7 -0
  6. package/dist/commands/onboard-warning.js +14 -0
  7. package/dist/commands/onboard.js +5 -5
  8. package/dist/commands/pack-install.d.ts +12 -0
  9. package/dist/commands/pack-install.js +74 -3
  10. package/dist/commands/packs.js +17 -3
  11. package/dist/commands/people.d.ts +26 -1
  12. package/dist/commands/people.js +70 -7
  13. package/dist/commands/secrets-scope.d.ts +20 -0
  14. package/dist/commands/secrets-scope.js +19 -0
  15. package/dist/commands/secrets.js +21 -6
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +44 -14
  18. package/dist/node-preflight.d.ts +39 -0
  19. package/dist/node-preflight.js +55 -0
  20. package/dist/sentry.d.ts +12 -0
  21. package/dist/sentry.js +19 -3
  22. package/dist/types.d.ts +18 -0
  23. package/dist/utils/epipe.d.ts +8 -0
  24. package/dist/utils/epipe.js +30 -0
  25. package/dist/utils/intercepted-process-exit.d.ts +7 -0
  26. package/dist/utils/intercepted-process-exit.js +38 -0
  27. package/dist/utils/pack-contributions.d.ts +7 -0
  28. package/dist/utils/pack-contributions.js +12 -2
  29. package/dist/utils/version-gate.d.ts +40 -1
  30. package/dist/utils/version-gate.js +91 -20
  31. package/e2e/cli.test.ts +35 -0
  32. package/package.json +1 -1
  33. package/src/bin/hq-auth-refresh.ts +3 -0
  34. package/src/commands/members.test.ts +176 -0
  35. package/src/commands/members.ts +113 -28
  36. package/src/commands/onboard-warning.test.ts +26 -0
  37. package/src/commands/onboard-warning.ts +12 -0
  38. package/src/commands/onboard.ts +4 -7
  39. package/src/commands/pack-install.test.ts +144 -0
  40. package/src/commands/pack-install.ts +86 -1
  41. package/src/commands/packs.ts +19 -0
  42. package/src/commands/people.test.ts +212 -5
  43. package/src/commands/people.ts +141 -5
  44. package/src/commands/secrets-scope.test.ts +56 -0
  45. package/src/commands/secrets-scope.ts +32 -0
  46. package/src/commands/secrets.ts +24 -10
  47. package/src/index.ts +40 -12
  48. package/src/node-preflight.test.ts +60 -0
  49. package/src/node-preflight.ts +67 -0
  50. package/src/sentry-epipe.test.ts +37 -0
  51. package/src/sentry-release.test.ts +54 -0
  52. package/src/sentry.ts +21 -1
  53. package/src/types.ts +19 -1
  54. package/src/utils/epipe.test.ts +28 -0
  55. package/src/utils/epipe.ts +29 -0
  56. package/src/utils/intercepted-process-exit.test.ts +37 -0
  57. package/src/utils/intercepted-process-exit.ts +36 -0
  58. package/src/utils/pack-contributions.test.ts +53 -0
  59. package/src/utils/pack-contributions.ts +17 -0
  60. package/src/utils/version-gate.test.ts +122 -0
  61. package/src/utils/version-gate.ts +109 -13
@@ -14,9 +14,17 @@
14
14
  import * as fs from "fs";
15
15
  import { Command, Option } from "commander";
16
16
  import chalk from "chalk";
17
+ import { VaultClient } from "@indigoai-us/hq-cloud";
17
18
  import * as yaml from "js-yaml";
18
19
  import { findHqRoot } from "../utils/manifest.js";
19
20
  import { manifestPath, type ManifestDoc } from "./cloud-provision.js";
21
+ import {
22
+ DEFAULT_COGNITO,
23
+ buildVaultConfig,
24
+ ensureCognitoToken,
25
+ } from "../utils/cognito-session.js";
26
+ import { getCompanyUid } from "../utils/vault-api.js";
27
+ import { createCompanyPresignClient, runGet } from "./files-browse.js";
20
28
  import {
21
29
  assertSafeCompanySlug,
22
30
  listCompanyPeople,
@@ -31,6 +39,39 @@ interface PeopleScopeOpts {
31
39
  hqRoot?: string;
32
40
  }
33
41
 
42
+ export type RefreshPeopleRoster = (
43
+ hqRoot: string,
44
+ companySlug: string,
45
+ ) => Promise<void>;
46
+
47
+ interface PeopleCommandDeps {
48
+ refreshRoster?: RefreshPeopleRoster;
49
+ }
50
+
51
+ interface PeopleLookupOpts {
52
+ localOnly?: boolean;
53
+ json?: boolean;
54
+ }
55
+
56
+ export async function refreshPeopleRosterFromCloud(
57
+ hqRoot: string,
58
+ companySlug: string,
59
+ ): Promise<void> {
60
+ const accessToken = await ensureCognitoToken();
61
+ const client = new VaultClient(buildVaultConfig(accessToken));
62
+ await getCompanyUid(accessToken, companySlug);
63
+
64
+ await runGet({
65
+ path: `companies/${companySlug}/people/`,
66
+ hqRoot,
67
+ companySlug,
68
+ vaultClient: client,
69
+ companyClient: ({ companyUid }) =>
70
+ createCompanyPresignClient({ token: accessToken, companyUid }),
71
+ region: DEFAULT_COGNITO.region,
72
+ });
73
+ }
74
+
34
75
  /** Companies that still exist (anything not explicitly `status: archived`). */
35
76
  function activeCompanySlugs(manifest: ManifestDoc): string[] {
36
77
  const companies = manifest.companies ?? {};
@@ -118,7 +159,82 @@ function fail(message: string): never {
118
159
  process.exit(1);
119
160
  }
120
161
 
121
- export function registerPeopleCommand(program: Command): void {
162
+ function logRefreshFailure(companySlug: string, err: unknown): void {
163
+ const message = err instanceof Error ? err.message : String(err);
164
+ console.error(
165
+ chalk.dim(
166
+ ` Could not refresh people roster for '${companySlug}': ${message}`,
167
+ ),
168
+ );
169
+ }
170
+
171
+ async function tryRefreshRoster(
172
+ refreshRoster: RefreshPeopleRoster,
173
+ hqRoot: string,
174
+ slug: string,
175
+ ): Promise<boolean> {
176
+ try {
177
+ await refreshRoster(hqRoot, slug);
178
+ return true;
179
+ } catch (err) {
180
+ logRefreshFailure(slug, err);
181
+ return false;
182
+ }
183
+ }
184
+
185
+ export async function resolvePersonWithRosterFallback(
186
+ input: {
187
+ hqRoot: string;
188
+ slug: string;
189
+ name: string;
190
+ opts?: PeopleLookupOpts;
191
+ refreshRoster?: RefreshPeopleRoster;
192
+ },
193
+ ): Promise<ReturnType<typeof resolveNameToEmail>> {
194
+ const local = resolveNameToEmail(
195
+ listCompanyPeople(input.hqRoot, input.slug),
196
+ input.name,
197
+ );
198
+ if (local.status !== "not_found" || input.opts?.localOnly) return local;
199
+
200
+ const refreshed = await tryRefreshRoster(
201
+ input.refreshRoster ?? refreshPeopleRosterFromCloud,
202
+ input.hqRoot,
203
+ input.slug,
204
+ );
205
+ if (!refreshed) return local;
206
+ return resolveNameToEmail(
207
+ listCompanyPeople(input.hqRoot, input.slug),
208
+ input.name,
209
+ );
210
+ }
211
+
212
+ export async function searchPeopleWithRosterFallback(input: {
213
+ hqRoot: string;
214
+ slug: string;
215
+ keyword: string;
216
+ opts?: PeopleLookupOpts;
217
+ refreshRoster?: RefreshPeopleRoster;
218
+ }): Promise<PersonRecord[]> {
219
+ const local = searchPeople(
220
+ listCompanyPeople(input.hqRoot, input.slug),
221
+ input.keyword,
222
+ );
223
+ if (local.length > 0 || input.opts?.localOnly) return local;
224
+
225
+ const refreshed = await tryRefreshRoster(
226
+ input.refreshRoster ?? refreshPeopleRosterFromCloud,
227
+ input.hqRoot,
228
+ input.slug,
229
+ );
230
+ if (!refreshed) return local;
231
+ return searchPeople(listCompanyPeople(input.hqRoot, input.slug), input.keyword);
232
+ }
233
+
234
+ export function registerPeopleCommand(
235
+ program: Command,
236
+ deps: PeopleCommandDeps = {},
237
+ ): void {
122
238
  const people = program
123
239
  .command("people")
124
240
  .description(
@@ -170,12 +286,22 @@ export function registerPeopleCommand(program: Command): void {
170
286
  .command("search <keyword>")
171
287
  .description("Keyword search over people names and emails")
172
288
  .option("--json", "Output JSON instead of a table")
173
- .action((keyword: string, opts: { json?: boolean }) => {
289
+ .option(
290
+ "--local-only",
291
+ "Skip cloud fallback; search only the local people roster",
292
+ )
293
+ .action(async (keyword: string, opts: PeopleLookupOpts) => {
174
294
  try {
175
295
  const scope = people.opts() as PeopleScopeOpts;
176
296
  const hqRoot = resolveHqRoot(scope);
177
297
  const slug = resolveCompanySlug(hqRoot, scope.company);
178
- const matches = searchPeople(listCompanyPeople(hqRoot, slug), keyword);
298
+ const matches = await searchPeopleWithRosterFallback({
299
+ hqRoot,
300
+ slug,
301
+ keyword,
302
+ opts,
303
+ refreshRoster: deps.refreshRoster,
304
+ });
179
305
 
180
306
  if (opts.json) {
181
307
  console.log(JSON.stringify(matches, null, 2));
@@ -195,12 +321,22 @@ export function registerPeopleCommand(program: Command): void {
195
321
  .command("resolve <name>")
196
322
  .description("Resolve a person name to their email address")
197
323
  .option("--json", "Output JSON instead of plain text")
198
- .action((name: string, opts: { json?: boolean }) => {
324
+ .option(
325
+ "--local-only",
326
+ "Skip cloud fallback; resolve only from the local people roster",
327
+ )
328
+ .action(async (name: string, opts: PeopleLookupOpts) => {
199
329
  try {
200
330
  const scope = people.opts() as PeopleScopeOpts;
201
331
  const hqRoot = resolveHqRoot(scope);
202
332
  const slug = resolveCompanySlug(hqRoot, scope.company);
203
- const result = resolveNameToEmail(listCompanyPeople(hqRoot, slug), name);
333
+ const result = await resolvePersonWithRosterFallback({
334
+ hqRoot,
335
+ slug,
336
+ name,
337
+ opts,
338
+ refreshRoster: deps.refreshRoster,
339
+ });
204
340
 
205
341
  if (opts.json) {
206
342
  console.log(JSON.stringify(result, null, 2));
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ describeSecretsScope,
5
+ formatSecretSaved,
6
+ formatSecretsListEmpty,
7
+ formatSecretsListHeader,
8
+ } from "./secrets-scope.js";
9
+
10
+ describe("describeSecretsScope", () => {
11
+ it("describes the personal vault", () => {
12
+ expect(
13
+ describeSecretsScope({ personal: true, companyUid: "prs_alice" }),
14
+ ).toBe("your personal vault");
15
+ });
16
+
17
+ it("describes a company by slug when present", () => {
18
+ expect(
19
+ describeSecretsScope({
20
+ personal: false,
21
+ companySlug: "acme",
22
+ companyUid: "cmp_01ABC",
23
+ }),
24
+ ).toBe("company acme");
25
+ });
26
+
27
+ it("describes a company by uid when no slug is present", () => {
28
+ expect(
29
+ describeSecretsScope({ personal: false, companyUid: "cmp_01ABC" }),
30
+ ).toBe("company cmp_01ABC");
31
+ });
32
+ });
33
+
34
+ describe("formatSecretSaved", () => {
35
+ it("formats the set echo", () => {
36
+ expect(formatSecretSaved("MY_KEY", "your personal vault")).toBe(
37
+ "Secret 'MY_KEY' saved to your personal vault.",
38
+ );
39
+ });
40
+ });
41
+
42
+ describe("formatSecretsListHeader", () => {
43
+ it("formats the list header", () => {
44
+ expect(formatSecretsListHeader("company acme")).toBe(
45
+ "Secrets for company acme:",
46
+ );
47
+ });
48
+ });
49
+
50
+ describe("formatSecretsListEmpty", () => {
51
+ it("formats the empty list message", () => {
52
+ expect(formatSecretsListEmpty("your personal vault")).toBe(
53
+ "No secrets found for your personal vault.",
54
+ );
55
+ });
56
+ });
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Pure helpers describing WHICH secrets scope a command acted on, so `set` and
3
+ * `list` can echo it. Users were setting a secret in one scope (personal vs a
4
+ * company, or company A vs B) and listing another, then seeing "no secrets" with
5
+ * no indication the scopes differed (feedback_70e059da).
6
+ */
7
+ export interface SecretsScopeRef {
8
+ /** True when --personal was used (caller's personal vault). */
9
+ personal: boolean;
10
+ /** The slug the user passed via --company, if any. */
11
+ companySlug?: string;
12
+ /** Resolved entity uid: prs_* for personal, cmp_* for a company. */
13
+ companyUid: string;
14
+ }
15
+
16
+ /** Human label for a secrets scope: "your personal vault" or "company <slug-or-uid>". */
17
+ export function describeSecretsScope(ref: SecretsScopeRef): string {
18
+ if (ref.personal) return "your personal vault";
19
+ return `company ${ref.companySlug ?? ref.companyUid}`;
20
+ }
21
+
22
+ export function formatSecretSaved(name: string, scope: string): string {
23
+ return `Secret '${name}' saved to ${scope}.`;
24
+ }
25
+
26
+ export function formatSecretsListHeader(scope: string): string {
27
+ return `Secrets for ${scope}:`;
28
+ }
29
+
30
+ export function formatSecretsListEmpty(scope: string): string {
31
+ return `No secrets found for ${scope}.`;
32
+ }
@@ -13,6 +13,12 @@ import {
13
13
  } from "../utils/secrets-cache.js";
14
14
  import { computeSha256 } from "../utils/integrity.js";
15
15
  import { SECRET_NAME_PATTERN, GROUP_ID_PATTERN } from "./_patterns.js";
16
+ import {
17
+ describeSecretsScope,
18
+ formatSecretSaved,
19
+ formatSecretsListEmpty,
20
+ formatSecretsListHeader,
21
+ } from "./secrets-scope.js";
16
22
  import {
17
23
  vaultApiFetch,
18
24
  getCompanyUid,
@@ -506,10 +512,13 @@ export function registerSecretsCommand(program: Command): void {
506
512
  }
507
513
 
508
514
  const token = await ensureCognitoToken();
509
- const companyUid = await getEntityUid(
510
- token,
511
- scopeOpts(secrets.opts()),
512
- );
515
+ const scope = scopeOpts(secrets.opts());
516
+ const companyUid = await getEntityUid(token, scope);
517
+ const scopeLabel = describeSecretsScope({
518
+ personal: scope.personal,
519
+ companySlug: scope.companySlug,
520
+ companyUid,
521
+ });
513
522
 
514
523
  const res = await vaultApiFetch({
515
524
  token,
@@ -527,7 +536,7 @@ export function registerSecretsCommand(program: Command): void {
527
536
  }
528
537
 
529
538
  removeCacheEntry(companyUid, name);
530
- console.log(chalk.green(`Secret '${name}' saved.`));
539
+ console.log(chalk.green(formatSecretSaved(name, scopeLabel)));
531
540
  } catch (err) {
532
541
  console.error(
533
542
  chalk.red("Error:"),
@@ -703,10 +712,13 @@ export function registerSecretsCommand(program: Command): void {
703
712
  }
704
713
 
705
714
  const token = await ensureCognitoToken();
706
- const companyUid = await getEntityUid(
707
- token,
708
- scopeOpts(secrets.opts()),
709
- );
715
+ const scope = scopeOpts(secrets.opts());
716
+ const companyUid = await getEntityUid(token, scope);
717
+ const scopeLabel = describeSecretsScope({
718
+ personal: scope.personal,
719
+ companySlug: scope.companySlug,
720
+ companyUid,
721
+ });
710
722
 
711
723
  const query: Record<string, string> = {};
712
724
  if (normalizedPrefix) {
@@ -739,7 +751,7 @@ export function registerSecretsCommand(program: Command): void {
739
751
  };
740
752
 
741
753
  if (data.secrets.length === 0) {
742
- console.log(chalk.dim("No secrets found."));
754
+ console.log(chalk.dim(formatSecretsListEmpty(scopeLabel)));
743
755
  return;
744
756
  }
745
757
 
@@ -756,6 +768,7 @@ export function registerSecretsCommand(program: Command): void {
756
768
  if (hasPermission) {
757
769
  const accessWidth = Math.max(6, ...data.secrets.map((s) => (s.permission ?? "-").length));
758
770
  const header = `${"NAME".padEnd(nameWidth)} ${"ACCESS".padEnd(accessWidth)} ${"TIER".padEnd(tierWidth)} ${"SCRIPT LOCK".padEnd(scriptLockWidth)} LAST MODIFIED`;
771
+ console.log(chalk.dim(formatSecretsListHeader(scopeLabel)));
759
772
  console.log(chalk.bold(header));
760
773
  for (const s of data.secrets) {
761
774
  const access = s.permission ?? "-";
@@ -766,6 +779,7 @@ export function registerSecretsCommand(program: Command): void {
766
779
  }
767
780
  } else {
768
781
  const header = `${"NAME".padEnd(nameWidth)} ${"TIER".padEnd(tierWidth)} ${"SCRIPT LOCK".padEnd(scriptLockWidth)} LAST MODIFIED`;
782
+ console.log(chalk.dim(formatSecretsListHeader(scopeLabel)));
769
783
  console.log(chalk.bold(header));
770
784
  for (const s of data.secrets) {
771
785
  const tier = normalizeSecretTier(s.tier);
package/src/index.ts CHANGED
@@ -4,6 +4,9 @@
4
4
  * HQ CLI - Module management, package management, and cloud sync for HQ
5
5
  */
6
6
 
7
+ // MUST be first: guard the Node version before any dependency that needs a
8
+ // Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
9
+ import "./node-preflight.js";
7
10
  import { Command } from "commander";
8
11
  import { initSentry, Sentry } from "./sentry.js";
9
12
  import { registerAddCommand } from "./commands/add.js";
@@ -47,6 +50,8 @@ import { registerRescueCommand } from "./commands/rescue.js";
47
50
  import { registerMcpCommand } from "./commands/mcp-status.js";
48
51
  import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
49
52
  import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
53
+ import { isEpipe } from "./utils/epipe.js";
54
+ import { isInterceptedProcessExit } from "./utils/intercepted-process-exit.js";
50
55
  import {
51
56
  maybeWarnNewVersion,
52
57
  refreshVersionCache,
@@ -57,9 +62,13 @@ import {
57
62
  } from "./utils/version-gate.js";
58
63
  import { CLI_VERSION } from "./cli-version.js";
59
64
 
60
- // Swallow EPIPE when a downstream reader (e.g. `source <(…)`, `| head`) closes the pipe early.
65
+ // Swallow EPIPE when a downstream reader (e.g. `source <(…)`, `| head`) closes
66
+ // the pipe early. This covers the ASYNC path — an 'error' event emitted on the
67
+ // stream. The SYNCHRONOUS path (a `write EPIPE` thrown straight out of
68
+ // console.log inside a command) is handled in the top-level catch below; both
69
+ // share `isEpipe` (HQ-6B).
61
70
  const onPipeError = (err: NodeJS.ErrnoException): void => {
62
- if (err.code === "EPIPE") {
71
+ if (isEpipe(err)) {
63
72
  process.exit(0);
64
73
  }
65
74
  throw err;
@@ -222,18 +231,37 @@ registerMcpCommand(program);
222
231
  }
223
232
  await program.parseAsync();
224
233
  } catch (err) {
225
- // A full disk / exhausted quota / read-only filesystem is the user's
226
- // machine, not an HQ code defect. Surface a clear, actionable message and
227
- // skip Sentry capture so one full disk doesn't flood the tracker with
228
- // identical, unfixable crash reports (HQ-CLI-2). Genuine errors still go
229
- // to Sentry and still exit 1.
230
- const envMsg = environmentalFsErrorMessage(err);
231
- if (envMsg) {
232
- process.stderr.write(`hq: ${envMsg}\n`);
234
+ // A broken pipe (EPIPE) means the reader of `hq`'s output closed it early
235
+ // (`hq | head`, `source <(hq …)`, a parent that exited). That is normal
236
+ // Unix behavior with no user-facing degradation exit cleanly (0) and
237
+ // skip Sentry capture instead of shipping a fatal (HQ-6B). A synchronous
238
+ // `write EPIPE` thrown out of console.log lands here rather than on the
239
+ // stream 'error' listener above.
240
+ if (isEpipe(err)) {
241
+ process.exitCode = 0;
242
+ } else if (isInterceptedProcessExit(err)) {
243
+ // A security/audit FUZZ harness replaced `process.exit` with a throw so it
244
+ // can keep exercising the binary. Commander calling `process.exit` for
245
+ // normal CLI control flow (e.g. an unknown command → exit 1) then surfaces
246
+ // here as that synthetic marker. It is a test-harness artifact, NOT an
247
+ // hq-cli defect — a real user's `process.exit` just exits, so nothing is
248
+ // thrown or captured. Skip Sentry capture (no signal, no user-facing
249
+ // degradation) and preserve the intended non-zero exit (HQ-CLI-3).
250
+ process.exitCode = 1;
233
251
  } else {
234
- Sentry.captureException(err);
252
+ // A full disk / exhausted quota / read-only filesystem is the user's
253
+ // machine, not an HQ code defect. Surface a clear, actionable message and
254
+ // skip Sentry capture so one full disk doesn't flood the tracker with
255
+ // identical, unfixable crash reports (HQ-CLI-2). Genuine errors still go
256
+ // to Sentry and still exit 1.
257
+ const envMsg = environmentalFsErrorMessage(err);
258
+ if (envMsg) {
259
+ process.stderr.write(`hq: ${envMsg}\n`);
260
+ } else {
261
+ Sentry.captureException(err);
262
+ }
263
+ process.exitCode = 1;
235
264
  }
236
- process.exitCode = 1;
237
265
  } finally {
238
266
  // Release health: finalize the per-run session before the flush.
239
267
  Sentry.endSession();
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Unit tests for the runtime Node version guard.
3
+ *
4
+ * The guard fails the CLI fast on Node < 20 (where prebuilt native modules hit
5
+ * an ABI mismatch and `util.styleText` is missing) with an actionable upgrade
6
+ * message, and is a no-op on Node 20+.
7
+ */
8
+
9
+ import { describe, expect, it } from "vitest";
10
+
11
+ import { MIN_NODE_MAJOR, checkNodeVersion } from "./node-preflight.js";
12
+
13
+ describe("checkNodeVersion", () => {
14
+ it("rejects Node 18 with an actionable upgrade message", () => {
15
+ const result = checkNodeVersion("18.19.0");
16
+
17
+ expect(result.ok).toBe(false);
18
+ expect(result.major).toBe(18);
19
+ expect(result.message).toContain(`Node.js ${MIN_NODE_MAJOR} or newer`);
20
+ expect(result.message).toContain("18.19.0");
21
+ expect(result.message).toMatch(/upgrade/i);
22
+ });
23
+
24
+ it("rejects every major below the minimum", () => {
25
+ for (const version of ["14.21.3", "16.20.2", "19.9.0"]) {
26
+ const result = checkNodeVersion(version);
27
+ expect(result.ok).toBe(false);
28
+ expect(result.message).toBeDefined();
29
+ }
30
+ });
31
+
32
+ it("accepts Node 20 (the minimum) without a message", () => {
33
+ const result = checkNodeVersion("20.11.1");
34
+
35
+ expect(result.ok).toBe(true);
36
+ expect(result.major).toBe(20);
37
+ expect(result.message).toBeUndefined();
38
+ });
39
+
40
+ it("accepts newer majors (22, 24)", () => {
41
+ for (const version of ["22.3.0", "24.0.0"]) {
42
+ const result = checkNodeVersion(version);
43
+ expect(result.ok).toBe(true);
44
+ expect(result.message).toBeUndefined();
45
+ }
46
+ });
47
+
48
+ it("treats an unparseable version as supported (never blocks on a bad string)", () => {
49
+ const result = checkNodeVersion("not-a-version");
50
+
51
+ expect(result.ok).toBe(true);
52
+ expect(result.message).toBeUndefined();
53
+ });
54
+
55
+ it("defaults to the running runtime, which is supported in CI", () => {
56
+ // The test runner itself must be on a supported Node, so the default-arg
57
+ // path returns ok — also proving importing this module did not exit.
58
+ expect(checkNodeVersion().ok).toBe(true);
59
+ });
60
+ });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Runtime Node.js version guard for the hq CLI.
3
+ *
4
+ * HQ tooling requires Node.js 20 or newer. On older runtimes (notably Node 18)
5
+ * the CLI dies with cryptic failures long before reaching any of its own code:
6
+ * a native-module ABI mismatch from a prebuilt dependency, and a missing
7
+ * `util.styleText` (added in Node 20). Those errors give the user no hint that
8
+ * the real problem is just an old Node.
9
+ *
10
+ * This module exists to fail fast with an actionable message instead. It is
11
+ * imported FIRST by every CLI entry point (`index.ts`, `bin/hq-auth-refresh.ts`)
12
+ * so the check runs before commander, Sentry, or any dependency that needs a
13
+ * Node 20+ API or a newer native ABI is evaluated. ES modules evaluate their
14
+ * imports in source order, so as long as this is the first import in the entry
15
+ * module, the guard short-circuits an unsupported runtime cleanly.
16
+ *
17
+ * Keep this file dependency-free — it must not import anything that could itself
18
+ * fail to load on the very runtime it is trying to detect.
19
+ */
20
+
21
+ export const MIN_NODE_MAJOR = 20;
22
+
23
+ export interface NodeVersionCheck {
24
+ ok: boolean;
25
+ major: number;
26
+ message?: string;
27
+ }
28
+
29
+ /**
30
+ * Pure check: is the given Node version string (e.g. "18.19.0") supported?
31
+ * Defaults to the running runtime's version. An unparseable version is treated
32
+ * as supported so we never block a user on a version string we can't read.
33
+ */
34
+ export function checkNodeVersion(
35
+ versionString: string = process.versions.node,
36
+ ): NodeVersionCheck {
37
+ const major = Number.parseInt(String(versionString).split(".")[0] ?? "", 10);
38
+
39
+ if (!Number.isFinite(major) || major >= MIN_NODE_MAJOR) {
40
+ return { ok: true, major };
41
+ }
42
+
43
+ const message =
44
+ `hq requires Node.js ${MIN_NODE_MAJOR} or newer — you are running Node ${versionString}.\n` +
45
+ `Older versions fail with native-module ABI mismatches and missing APIs.\n` +
46
+ `Please upgrade to Node ${MIN_NODE_MAJOR}+ (https://nodejs.org/) and run hq again.`;
47
+
48
+ return { ok: false, major, message };
49
+ }
50
+
51
+ /**
52
+ * Side-effecting guard run on import: prints the upgrade message to stderr and
53
+ * exits 1 on an unsupported runtime. A no-op on Node 20+. Set
54
+ * `HQ_SKIP_NODE_PREFLIGHT=1` to bypass (used by the test runner, which already
55
+ * runs on a supported Node).
56
+ */
57
+ export function enforceNodeVersion(): void {
58
+ if (process.env.HQ_SKIP_NODE_PREFLIGHT) return;
59
+
60
+ const result = checkNodeVersion();
61
+ if (!result.ok && result.message) {
62
+ process.stderr.write(`${result.message}\n`);
63
+ process.exit(1);
64
+ }
65
+ }
66
+
67
+ enforceNodeVersion();
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type { ErrorEvent, EventHint } from "@sentry/node";
3
+
4
+ // sentry.ts reads BUNDLED_DSN at import time; stub it so the module loads
5
+ // without a real DSN (mirrors sentry.test.ts).
6
+ vi.mock("./sentry-dsn.generated.js", () => ({ BUNDLED_DSN: "" }));
7
+
8
+ import { epipeAwareBeforeSend } from "./sentry.js";
9
+
10
+ describe("epipeAwareBeforeSend (HQ-6B)", () => {
11
+ it("drops an EPIPE crash before it can ship a fatal", () => {
12
+ const epipe = Object.assign(new Error("write EPIPE"), { code: "EPIPE" });
13
+ const event = {
14
+ exception: { values: [{ type: "Error", value: "write EPIPE" }] },
15
+ } as ErrorEvent;
16
+ const out = epipeAwareBeforeSend(event, {
17
+ originalException: epipe,
18
+ } as EventHint);
19
+ expect(out).toBeNull();
20
+ });
21
+
22
+ it("forwards a genuine error to the scrubber (still reported)", () => {
23
+ const err = new Error("boom");
24
+ const event = { message: "boom" } as ErrorEvent;
25
+ const out = epipeAwareBeforeSend(event, {
26
+ originalException: err,
27
+ } as EventHint);
28
+ expect(out).not.toBeNull();
29
+ expect(out?.message).toBe("boom");
30
+ });
31
+
32
+ it("forwards when there is no originalException hint", () => {
33
+ const event = { message: "no hint" } as ErrorEvent;
34
+ const out = epipeAwareBeforeSend(event, {} as EventHint);
35
+ expect(out).not.toBeNull();
36
+ });
37
+ });
@@ -0,0 +1,54 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { readFileSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import path from "node:path";
5
+
6
+ // `@sentry/node`'s `init` is a non-configurable export, so it can't be spied
7
+ // in place — replace it via importOriginal spread (every OTHER Sentry export
8
+ // stays real, so initSentry's setUser/startSession remain harmless no-ops with
9
+ // no real SDK init). We only need to inspect the options handed to `init`.
10
+ const { initMock } = vi.hoisted(() => ({ initMock: vi.fn() }));
11
+ vi.mock("@sentry/node", async (importOriginal) => {
12
+ const actual = await importOriginal<typeof import("@sentry/node")>();
13
+ return { ...actual, init: initMock };
14
+ });
15
+ // A DSN must be present for initSentry to reach Sentry.init.
16
+ vi.mock("./sentry-dsn.generated.js", () => ({
17
+ BUNDLED_DSN: "https://examplePublicKey@o0.ingest.sentry.io/0",
18
+ }));
19
+
20
+ import { initSentry } from "./sentry.js";
21
+ import { CLI_VERSION } from "./cli-version.js";
22
+
23
+ const PKG_VERSION = (
24
+ JSON.parse(
25
+ readFileSync(
26
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"),
27
+ "utf-8",
28
+ ),
29
+ ) as { version: string }
30
+ ).version;
31
+
32
+ describe("initSentry — release tag carries the real CLI version (resolve-by-release)", () => {
33
+ afterEach(() => {
34
+ vi.clearAllMocks();
35
+ });
36
+
37
+ // Locks the resolve-by-release path for hq-cli: every event must be stamped
38
+ // with the REAL package version so Sentry's "resolved in next release" works
39
+ // and old-version stragglers (the legacy `hq-cli@0.0.0` events from pre-#8
40
+ // installs) sort as the oldest release and stay suppressed. Regression guard
41
+ // against ever reverting to the `npm_package_version` 0.0.0 pitfall.
42
+ it("stamps release = hq-cli@<package.json version>, never the 0.0.0 placeholder", () => {
43
+ initSentry();
44
+
45
+ expect(initMock).toHaveBeenCalledTimes(1);
46
+ const opts = initMock.mock.calls[0][0] as { release?: string };
47
+
48
+ // CLI_VERSION resolves from package.json at runtime (not npm_package_version).
49
+ expect(CLI_VERSION).toBe(PKG_VERSION);
50
+ expect(CLI_VERSION).not.toBe("0.0.0");
51
+ expect(opts.release).toBe(`hq-cli@${PKG_VERSION}`);
52
+ expect(opts.release).not.toBe("hq-cli@0.0.0");
53
+ });
54
+ });