@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.
package/dist/main.js ADDED
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * HQ CLI - Module management, package management, and cloud sync for HQ
4
+ */
5
+ // MUST be first: guard the Node version before any dependency that needs a
6
+ // Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
7
+
8
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a2c1badb-d418-557d-a0f4-0e3defd13913")}catch(e){}}();
9
+ 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 { maybeWarnNewVersion, refreshVersionCache, } from "./utils/version-check.js";
59
+ import { enforceVersionGate, shouldSkipGate, } from "./utils/version-gate.js";
60
+ import { CLI_VERSION } from "./cli-version.js";
61
+ // Swallow EPIPE when a downstream reader (e.g. `source <(…)`, `| head`) closes
62
+ // the pipe early. This covers the ASYNC path — an 'error' event emitted on the
63
+ // stream. The SYNCHRONOUS path (a `write EPIPE` thrown straight out of
64
+ // console.log inside a command) is handled in the top-level catch below; both
65
+ // share `isEpipe` (HQ-6B).
66
+ const onPipeError = (err) => {
67
+ if (isEpipe(err)) {
68
+ process.exit(0);
69
+ }
70
+ throw err;
71
+ };
72
+ process.stdout.on("error", onPipeError);
73
+ process.stderr.on("error", onPipeError);
74
+ initSentry();
75
+ maybeWarnNewVersion();
76
+ const program = new Command();
77
+ program
78
+ .name("hq")
79
+ .description("HQ management CLI — modules, packages, and cloud sync")
80
+ .version(CLI_VERSION);
81
+ // Module management subcommand group
82
+ const modulesCmd = program
83
+ .command("modules")
84
+ .description("Module management commands");
85
+ registerAddCommand(modulesCmd);
86
+ registerSyncCommand(modulesCmd);
87
+ registerListCommand(modulesCmd);
88
+ registerUpdateCommand(modulesCmd);
89
+ // Package management subcommand group
90
+ const packagesCmd = program
91
+ .command("packages")
92
+ .description("Package management commands");
93
+ registerPackageInstallCommand(packagesCmd);
94
+ registerPackageRemoveCommand(packagesCmd);
95
+ registerPackageUpdateCommand(packagesCmd);
96
+ registerPackageListCommand(packagesCmd);
97
+ // Content-pack lifecycle (core/packages/hq-pack-*). Distinct from the registry
98
+ // `packages` system above. Available as both `hq packages packs …` (grouped)
99
+ // and `hq packs …` (top-level convenience).
100
+ registerPacksCommand(packagesCmd);
101
+ registerPacksCommand(program);
102
+ // Top-level shortcuts for package commands
103
+ // "hq install <slug>" = "hq packages install <slug>"
104
+ // "hq remove <slug>" = "hq packages remove <slug>"
105
+ registerPackageInstallCommand(program);
106
+ registerPackageRemoveCommand(program);
107
+ // Marketplace publish (top-level — packer + authenticated upload, US-004)
108
+ // "hq publish <skill-or-worker-path>" packages and submits a pack to the
109
+ // marketplace via POST /v1/listings.
110
+ registerPublishCommand(program);
111
+ // `hq creators apply` — request verified-creator access (required to publish).
112
+ registerCreatorsCommand(program);
113
+ // Cloud sync subcommand group
114
+ const syncCmd = program
115
+ .command("sync")
116
+ .description("Cloud sync commands — sync HQ to S3 for mobile access");
117
+ registerCloudCommands(syncCmd);
118
+ registerSyncModeCommand(syncCmd);
119
+ registerSyncNarrowCommand(syncCmd);
120
+ // Cloud provisioning subcommand group (entity + bucket + initial sync)
121
+ // Distinct from `hq sync` which assumes provisioning has already happened.
122
+ const cloudCmd = program
123
+ .command("cloud")
124
+ .description("Cloud commands — provision entities and manage cloud-backed companies");
125
+ registerCloudProvisionCommands(cloudCmd);
126
+ registerCloudDemoteCommands(cloudCmd);
127
+ // Team commands (top-level)
128
+ registerTeamSyncCommand(program);
129
+ // Auth commands (top-level — Cognito OAuth)
130
+ registerLoginCommand(program);
131
+ registerLogoutCommand(program);
132
+ registerWhoamiCommand(program);
133
+ registerAuthCommands(program);
134
+ // Secrets management (subcommand group — hq secrets set|get|list|delete|exec|generate-link|cache)
135
+ registerSecretsCommand(program);
136
+ // API key management (subcommand group — hq api-keys create|list|revoke)
137
+ registerApiKeysCommand(program);
138
+ // Schema-driven dev runner — hq run [options] -- <cmd>
139
+ registerRunCommand(program);
140
+ // Groups management (subcommand group — hq groups create|delete|add|remove|list|members)
141
+ registerGroupsCommand(program);
142
+ // Cross-company group grants (subcommand group —
143
+ // hq group-grants grant|revoke|outbound|inbound)
144
+ registerGroupGrantsCommand(program);
145
+ // Files ACL management (subcommand group — hq files share|unshare|acl)
146
+ // `registerFilesCommand` returns the `files` group so we can attach the
147
+ // browse-vs-sync subcommands (`hq files browse`/`cat`) onto the same group.
148
+ const filesCmd = registerFilesCommand(program);
149
+ registerFilesBrowseCommands(filesCmd);
150
+ // Membership management (subcommand group — hq members invite|list|revoke)
151
+ registerMembersCommand(program);
152
+ // People directory (subcommand group — hq people list|search|resolve), reading
153
+ // the local companies/<co>/people store scoped to one company.
154
+ registerPeopleCommand(program);
155
+ registerDmCommand(program);
156
+ registerChannelsCommand(program);
157
+ // Onboarding (top-level — Cognito + vault-service provisioning)
158
+ registerOnboardCommand(program);
159
+ // Feedback (subcommand group — hq feedback bug|feature)
160
+ registerFeedbackCommand(program);
161
+ // Meetings (subcommand group — hq meetings list|get|search|transcript|notes)
162
+ registerMeetingsCommand(program);
163
+ // Sources read surface (subcommand group — hq sources list|get|channels|entities)
164
+ registerSourcesCommand(program);
165
+ // Signals read surface (subcommand group — hq signals list|get|types|entities)
166
+ registerSignalsCommand(program);
167
+ // Skill/personal-overlay mirroring + workers-registry regen. Invoked by the
168
+ // hq-core reindex hook shim (Stop / PostToolUse) and by sync()/rescue() after
169
+ // they change on-disk sources. Keeps a `master-sync` alias for one release.
170
+ // Implementation lives in @indigoai-us/hq-cloud.
171
+ registerReindexCommand(program);
172
+ // Drift-preserving HQ-core re-sync (top-level — `hq rescue`). CLI sibling of
173
+ // the HQ Sync app's "Update / Restore" pill; drives the same replace-rescue.sh
174
+ // shipped from @indigoai-us/hq-cloud.
175
+ registerRescueCommand(program);
176
+ // MCP pack observability (subcommand group — `hq mcp status`). Read-only
177
+ // provenance-based status across BOTH Claude + Codex runtimes (reads `_hqPack`
178
+ // off the configs, NOT linkStatus), with secret-redacted output + `--json`.
179
+ registerMcpCommand(program);
180
+ // Native CRM entity upsert (subcommand group — `hq crm entity upsert`). Wraps
181
+ // POST /crm/entities (the ontology write gate) so an authenticated company
182
+ // member can create/update canonical CRM entities in the company vault.
183
+ registerCrmCommand(program);
184
+ // Company settings (subcommand group — `hq company settings set`). Owner-only
185
+ // toggles for crmEnabled / ontologyEnabled via PUT /company-settings.
186
+ registerCompanyCommand(program);
187
+ export async function runCli() {
188
+ try {
189
+ Sentry.addBreadcrumb({
190
+ category: "command",
191
+ message: sanitizeArgv(process.argv.slice(2)).join(" "),
192
+ level: "info",
193
+ });
194
+ // Hard version gate: ask hq-pro whether this CLI is below the floor and
195
+ // auto-update if so (exits the process on update). Skipped for inspection
196
+ // flags (`--version`, `--help`) so users debugging a broken install can
197
+ // still introspect what they have. Silent on any failure — never blocks
198
+ // the CLI on a flaky network or hq-pro hiccup. See `utils/version-gate.ts`.
199
+ if (!shouldSkipGate(process.argv)) {
200
+ await enforceVersionGate();
201
+ }
202
+ await program.parseAsync();
203
+ }
204
+ catch (err) {
205
+ // A broken pipe (EPIPE) means the reader of `hq`'s output closed it early
206
+ // (`hq … | head`, `source <(hq …)`, a parent that exited). That is normal
207
+ // Unix behavior with no user-facing degradation — exit cleanly (0) and
208
+ // skip Sentry capture instead of shipping a fatal (HQ-6B). A synchronous
209
+ // `write EPIPE` thrown out of console.log lands here rather than on the
210
+ // stream 'error' listener above.
211
+ if (isEpipe(err)) {
212
+ process.exitCode = 0;
213
+ }
214
+ else if (isInterceptedProcessExit(err)) {
215
+ // A security/audit FUZZ harness replaced `process.exit` with a throw so it
216
+ // can keep exercising the binary. Commander calling `process.exit` for
217
+ // normal CLI control flow (e.g. an unknown command → exit 1) then surfaces
218
+ // here as that synthetic marker. It is a test-harness artifact, NOT an
219
+ // hq-cli defect — a real user's `process.exit` just exits, so nothing is
220
+ // thrown or captured. Skip Sentry capture (no signal, no user-facing
221
+ // degradation) and preserve the intended non-zero exit (HQ-CLI-3).
222
+ process.exitCode = 1;
223
+ }
224
+ else {
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`);
233
+ }
234
+ else {
235
+ Sentry.captureException(err);
236
+ }
237
+ process.exitCode = 1;
238
+ }
239
+ }
240
+ finally {
241
+ // Release health: finalize the per-run session before the flush.
242
+ Sentry.endSession();
243
+ await Promise.allSettled([refreshVersionCache(), Sentry.flush(2000)]);
244
+ }
245
+ }
246
+ //# sourceMappingURL=main.js.map
247
+ //# debugId=a2c1badb-d418-557d-a0f4-0e3defd13913
@@ -18,15 +18,28 @@ export interface SandboxRunnerJob {
18
18
  export interface SandboxRunnerClientOptions {
19
19
  baseUrl?: string;
20
20
  fetchImpl?: typeof fetch;
21
+ retry?: SandboxRunnerRetryOptions;
22
+ sleep?: (ms: number) => Promise<void>;
21
23
  }
22
24
  export interface SandboxRunnerPollOptions {
23
25
  intervalMs?: number;
24
26
  maxPolls?: number;
25
27
  }
28
+ export interface SandboxRunnerRetryOptions {
29
+ maxAttempts?: number;
30
+ maxElapsedMs?: number;
31
+ baseDelayMs?: number;
32
+ maxDelayMs?: number;
33
+ }
26
34
  export declare class SandboxRunnerClient {
27
35
  private readonly baseUrl;
28
36
  private readonly fetchImpl;
37
+ private readonly retry;
38
+ private readonly sleep;
29
39
  constructor(options?: SandboxRunnerClientOptions);
40
+ private fetchWithRetry;
41
+ private shouldRetry;
42
+ private nextDelayMs;
30
43
  startJob(token: string, request: SandboxRunnerStartRequest): Promise<SandboxRunnerStartResponse>;
31
44
  getJob(token: string, jobId: string): Promise<SandboxRunnerJob>;
32
45
  pollJob(token: string, jobId: string, options?: SandboxRunnerPollOptions): Promise<SandboxRunnerJob>;
@@ -1,6 +1,13 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3cbec729-3b2b-5d53-9e90-5680dd725b7d")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e77a0f25-ac1a-574f-a1e4-985c6b3306d7")}catch(e){}}();
3
3
  const DEFAULT_SANDBOX_RUNNER_URL = "https://hqapi.getindigo.ai/sandbox";
4
+ const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
5
+ const DEFAULT_RETRY_OPTIONS = {
6
+ maxAttempts: 8,
7
+ maxElapsedMs: 90_000,
8
+ baseDelayMs: 500,
9
+ maxDelayMs: 5_000,
10
+ };
4
11
  function normalizeBaseUrl(baseUrl) {
5
12
  return baseUrl.replace(/\/+$/, "");
6
13
  }
@@ -40,15 +47,85 @@ function delay(ms) {
40
47
  return Promise.resolve();
41
48
  return new Promise((resolve) => setTimeout(resolve, ms));
42
49
  }
50
+ function getErrorMessage(error) {
51
+ if (error instanceof Error) {
52
+ return error.message;
53
+ }
54
+ if (typeof error === "string") {
55
+ return error;
56
+ }
57
+ return String(error);
58
+ }
59
+ function parseRetryAfterMs(value) {
60
+ if (!value)
61
+ return undefined;
62
+ const seconds = Number(value);
63
+ if (Number.isFinite(seconds) && seconds >= 0) {
64
+ return seconds * 1000;
65
+ }
66
+ const dateMs = Date.parse(value);
67
+ if (!Number.isNaN(dateMs)) {
68
+ return Math.max(0, dateMs - Date.now());
69
+ }
70
+ return undefined;
71
+ }
43
72
  export class SandboxRunnerClient {
44
73
  baseUrl;
45
74
  fetchImpl;
75
+ retry;
76
+ sleep;
46
77
  constructor(options = {}) {
47
78
  this.baseUrl = normalizeBaseUrl(options.baseUrl ?? getSandboxRunnerBaseUrl());
48
79
  this.fetchImpl = options.fetchImpl ?? fetch;
80
+ this.retry = { ...DEFAULT_RETRY_OPTIONS, ...options.retry };
81
+ this.sleep = options.sleep ?? delay;
82
+ }
83
+ async fetchWithRetry(url, init) {
84
+ const startedAt = Date.now();
85
+ let lastError = "unknown error";
86
+ let attempts = 0;
87
+ for (let attempt = 1; attempt <= this.retry.maxAttempts; attempt += 1) {
88
+ attempts = attempt;
89
+ try {
90
+ const res = await this.fetchImpl(url, init);
91
+ if (!RETRYABLE_STATUS_CODES.has(res.status)) {
92
+ return res;
93
+ }
94
+ lastError = `HTTP ${res.status} ${res.statusText}`.trim();
95
+ if (!this.shouldRetry(attempt, startedAt)) {
96
+ break;
97
+ }
98
+ await this.sleep(this.nextDelayMs(attempt, res));
99
+ }
100
+ catch (error) {
101
+ lastError = getErrorMessage(error);
102
+ if (!this.shouldRetry(attempt, startedAt)) {
103
+ break;
104
+ }
105
+ await this.sleep(this.nextDelayMs(attempt));
106
+ }
107
+ }
108
+ throw new Error(`Sandbox Runner did not respond after ${attempts} attempts ` +
109
+ `(cold start or transient network); last error: ${lastError}`);
110
+ }
111
+ shouldRetry(attempt, startedAt) {
112
+ if (attempt >= this.retry.maxAttempts) {
113
+ return false;
114
+ }
115
+ return Date.now() - startedAt < this.retry.maxElapsedMs;
116
+ }
117
+ nextDelayMs(attempt, res) {
118
+ const retryAfterMs = parseRetryAfterMs(res?.headers.get("Retry-After") ?? null);
119
+ if (retryAfterMs !== undefined) {
120
+ return Math.min(retryAfterMs, this.retry.maxDelayMs);
121
+ }
122
+ const exponential = this.retry.baseDelayMs * 2 ** (attempt - 1);
123
+ const capped = Math.min(exponential, this.retry.maxDelayMs);
124
+ const jitter = Math.floor(Math.random() * Math.max(1, capped * 0.25));
125
+ return Math.min(capped + jitter, this.retry.maxDelayMs);
49
126
  }
50
127
  async startJob(token, request) {
51
- const res = await this.fetchImpl(`${this.baseUrl}/jobs`, {
128
+ const res = await this.fetchWithRetry(`${this.baseUrl}/jobs`, {
52
129
  method: "POST",
53
130
  headers: {
54
131
  Authorization: `Bearer ${token}`,
@@ -75,7 +152,7 @@ export class SandboxRunnerClient {
75
152
  };
76
153
  }
77
154
  async getJob(token, jobId) {
78
- const res = await this.fetchImpl(`${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`, {
155
+ const res = await this.fetchWithRetry(`${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`, {
79
156
  headers: { Authorization: `Bearer ${token}` },
80
157
  });
81
158
  const body = await parseJsonResponse(res);
@@ -97,10 +174,10 @@ export class SandboxRunnerClient {
97
174
  if (job.status === "succeeded" || job.status === "failed") {
98
175
  return job;
99
176
  }
100
- await delay(intervalMs);
177
+ await this.sleep(intervalMs);
101
178
  }
102
179
  throw new Error(`Sandbox Runner job '${jobId}' did not finish before the poll limit.`);
103
180
  }
104
181
  }
105
182
  //# sourceMappingURL=sandbox-runner-client.js.map
106
- //# debugId=3cbec729-3b2b-5d53-9e90-5680dd725b7d
183
+ //# debugId=e77a0f25-ac1a-574f-a1e4-985c6b3306d7
@@ -1,3 +1,9 @@
1
+ declare function isKnownNoninteractiveStatusProbe(argv?: readonly string[]): boolean;
1
2
  export declare function maybeWarnNewVersion(): void;
2
3
  export declare function refreshVersionCache(): Promise<void>;
4
+ export declare const __test__: {
5
+ CACHE_TTL_MS: number;
6
+ isKnownNoninteractiveStatusProbe: typeof isKnownNoninteractiveStatusProbe;
7
+ };
8
+ export {};
3
9
  //# sourceMappingURL=version-check.d.ts.map
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="99545a82-414c-5fed-a478-ea8e63009643")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f7058fc6-251e-5e11-af6c-de15f6e256f3")}catch(e){}}();
3
3
  import * as fs from "fs";
4
4
  import * as os from "os";
5
5
  import * as path from "path";
@@ -9,10 +9,15 @@ import { CLI_VERSION } from "../cli-version.js";
9
9
  const PACKAGE_NAME = "@indigoai-us/hq-cli";
10
10
  const REGISTRY_URL = `https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}/latest`;
11
11
  const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
12
+ const CACHE_TTL_JITTER_MS = 60 * 60 * 1000;
12
13
  const FETCH_TIMEOUT_MS = 3_000;
14
+ const REFRESH_LOCK_STALE_MS = 10 * 60 * 1000;
13
15
  function cachePath() {
14
16
  return path.join(os.homedir(), ".hq", "version-check.json");
15
17
  }
18
+ function lockPath() {
19
+ return path.join(os.homedir(), ".hq", "version-check.lock");
20
+ }
16
21
  function isOptedOut() {
17
22
  return process.env.HQ_NO_UPDATE_CHECK === "1";
18
23
  }
@@ -40,6 +45,59 @@ function writeCache(entry) {
40
45
  // best-effort; never break the CLI on cache write failure
41
46
  }
42
47
  }
48
+ function freshEnough(entry, now = Date.now()) {
49
+ const jitter = Math.floor(Math.random() * CACHE_TTL_JITTER_MS);
50
+ return now - entry.fetchedAt <= CACHE_TTL_MS - jitter;
51
+ }
52
+ function isKnownNoninteractiveStatusProbe(argv = process.argv) {
53
+ const args = argv.slice(2);
54
+ const positional = args.filter((arg) => !arg.startsWith("-"));
55
+ const json = args.includes("--json") || !process.stdout.isTTY;
56
+ if (!json)
57
+ return false;
58
+ if (positional[0] === "mcp" && positional[1] === "status")
59
+ return true;
60
+ if (positional[0] === "packs" && (positional[1] === "list" || positional[1] === "ls"))
61
+ return true;
62
+ if (positional[0] === "packages" &&
63
+ positional[1] === "packs" &&
64
+ (positional[2] === "list" || positional[2] === "ls")) {
65
+ return true;
66
+ }
67
+ if ((positional[0] === "sources" || positional[0] === "signals") && positional[1] === "list") {
68
+ return true;
69
+ }
70
+ return false;
71
+ }
72
+ function acquireRefreshLock(now = Date.now()) {
73
+ const dir = lockPath();
74
+ try {
75
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
76
+ fs.mkdirSync(dir);
77
+ fs.writeFileSync(path.join(dir, "owner"), `${process.pid}\n${now}\n`);
78
+ return () => {
79
+ try {
80
+ fs.rmSync(dir, { recursive: true, force: true });
81
+ }
82
+ catch {
83
+ // best-effort lock cleanup
84
+ }
85
+ };
86
+ }
87
+ catch {
88
+ try {
89
+ const stat = fs.statSync(dir);
90
+ if (now - stat.mtimeMs > REFRESH_LOCK_STALE_MS) {
91
+ fs.rmSync(dir, { recursive: true, force: true });
92
+ return acquireRefreshLock(now);
93
+ }
94
+ }
95
+ catch {
96
+ // ignore lock inspection failures
97
+ }
98
+ return null;
99
+ }
100
+ }
43
101
  export function maybeWarnNewVersion() {
44
102
  if (isOptedOut())
45
103
  return;
@@ -60,7 +118,18 @@ export function maybeWarnNewVersion() {
60
118
  export async function refreshVersionCache() {
61
119
  if (isOptedOut())
62
120
  return;
121
+ if (isKnownNoninteractiveStatusProbe())
122
+ return;
123
+ const existing = readCache();
124
+ if (existing && freshEnough(existing))
125
+ return;
126
+ const releaseLock = acquireRefreshLock();
127
+ if (!releaseLock)
128
+ return;
63
129
  try {
130
+ const lockedExisting = readCache();
131
+ if (lockedExisting && freshEnough(lockedExisting))
132
+ return;
64
133
  const res = await fetch(REGISTRY_URL, {
65
134
  headers: { Accept: "application/json" },
66
135
  signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
@@ -75,6 +144,13 @@ export async function refreshVersionCache() {
75
144
  catch {
76
145
  // best-effort; offline / registry down / timeout — silent
77
146
  }
147
+ finally {
148
+ releaseLock();
149
+ }
78
150
  }
151
+ export const __test__ = {
152
+ CACHE_TTL_MS,
153
+ isKnownNoninteractiveStatusProbe,
154
+ };
79
155
  //# sourceMappingURL=version-check.js.map
80
- //# debugId=99545a82-414c-5fed-a478-ea8e63009643
156
+ //# debugId=f7058fc6-251e-5e11-af6c-de15f6e256f3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.59.0",
3
+ "version": "5.61.0",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -45,6 +45,7 @@ beforeEach(() => {
45
45
 
46
46
  afterEach(() => {
47
47
  vi.restoreAllMocks();
48
+ vi.unstubAllGlobals();
48
49
  });
49
50
 
50
51
  function buildProgram(): Command {
@@ -298,7 +299,7 @@ describe("meetings set-company", () => {
298
299
  "acme",
299
300
  ]);
300
301
 
301
- const output = logSpy.mock.calls.map(([line]) => String(line)).join("\n");
302
+ const output = logSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
302
303
  expect(output).not.toContain("Applied to 1 meetings");
303
304
  expect(output).not.toContain("Refiled 0 transcripts");
304
305
  expect(output).not.toContain("Future occurrences of this recurring series will inherit this attribution.");
@@ -345,8 +346,121 @@ describe("meetings list — null-safe rendering", () => {
345
346
  program.parseAsync(["node", "hq", "meetings", "list", "--company", "indigo"]),
346
347
  ).resolves.toBeDefined();
347
348
 
348
- const printed = logSpy.mock.calls.map(([line]) => String(line)).join("\n");
349
+ const printed = logSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
349
350
  expect(printed).toContain("Meetings (2)");
350
351
  expect(printed).toContain("(untitled)");
351
352
  });
352
353
  });
354
+
355
+ describe("meetings — markdown shape rendering", () => {
356
+ const markdownMeetingId = "589bfd78-aaaa-bbbb-cccc-1234567890ab";
357
+ const markdownUrl = "https://example.test/meeting.md";
358
+
359
+ function markdownDetail(signals: Record<string, unknown> = {}) {
360
+ return {
361
+ meetingId: markdownMeetingId,
362
+ sourceShape: "markdown",
363
+ source: {
364
+ path: "meetings/meeting.md",
365
+ presigned_url: markdownUrl,
366
+ frontmatter: {
367
+ title: "Markdown Standup",
368
+ channel: "eng",
369
+ origin: "recall",
370
+ company_id: "cmp_indigo",
371
+ meeting_url: "https://meet.example.test/standup",
372
+ meeting_platform: "google_meet",
373
+ calendar_event_id: null,
374
+ scheduled_start_time: "2026-02-03T15:30:00Z",
375
+ created_at: "2026-02-03T15:00:00Z",
376
+ updated_at: "2026-02-03T16:00:00Z",
377
+ ingested_at: "2026-02-03T16:05:00Z",
378
+ recall_bot_id: null,
379
+ bot_status: "done",
380
+ auto_scheduled: true,
381
+ },
382
+ },
383
+ signals,
384
+ };
385
+ }
386
+
387
+ it("lists markdown meetings without invalid legacy field output", async () => {
388
+ vi.mocked(vaultApiFetch).mockResolvedValueOnce(
389
+ jsonRes({
390
+ meetings: [
391
+ {
392
+ meetingId: markdownMeetingId,
393
+ sourceShape: "markdown",
394
+ title: "Markdown Standup",
395
+ startTime: "2026-02-03T15:30:00Z",
396
+ channel: "eng",
397
+ ingested_at: "2026-02-03T16:05:00Z",
398
+ hasSignals: true,
399
+ companyId: "cmp_indigo",
400
+ attributed: true,
401
+ },
402
+ ],
403
+ }),
404
+ );
405
+
406
+ const program = buildProgram();
407
+ await program.parseAsync(["node", "hq", "meetings", "list"]);
408
+
409
+ const output = logSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
410
+ expect(output).toContain("Markdown Standup");
411
+ expect(output).toContain(" S ");
412
+ expect(output).not.toContain("NaN");
413
+ expect(output).not.toContain("undefined");
414
+ expect(output).not.toContain("Invalid Date");
415
+ });
416
+
417
+ it("gets markdown details from frontmatter without reading participants", async () => {
418
+ vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes(markdownDetail({ action_items: ["Ship fix"] })));
419
+
420
+ const program = buildProgram();
421
+ await expect(
422
+ program.parseAsync(["node", "hq", "meetings", "get", markdownMeetingId]),
423
+ ).resolves.toBeDefined();
424
+
425
+ const output = logSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
426
+ expect(output).toContain("Markdown Standup");
427
+ expect(output).toContain("Status: done");
428
+ expect(output).toContain("Platform: google_meet");
429
+ expect(output).toContain("Origin: recall");
430
+ expect(output).toContain("Company: cmp_indigo");
431
+ expect(output).toContain("Meeting URL: https://meet.example.test/standup");
432
+ expect(output).toContain("Signals: 1");
433
+ expect(output).toContain("stored as a markdown document");
434
+ });
435
+
436
+ it("prints markdown transcript text from the presigned source URL", async () => {
437
+ vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes(markdownDetail()));
438
+ const fetchMock = vi.fn(async () => new Response("# Markdown transcript\n\nHello team."));
439
+ vi.stubGlobal("fetch", fetchMock);
440
+
441
+ const program = buildProgram();
442
+ await program.parseAsync(["node", "hq", "meetings", "transcript", markdownMeetingId]);
443
+
444
+ expect(fetchMock).toHaveBeenCalledWith(markdownUrl);
445
+ const output = logSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
446
+ expect(output).toContain("Transcript: Markdown Standup");
447
+ expect(output).toContain("# Markdown transcript");
448
+ expect(output).toContain("Hello team.");
449
+ });
450
+
451
+ it("falls back to the markdown document for notes when markdown signals are empty", async () => {
452
+ vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes(markdownDetail({})));
453
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("# Notes\n\nFollow up next week.")));
454
+
455
+ const program = buildProgram();
456
+ await program.parseAsync(["node", "hq", "meetings", "notes", markdownMeetingId]);
457
+
458
+ const output = logSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
459
+ const errors = errSpy.mock.calls.map(([line]) => (line === undefined ? "" : String(line))).join("\n");
460
+ expect(output).toContain("Meeting Notes: Markdown Standup");
461
+ expect(output).toContain("# Notes");
462
+ expect(output).toContain("Follow up next week.");
463
+ expect(output).not.toContain("No document URL available");
464
+ expect(errors).not.toContain("No document URL available");
465
+ });
466
+ });