@indigoai-us/hq-cli 5.59.0 → 5.61.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.
@@ -279,6 +279,110 @@ function describeSecretAclPrincipal(principal: SecretAclPrincipal): string {
279
279
  : principal.granteeId;
280
280
  }
281
281
 
282
+ // secrets-proxy-per-secret-destination US-006: an InjectionRecipe as sent on
283
+ // the create/update POST body. Mirrors hq-pro's `InjectionRecipe`
284
+ // (src/vault-service/handlers/secrets.ts) — kept as a local shape (not
285
+ // imported) since the CLI does not depend on the hq-pro package.
286
+ export interface SecretInjectionRecipe {
287
+ header: string;
288
+ scheme: "raw" | "bearer";
289
+ extraHeaders?: Record<string, string>;
290
+ }
291
+
292
+ // Mirrors hq-pro's server-authoritative KNOWN_DESTINATION_REGISTRY
293
+ // (src/vault-service/handlers/destination-registry.ts) — a KNOWN host's
294
+ // --auth-style is optional because the server resolves the recipe itself.
295
+ // This client-side copy exists purely so an UNKNOWN host with no
296
+ // --auth-style can be rejected immediately with a clear, actionable message
297
+ // instead of a round trip; the server remains the authoritative validator
298
+ // (this list drifting stale merely means one extra CLI round trip, not a
299
+ // security gap — the server still 400s an unrecognized host with no recipe).
300
+ const KNOWN_DESTINATION_HOSTS = new Set([
301
+ "api.anthropic.com",
302
+ "api.openai.com",
303
+ "api.stripe.com",
304
+ ]);
305
+
306
+ // Parses `--auth-style` into the InjectionRecipe shape the server expects.
307
+ // Returns `null` (with a printed error) for an unrecognized value.
308
+ function parseAuthStyle(authStyle: string): SecretInjectionRecipe | null {
309
+ if (authStyle === "bearer") {
310
+ return { header: "authorization", scheme: "bearer" };
311
+ }
312
+ if (authStyle === "x-api-key") {
313
+ return { header: "x-api-key", scheme: "raw" };
314
+ }
315
+ const headerMatch = authStyle.match(/^header:(.+)$/);
316
+ if (headerMatch) {
317
+ const headerName = headerMatch[1].trim();
318
+ if (!headerName) {
319
+ console.error(
320
+ chalk.red(
321
+ `Invalid --auth-style 'header:': must name a header, e.g. header:X-Custom-Key`,
322
+ ),
323
+ );
324
+ return null;
325
+ }
326
+ return { header: headerName, scheme: "raw" };
327
+ }
328
+ console.error(
329
+ chalk.red(
330
+ `Invalid --auth-style '${authStyle}': must be one of bearer, x-api-key, or header:NAME`,
331
+ ),
332
+ );
333
+ return null;
334
+ }
335
+
336
+ // Validates `--destination` is a bare HTTPS scheme+host URL (no path, query,
337
+ // port). Mirrors hq-pro's `validateDestinations` server-side check
338
+ // (src/vault-service/handlers/secrets.ts) so a malformed URL is caught
339
+ // locally with an actionable message rather than a round trip — the server
340
+ // re-validates and remains authoritative.
341
+ function parseDestinationUrl(
342
+ raw: string,
343
+ ): { ok: true; url: string; hostname: string } | { ok: false } {
344
+ let parsed: URL;
345
+ try {
346
+ parsed = new URL(raw);
347
+ } catch {
348
+ console.error(
349
+ chalk.red(`Invalid --destination '${raw}': must be a valid URL`),
350
+ );
351
+ return { ok: false };
352
+ }
353
+ if (parsed.protocol !== "https:") {
354
+ console.error(
355
+ chalk.red(`Invalid --destination '${raw}': must use https://`),
356
+ );
357
+ return { ok: false };
358
+ }
359
+ if (!parsed.hostname) {
360
+ console.error(
361
+ chalk.red(`Invalid --destination '${raw}': missing hostname`),
362
+ );
363
+ return { ok: false };
364
+ }
365
+ if (
366
+ (parsed.pathname !== "" && parsed.pathname !== "/") ||
367
+ parsed.search !== "" ||
368
+ parsed.hash !== ""
369
+ ) {
370
+ console.error(
371
+ chalk.red(
372
+ `Invalid --destination '${raw}': must be a bare scheme+host URL with no path, query, or fragment (e.g. https://api.openai.com)`,
373
+ ),
374
+ );
375
+ return { ok: false };
376
+ }
377
+ if (parsed.port !== "") {
378
+ console.error(
379
+ chalk.red(`Invalid --destination '${raw}': must not specify a port`),
380
+ );
381
+ return { ok: false };
382
+ }
383
+ return { ok: true, url: `https://${parsed.hostname}`, hostname: parsed.hostname };
384
+ }
385
+
282
386
  function normalizeSecretTier(tier?: string): SecretTier {
283
387
  return tier === "sensitive" || tier === "nuclear" ? tier : "standard";
284
388
  }
@@ -369,7 +473,11 @@ export function scrubSandboxOutput(text: string, secretNames: string[] = []): st
369
473
 
370
474
  function renderSandboxJobResult(job: SandboxRunnerJob, secretNames: string[]): void {
371
475
  if (job.output) {
372
- process.stdout.write(scrubSandboxOutput(job.output, secretNames));
476
+ const output = scrubSandboxOutput(job.output, secretNames);
477
+ process.stdout.write(output);
478
+ if (output.length > 0 && !output.endsWith("\n")) {
479
+ process.stdout.write("\n");
480
+ }
373
481
  }
374
482
  }
375
483
 
@@ -568,13 +676,87 @@ export function registerSecretsCommand(program: Command): void {
568
676
  .command("set <name>")
569
677
  .description("Create or update a secret")
570
678
  .option("--from-stdin", "Read secret value from piped stdin")
571
- .action(async (name: string, opts: { fromStdin?: boolean }) => {
679
+ .option(
680
+ "--high-security",
681
+ "Mark the secret high-security: it can never be revealed or injected locally, only used through the HQ secret proxy (requires --destination)",
682
+ )
683
+ .option(
684
+ "--destination <https-url>",
685
+ "Approved scheme+host HTTPS URL the proxy may forward this secret to (e.g. https://api.openai.com); required with --high-security",
686
+ )
687
+ .option(
688
+ "--auth-style <style>",
689
+ "How the proxy attaches the key upstream: bearer | x-api-key | header:NAME. Optional for known destinations (auto-resolved server-side); required for unknown ones",
690
+ )
691
+ .action(async (
692
+ name: string,
693
+ opts: {
694
+ fromStdin?: boolean;
695
+ highSecurity?: boolean;
696
+ destination?: string;
697
+ authStyle?: string;
698
+ },
699
+ ) => {
572
700
  try {
573
701
  if (!SECRET_NAME_PATTERN.test(name)) {
574
702
  console.error(chalk.red(`Invalid secret name '${name}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_API_KEY or DEV/MY_KEY)`));
575
703
  process.exit(1);
576
704
  }
577
705
 
706
+ // secrets-proxy-per-secret-destination US-006: --high-security marks
707
+ // the secret so it can only ever be used through the server-side
708
+ // proxy (never revealed/injected locally — that refusal is the
709
+ // pre-existing consumption-side behavior in `get`/`exec`/`env` above,
710
+ // unchanged by this story). It REQUIRES a --destination: the proxy
711
+ // (hq-pro US-002) fails closed with no destination configured, so
712
+ // catching the missing pin here is a clear, immediate CLI error
713
+ // rather than a deferred proxy-time failure.
714
+ let destinations: string[] | undefined;
715
+ let injection: SecretInjectionRecipe | undefined;
716
+ if (opts.highSecurity) {
717
+ if (!opts.destination) {
718
+ console.error(
719
+ chalk.red(
720
+ "Error: --high-security requires --destination <https-url> (e.g. --destination https://api.openai.com).",
721
+ ),
722
+ );
723
+ process.exit(1);
724
+ }
725
+
726
+ const destResult = parseDestinationUrl(opts.destination);
727
+ if (!destResult.ok) {
728
+ process.exit(1);
729
+ }
730
+ destinations = [destResult.url];
731
+
732
+ if (opts.authStyle) {
733
+ const recipe = parseAuthStyle(opts.authStyle);
734
+ if (!recipe) {
735
+ process.exit(1);
736
+ }
737
+ injection = recipe;
738
+ } else if (!KNOWN_DESTINATION_HOSTS.has(destResult.hostname)) {
739
+ // Unknown host + no explicit recipe: the server would reject this
740
+ // 400 anyway (US-004 registry lookup only, never guesses) — fail
741
+ // fast locally with an actionable message instead of a round trip.
742
+ console.error(
743
+ chalk.red(
744
+ `Error: unknown destination host '${destResult.hostname}' — provide --auth-style <bearer|x-api-key|header:NAME> (known hosts auto-resolve: ${[...KNOWN_DESTINATION_HOSTS].join(", ")}).`,
745
+ ),
746
+ );
747
+ process.exit(1);
748
+ }
749
+ // Known host + no --auth-style: leave `injection` undefined so the
750
+ // server (US-004) auto-resolves the recipe from its registry.
751
+ } else if (opts.destination || opts.authStyle) {
752
+ console.error(
753
+ chalk.red(
754
+ "Error: --destination/--auth-style require --high-security.",
755
+ ),
756
+ );
757
+ process.exit(1);
758
+ }
759
+
578
760
  let value: string;
579
761
  if (opts.fromStdin) {
580
762
  if (process.stdin.isTTY) {
@@ -613,19 +795,35 @@ export function registerSecretsCommand(program: Command): void {
613
795
  token,
614
796
  path: `/secrets/${encodeURIComponent(companyUid)}`,
615
797
  method: "POST",
616
- body: { name, value },
798
+ body: {
799
+ name,
800
+ value,
801
+ // Only present when --high-security was passed — an ordinary
802
+ // `set` with no flags sends exactly `{ name, value }`, byte-for-
803
+ // byte unchanged from before this story.
804
+ ...(opts.highSecurity ? { highSecurity: true } : {}),
805
+ ...(destinations ? { destinations } : {}),
806
+ ...(injection ? { injection } : {}),
807
+ },
617
808
  });
618
809
 
619
810
  if (!res.ok) {
620
- const body = await res.json().catch(() => ({}));
811
+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
621
812
  console.error(
622
- chalk.red(`Failed to set secret: ${(body as Record<string, string>).error ?? res.statusText}`),
813
+ chalk.red(`Failed to set secret: ${extractApiMessage(body, res.statusText)}`),
623
814
  );
624
815
  process.exit(1);
625
816
  }
626
817
 
627
818
  removeCacheEntry(companyUid, name);
628
819
  console.log(chalk.green(formatSecretSaved(name, scopeLabel)));
820
+ if (opts.highSecurity) {
821
+ console.log(
822
+ chalk.dim(
823
+ ` High-security: destination pinned to ${destinations?.[0]}. This value can never be revealed or injected locally — only used through the HQ secret proxy.`,
824
+ ),
825
+ );
826
+ }
629
827
  } catch (err) {
630
828
  console.error(
631
829
  chalk.red("Error:"),
@@ -0,0 +1,32 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ vi.mock("./cli-version.js", () => ({
4
+ CLI_VERSION: "5.60.0",
5
+ CLI_NAME: "@indigoai-us/hq-cli",
6
+ }));
7
+
8
+ vi.mock("./node-preflight.js", () => ({}));
9
+
10
+ afterEach(() => {
11
+ vi.restoreAllMocks();
12
+ vi.resetModules();
13
+ });
14
+
15
+ describe("bin bootstrap", () => {
16
+ it("answers --version without importing the command graph", async () => {
17
+ const originalArgv = process.argv;
18
+ const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
19
+ const runCli = vi.fn();
20
+ vi.doMock("./main.js", () => ({ runCli }));
21
+ process.argv = ["node", "hq", "--version"];
22
+
23
+ try {
24
+ await import("./index.js");
25
+ } finally {
26
+ process.argv = originalArgv;
27
+ }
28
+
29
+ expect(write).toHaveBeenCalledWith("5.60.0\n");
30
+ expect(runCli).not.toHaveBeenCalled();
31
+ });
32
+ });
package/src/index.ts CHANGED
@@ -1,283 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- /**
4
- * HQ CLI - Module management, package management, and cloud sync for HQ
5
- */
6
-
7
3
  // MUST be first: guard the Node version before any dependency that needs a
8
4
  // Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
9
5
  import "./node-preflight.js";
10
- import { Command } from "commander";
11
- import { initSentry, Sentry } from "./sentry.js";
12
- import { registerAddCommand } from "./commands/add.js";
13
- import { registerSyncCommand } from "./commands/sync.js";
14
- import { registerListCommand } from "./commands/list.js";
15
- import { registerUpdateCommand } from "./commands/update.js";
16
- import { registerCloudCommands } from "./commands/cloud.js";
17
- import { registerSyncModeCommand } from "./commands/sync-mode.js";
18
- import { registerSyncNarrowCommand } from "./commands/sync-narrow.js";
19
- import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
20
- import { registerCloudDemoteCommands } from "./commands/cloud-demote.js";
21
- import { registerLoginCommand } from "./commands/login.js";
22
- import { registerLogoutCommand } from "./commands/logout.js";
23
- import { registerWhoamiCommand } from "./commands/whoami.js";
24
- import { registerOnboardCommand } from "./commands/onboard.js";
25
- import { registerPackageInstallCommand } from "./commands/pkg-install.js";
26
- import { registerPackageRemoveCommand } from "./commands/pkg-remove.js";
27
- import { registerPackageUpdateCommand } from "./commands/pkg-update.js";
28
- import { registerPackageListCommand } from "./commands/pkg-list.js";
29
- import { registerPacksCommand } from "./commands/packs.js";
30
- import { registerPublishCommand } from "./commands/publish.js";
31
- import { registerCreatorsCommand } from "./commands/creators.js";
32
- import { registerTeamSyncCommand } from "./commands/team-sync.js";
33
- import { registerAuthCommands } from "./commands/auth.js";
34
- import { registerApiKeysCommand } from "./commands/api-keys.js";
35
- import { registerSecretsCommand } from "./commands/secrets.js";
36
- import { registerRunCommand } from "./commands/run.js";
37
- import { registerGroupsCommand } from "./commands/groups.js";
38
- import { registerGroupGrantsCommand } from "./commands/group-grants.js";
39
- import { registerFilesCommand } from "./commands/files.js";
40
- import { registerFilesBrowseCommands } from "./commands/files-browse.js";
41
- import { registerMembersCommand } from "./commands/members.js";
42
- import { registerPeopleCommand } from "./commands/people.js";
43
- import { registerDmCommand } from "./commands/dm.js";
44
- import { registerChannelsCommand } from "./commands/channels.js";
45
- import { registerFeedbackCommand } from "./commands/feedback.js";
46
- import { registerMeetingsCommand } from "./commands/meetings.js";
47
- import { registerSourcesCommand } from "./commands/sources.js";
48
- import { registerSignalsCommand } from "./commands/signals.js";
49
- import { registerReindexCommand } from "./commands/reindex.js";
50
- import { registerRescueCommand } from "./commands/rescue.js";
51
- import { registerMcpCommand } from "./commands/mcp-status.js";
52
- import { registerCrmCommand } from "./commands/crm.js";
53
- import { registerCompanyCommand } from "./commands/company.js";
54
- import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
55
- import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
56
- import { isEpipe } from "./utils/epipe.js";
57
- import { isInterceptedProcessExit } from "./utils/intercepted-process-exit.js";
58
- import {
59
- maybeWarnNewVersion,
60
- refreshVersionCache,
61
- } from "./utils/version-check.js";
62
- import {
63
- enforceVersionGate,
64
- shouldSkipGate,
65
- } from "./utils/version-gate.js";
66
6
  import { CLI_VERSION } from "./cli-version.js";
67
7
 
68
- // Swallow EPIPE when a downstream reader (e.g. `source <(…)`, `| head`) closes
69
- // the pipe early. This covers the ASYNC path — an 'error' event emitted on the
70
- // stream. The SYNCHRONOUS path (a `write EPIPE` thrown straight out of
71
- // console.log inside a command) is handled in the top-level catch below; both
72
- // share `isEpipe` (HQ-6B).
73
- const onPipeError = (err: NodeJS.ErrnoException): void => {
74
- if (isEpipe(err)) {
75
- process.exit(0);
76
- }
77
- throw err;
78
- };
79
- process.stdout.on("error", onPipeError);
80
- process.stderr.on("error", onPipeError);
81
-
82
- initSentry();
83
- maybeWarnNewVersion();
84
-
85
- const program = new Command();
86
-
87
- program
88
- .name("hq")
89
- .description("HQ management CLI — modules, packages, and cloud sync")
90
- .version(CLI_VERSION);
91
-
92
- // Module management subcommand group
93
- const modulesCmd = program
94
- .command("modules")
95
- .description("Module management commands");
96
-
97
- registerAddCommand(modulesCmd);
98
- registerSyncCommand(modulesCmd);
99
- registerListCommand(modulesCmd);
100
- registerUpdateCommand(modulesCmd);
101
-
102
- // Package management subcommand group
103
- const packagesCmd = program
104
- .command("packages")
105
- .description("Package management commands");
106
-
107
- registerPackageInstallCommand(packagesCmd);
108
- registerPackageRemoveCommand(packagesCmd);
109
- registerPackageUpdateCommand(packagesCmd);
110
- registerPackageListCommand(packagesCmd);
111
-
112
- // Content-pack lifecycle (core/packages/hq-pack-*). Distinct from the registry
113
- // `packages` system above. Available as both `hq packages packs …` (grouped)
114
- // and `hq packs …` (top-level convenience).
115
- registerPacksCommand(packagesCmd);
116
- registerPacksCommand(program);
117
-
118
- // Top-level shortcuts for package commands
119
- // "hq install <slug>" = "hq packages install <slug>"
120
- // "hq remove <slug>" = "hq packages remove <slug>"
121
- registerPackageInstallCommand(program);
122
- registerPackageRemoveCommand(program);
123
-
124
- // Marketplace publish (top-level — packer + authenticated upload, US-004)
125
- // "hq publish <skill-or-worker-path>" packages and submits a pack to the
126
- // marketplace via POST /v1/listings.
127
- registerPublishCommand(program);
128
- // `hq creators apply` — request verified-creator access (required to publish).
129
- registerCreatorsCommand(program);
130
-
131
- // Cloud sync subcommand group
132
- const syncCmd = program
133
- .command("sync")
134
- .description("Cloud sync commands — sync HQ to S3 for mobile access");
135
-
136
- registerCloudCommands(syncCmd);
137
- registerSyncModeCommand(syncCmd);
138
- registerSyncNarrowCommand(syncCmd);
139
-
140
- // Cloud provisioning subcommand group (entity + bucket + initial sync)
141
- // Distinct from `hq sync` which assumes provisioning has already happened.
142
- const cloudCmd = program
143
- .command("cloud")
144
- .description(
145
- "Cloud commands — provision entities and manage cloud-backed companies",
146
- );
147
-
148
- registerCloudProvisionCommands(cloudCmd);
149
- registerCloudDemoteCommands(cloudCmd);
150
-
151
- // Team commands (top-level)
152
- registerTeamSyncCommand(program);
153
-
154
- // Auth commands (top-level — Cognito OAuth)
155
- registerLoginCommand(program);
156
- registerLogoutCommand(program);
157
- registerWhoamiCommand(program);
158
- registerAuthCommands(program);
159
-
160
- // Secrets management (subcommand group — hq secrets set|get|list|delete|exec|generate-link|cache)
161
- registerSecretsCommand(program);
162
-
163
- // API key management (subcommand group — hq api-keys create|list|revoke)
164
- registerApiKeysCommand(program);
165
-
166
- // Schema-driven dev runner — hq run [options] -- <cmd>
167
- registerRunCommand(program);
168
-
169
- // Groups management (subcommand group — hq groups create|delete|add|remove|list|members)
170
- registerGroupsCommand(program);
171
-
172
- // Cross-company group grants (subcommand group —
173
- // hq group-grants grant|revoke|outbound|inbound)
174
- registerGroupGrantsCommand(program);
175
-
176
- // Files ACL management (subcommand group — hq files share|unshare|acl)
177
- // `registerFilesCommand` returns the `files` group so we can attach the
178
- // browse-vs-sync subcommands (`hq files browse`/`cat`) onto the same group.
179
- const filesCmd = registerFilesCommand(program);
180
- registerFilesBrowseCommands(filesCmd);
181
-
182
- // Membership management (subcommand group — hq members invite|list|revoke)
183
- registerMembersCommand(program);
184
- // People directory (subcommand group — hq people list|search|resolve), reading
185
- // the local companies/<co>/people store scoped to one company.
186
- registerPeopleCommand(program);
187
- registerDmCommand(program);
188
- registerChannelsCommand(program);
189
-
190
- // Onboarding (top-level — Cognito + vault-service provisioning)
191
- registerOnboardCommand(program);
192
-
193
- // Feedback (subcommand group — hq feedback bug|feature)
194
- registerFeedbackCommand(program);
195
-
196
- // Meetings (subcommand group — hq meetings list|get|search|transcript|notes)
197
- registerMeetingsCommand(program);
198
-
199
- // Sources read surface (subcommand group — hq sources list|get|channels|entities)
200
- registerSourcesCommand(program);
201
-
202
- // Signals read surface (subcommand group — hq signals list|get|types|entities)
203
- registerSignalsCommand(program);
204
-
205
- // Skill/personal-overlay mirroring + workers-registry regen. Invoked by the
206
- // hq-core reindex hook shim (Stop / PostToolUse) and by sync()/rescue() after
207
- // they change on-disk sources. Keeps a `master-sync` alias for one release.
208
- // Implementation lives in @indigoai-us/hq-cloud.
209
- registerReindexCommand(program);
210
-
211
- // Drift-preserving HQ-core re-sync (top-level — `hq rescue`). CLI sibling of
212
- // the HQ Sync app's "Update / Restore" pill; drives the same replace-rescue.sh
213
- // shipped from @indigoai-us/hq-cloud.
214
- registerRescueCommand(program);
215
-
216
- // MCP pack observability (subcommand group — `hq mcp status`). Read-only
217
- // provenance-based status across BOTH Claude + Codex runtimes (reads `_hqPack`
218
- // off the configs, NOT linkStatus), with secret-redacted output + `--json`.
219
- registerMcpCommand(program);
220
-
221
- // Native CRM entity upsert (subcommand group — `hq crm entity upsert`). Wraps
222
- // POST /crm/entities (the ontology write gate) so an authenticated company
223
- // member can create/update canonical CRM entities in the company vault.
224
- registerCrmCommand(program);
8
+ function isVersionRequest(argv: readonly string[]): boolean {
9
+ const args = argv.slice(2);
10
+ return args.length === 1 && (args[0] === "--version" || args[0] === "-V" || args[0] === "-v");
11
+ }
225
12
 
226
- // Company settings (subcommand group — `hq company settings set`). Owner-only
227
- // toggles for crmEnabled / ontologyEnabled via PUT /company-settings.
228
- registerCompanyCommand(program);
13
+ if (isVersionRequest(process.argv)) {
14
+ process.stdout.write(`${CLI_VERSION}\n`);
15
+ } else {
16
+ const { runCli } = await import("./main.js");
17
+ await runCli();
18
+ }
229
19
 
230
- (async () => {
231
- try {
232
- Sentry.addBreadcrumb({
233
- category: "command",
234
- message: sanitizeArgv(process.argv.slice(2)).join(" "),
235
- level: "info",
236
- });
237
- // Hard version gate: ask hq-pro whether this CLI is below the floor and
238
- // auto-update if so (exits the process on update). Skipped for inspection
239
- // flags (`--version`, `--help`) so users debugging a broken install can
240
- // still introspect what they have. Silent on any failure — never blocks
241
- // the CLI on a flaky network or hq-pro hiccup. See `utils/version-gate.ts`.
242
- if (!shouldSkipGate(process.argv)) {
243
- await enforceVersionGate();
244
- }
245
- await program.parseAsync();
246
- } catch (err) {
247
- // A broken pipe (EPIPE) means the reader of `hq`'s output closed it early
248
- // (`hq … | head`, `source <(hq …)`, a parent that exited). That is normal
249
- // Unix behavior with no user-facing degradation — exit cleanly (0) and
250
- // skip Sentry capture instead of shipping a fatal (HQ-6B). A synchronous
251
- // `write EPIPE` thrown out of console.log lands here rather than on the
252
- // stream 'error' listener above.
253
- if (isEpipe(err)) {
254
- process.exitCode = 0;
255
- } else if (isInterceptedProcessExit(err)) {
256
- // A security/audit FUZZ harness replaced `process.exit` with a throw so it
257
- // can keep exercising the binary. Commander calling `process.exit` for
258
- // normal CLI control flow (e.g. an unknown command → exit 1) then surfaces
259
- // here as that synthetic marker. It is a test-harness artifact, NOT an
260
- // hq-cli defect — a real user's `process.exit` just exits, so nothing is
261
- // thrown or captured. Skip Sentry capture (no signal, no user-facing
262
- // degradation) and preserve the intended non-zero exit (HQ-CLI-3).
263
- process.exitCode = 1;
264
- } else {
265
- // A full disk / exhausted quota / read-only filesystem is the user's
266
- // machine, not an HQ code defect. Surface a clear, actionable message and
267
- // skip Sentry capture so one full disk doesn't flood the tracker with
268
- // identical, unfixable crash reports (HQ-CLI-2). Genuine errors still go
269
- // to Sentry and still exit 1.
270
- const envMsg = environmentalFsErrorMessage(err);
271
- if (envMsg) {
272
- process.stderr.write(`hq: ${envMsg}\n`);
273
- } else {
274
- Sentry.captureException(err);
275
- }
276
- process.exitCode = 1;
277
- }
278
- } finally {
279
- // Release health: finalize the per-run session before the flush.
280
- Sentry.endSession();
281
- await Promise.allSettled([refreshVersionCache(), Sentry.flush(2000)]);
282
- }
283
- })();
20
+ export const __test__ = { isVersionRequest };