@indigoai-us/hq-cli 5.345.263 → 5.345.267

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 (83) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +4 -48
  3. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +16 -10
  4. package/assets/scaffold/core/scripts/hq-delegate-send.sh +17 -1
  5. package/contracts/host-canary-release.json +7 -7
  6. package/dist/command-catalog.generated.d.ts +67 -1
  7. package/dist/command-catalog.generated.js +83 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/bot.d.ts +2 -0
  11. package/dist/commands/bot.js +4 -3
  12. package/dist/commands/core-delegate-w1b.js +21 -40
  13. package/dist/commands/core-delegate.js +11 -8
  14. package/dist/commands/files-browse.d.ts +83 -4
  15. package/dist/commands/files-browse.js +404 -54
  16. package/dist/commands/groups.js +2 -2
  17. package/dist/commands/skill.js +15 -0
  18. package/dist/commands/sync-held.d.ts +11 -0
  19. package/dist/commands/sync-held.js +65 -1
  20. package/dist/commands/sync-telemetry-report.d.ts +5 -0
  21. package/dist/commands/sync-telemetry-report.js +239 -0
  22. package/dist/commands/sync-telemetry.d.ts +47 -0
  23. package/dist/commands/sync-telemetry.js +309 -0
  24. package/dist/index.js +107 -43
  25. package/dist/lib/agent-kit/mcp/tools.js +2 -2
  26. package/dist/lib/agent-kit/skills.js +12 -6
  27. package/dist/lib/bot/runnable.d.ts +17 -7
  28. package/dist/lib/bot/runnable.js +17 -10
  29. package/dist/lib/capacity/available.js +6 -2
  30. package/dist/lib/capacity/collectors/claude-oauth.d.ts +10 -256
  31. package/dist/lib/capacity/collectors/claude-oauth.js +19 -1078
  32. package/dist/lib/capacity/ledger.d.ts +12 -1
  33. package/dist/lib/capacity/ledger.js +15 -5
  34. package/dist/lib/capacity/route.d.ts +2 -0
  35. package/dist/lib/capacity/route.js +21 -4
  36. package/dist/lib/capacity/scheduler.js +2 -3
  37. package/dist/lib/capacity/sign-in.js +4 -4
  38. package/dist/lib/daemon/merge-sections.d.ts +44 -9
  39. package/dist/lib/daemon/merge-sections.js +234 -37
  40. package/dist/lib/daemon/ops/skill-command.d.ts +2 -0
  41. package/dist/lib/daemon/ops/skill-command.js +7 -1
  42. package/dist/lib/daemon/run.js +1 -0
  43. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +2 -1
  44. package/dist/lib/doctor/checks/antigravity-wiring.js +75 -3
  45. package/dist/lib/doctor/checks/hook-engine.d.ts +2 -0
  46. package/dist/lib/doctor/checks/hook-engine.js +100 -1
  47. package/dist/lib/doctor/checks/host-core.d.ts +1 -1
  48. package/dist/lib/doctor/checks/host-core.js +19 -7
  49. package/dist/lib/doctor/fix/process-identity.d.ts +2 -0
  50. package/dist/lib/doctor/fix/process-identity.js +5 -2
  51. package/dist/lib/hook-engine/coverage.d.ts +19 -10
  52. package/dist/lib/hook-engine/coverage.js +116 -25
  53. package/dist/lib/hook-engine/native-precompact-compatibility.json +8 -1
  54. package/dist/lib/hook-engine/native-stop-compatibility.json +8 -4
  55. package/dist/lib/hook-engine/reconcile.js +60 -2
  56. package/dist/lib/install/antigravity-targets.d.ts +22 -0
  57. package/dist/lib/install/antigravity-targets.js +82 -0
  58. package/dist/lib/signals/reply.js +25 -5
  59. package/dist/lib/signals/steps/extract.d.ts +28 -4
  60. package/dist/lib/signals/steps/extract.js +124 -10
  61. package/dist/lib/sync-core/release.d.ts +1 -1
  62. package/dist/lib/sync-core/release.js +2 -2
  63. package/dist/main.js +8 -3
  64. package/dist/sentry-init.d.ts +7 -1
  65. package/dist/sentry-init.js +6 -2
  66. package/dist/sentry.d.ts +7 -0
  67. package/dist/sentry.js +16 -1
  68. package/dist/started-version.d.ts +13 -0
  69. package/dist/started-version.js +34 -0
  70. package/dist/startup-registration.d.ts +9 -9
  71. package/dist/startup-registration.js +42 -18
  72. package/dist/utils/client-health.d.ts +1 -0
  73. package/dist/utils/client-health.js +54 -11
  74. package/dist/utils/core-next-kill.d.ts +9 -0
  75. package/dist/utils/core-next-kill.js +22 -0
  76. package/dist/utils/host-registration.d.ts +4 -2
  77. package/dist/utils/host-registration.js +55 -7
  78. package/dist/utils/install-tree-recovery-markers.d.ts +45 -0
  79. package/dist/utils/install-tree-recovery-markers.js +70 -0
  80. package/dist/utils/install-tree-torn.d.ts +102 -5
  81. package/dist/utils/install-tree-torn.js +199 -2
  82. package/dist/utils/sentry-fingerprint.js +3 -0
  83. package/package.json +7 -7
@@ -0,0 +1,309 @@
1
+ import { isAuthError } from "../utils/auth-error.js";
2
+ import { isCompanySelectionError } from "../utils/company-selection-error.js";
3
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
4
+ import { isExpectedUserError } from "../utils/expected-cli-error.js";
5
+ import { findHqRootAncestor } from "../utils/hq-roots-core.js";
6
+ import { networkTransportErrorCode } from "../utils/network-transport-error.js";
7
+ import { isPlanGateError } from "../utils/plan-gate-error.js";
8
+ import { peekHqApiKey } from "../utils/resolve-vault-credential.js";
9
+ import { getCompanyUid, looksLikeCompanyUid, vaultApiFetch } from "../utils/vault-api.js";
10
+ import { readActiveCompanySlug } from "./sync-mode.js";
11
+ import { TELEMETRY_VIEWS, renderTelemetryReport } from "./sync-telemetry-report.js";
12
+ export const TELEMETRY_WINDOWS = ["1h", "24h", "7d", "30d"];
13
+ export const SYNC_TELEMETRY_PATH = "/v1/sync-telemetry";
14
+ export const SYNC_TELEMETRY_COMMAND = "hq sync telemetry";
15
+ export const SYNC_TELEMETRY_TIMEOUT_MS = 20_000;
16
+ export const SYNC_TELEMETRY_MAX_RETRIES = 2;
17
+ export const SYNC_TELEMETRY_BACKOFF_MS = [500, 1_500];
18
+ const RETRY_AFTER_CAP_MS = 5_000;
19
+ export const SYNC_TELEMETRY_EXIT = {
20
+ ok: 0,
21
+ badArguments: 2,
22
+ notSignedIn: 3,
23
+ refused: 4,
24
+ rateLimited: 5,
25
+ unavailable: 6,
26
+ };
27
+ const COMPANY_UID_PATTERN = /^cmp_[A-Za-z0-9_-]{1,80}$/;
28
+ const MACHINE_ID_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;
29
+ const SERVER_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/;
30
+ export class PersonLoginRequiredError extends Error {
31
+ constructor() {
32
+ super("sync telemetry needs a person sign-in");
33
+ this.name = "PersonLoginRequiredError";
34
+ }
35
+ }
36
+ class TelemetryTimeoutError extends Error {
37
+ constructor() {
38
+ super("sync telemetry request timed out");
39
+ this.name = "TelemetryTimeoutError";
40
+ }
41
+ }
42
+ function outcome(code, message, status, exitCode, retry = {}) {
43
+ return {
44
+ failure: { ok: false, code, message, status },
45
+ exitCode,
46
+ retryable: retry.retryable === true,
47
+ ...(retry.retryAfterMs !== undefined ? { retryAfterMs: retry.retryAfterMs } : {}),
48
+ };
49
+ }
50
+ function badArguments(message) {
51
+ return outcome("bad_arguments", message, null, SYNC_TELEMETRY_EXIT.badArguments);
52
+ }
53
+ function notSignedIn(status = null) {
54
+ return outcome("not_signed_in", "You are not signed in to HQ, or the session has expired. Run `hq login` and try again.", status, SYNC_TELEMETRY_EXIT.notSignedIn);
55
+ }
56
+ function transportOutcome(err) {
57
+ if (err instanceof TelemetryTimeoutError) {
58
+ return outcome("timeout", "HQ did not answer in time. Check the connection and try again.", null, SYNC_TELEMETRY_EXIT.unavailable, { retryable: true });
59
+ }
60
+ if (isPlanGateError(err) || isExpectedUserError(err)) {
61
+ return outcome("request_not_sent", "HQ could not serve this request for the current sign-in. Sign in as a person with `hq login` and try again.", null, SYNC_TELEMETRY_EXIT.unavailable);
62
+ }
63
+ const code = networkTransportErrorCode(err);
64
+ return outcome("network_error", `Could not reach HQ${code ? ` (${code})` : ""}. Check the connection and try again.`, null, SYNC_TELEMETRY_EXIT.unavailable, { retryable: true });
65
+ }
66
+ function serverCodeFrom(text) {
67
+ let body;
68
+ try {
69
+ body = JSON.parse(text);
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ if (body === null || typeof body !== "object" || Array.isArray(body))
75
+ return undefined;
76
+ const root = body;
77
+ const nested = root.error !== null && typeof root.error === "object" && !Array.isArray(root.error)
78
+ ? root.error.code
79
+ : undefined;
80
+ for (const candidate of [root.code, nested, root.error]) {
81
+ if (typeof candidate === "string" && SERVER_CODE_PATTERN.test(candidate))
82
+ return candidate;
83
+ }
84
+ return undefined;
85
+ }
86
+ function retryAfterMs(response) {
87
+ const raw = response.headers.get("retry-after");
88
+ if (!raw)
89
+ return undefined;
90
+ const seconds = Number(raw);
91
+ if (!Number.isFinite(seconds) || seconds < 0)
92
+ return undefined;
93
+ return Math.min(RETRY_AFTER_CAP_MS, Math.round(seconds * 1000));
94
+ }
95
+ async function statusOutcome(response) {
96
+ const status = response.status;
97
+ if (status === 400) {
98
+ const code = serverCodeFrom(await response.text().catch(() => ""));
99
+ return outcome("bad_arguments", `HQ rejected the request arguments${code ? ` (${code})` : ""}. Check --company, --view, --window and --machine.`, status, SYNC_TELEMETRY_EXIT.badArguments);
100
+ }
101
+ await response.body?.cancel().catch(() => undefined);
102
+ if (status === 401)
103
+ return notSignedIn(status);
104
+ if (status === 403) {
105
+ return outcome("refused", "HQ refused this request. Sync telemetry is open to a signed-in person who is an owner or admin of the company. Agent and machine sign-ins are refused.", status, SYNC_TELEMETRY_EXIT.refused);
106
+ }
107
+ if (status === 404) {
108
+ return outcome("not_available", "This HQ server does not serve sync telemetry yet.", status, SYNC_TELEMETRY_EXIT.unavailable);
109
+ }
110
+ if (status === 429) {
111
+ return outcome("rate_limited", "HQ is limiting sync telemetry requests for this sign-in (60 a minute). Wait a minute and try again.", status, SYNC_TELEMETRY_EXIT.rateLimited, { retryable: true, retryAfterMs: retryAfterMs(response) });
112
+ }
113
+ if (status >= 500) {
114
+ return outcome("server_error", `HQ returned a server error (HTTP ${status}). Try again shortly.`, status, SYNC_TELEMETRY_EXIT.unavailable, { retryable: true });
115
+ }
116
+ return outcome("unexpected_status", `HQ answered with an unexpected status (HTTP ${status}).`, status, SYNC_TELEMETRY_EXIT.unavailable);
117
+ }
118
+ async function attempt(deps, token, query) {
119
+ const controller = new AbortController();
120
+ const timeout = new TelemetryTimeoutError();
121
+ let timer;
122
+ const expired = new Promise((_, reject) => {
123
+ timer = setTimeout(() => {
124
+ controller.abort(timeout);
125
+ reject(timeout);
126
+ }, deps.timeoutMs);
127
+ });
128
+ const exchange = (async () => {
129
+ const response = await deps.request({ token, path: SYNC_TELEMETRY_PATH, query, signal: controller.signal });
130
+ if (!response.ok)
131
+ return statusOutcome(response);
132
+ return { text: await response.text() };
133
+ })();
134
+ exchange.catch(() => undefined);
135
+ try {
136
+ return await Promise.race([exchange, expired]);
137
+ }
138
+ catch (err) {
139
+ return transportOutcome(controller.signal.aborted ? timeout : err);
140
+ }
141
+ finally {
142
+ clearTimeout(timer);
143
+ }
144
+ }
145
+ async function fetchTelemetry(deps, token, query) {
146
+ for (let retries = 0;; retries++) {
147
+ const result = await attempt(deps, token, query);
148
+ if ("text" in result)
149
+ return result;
150
+ if (!result.retryable || retries >= SYNC_TELEMETRY_MAX_RETRIES)
151
+ return result;
152
+ const backoff = SYNC_TELEMETRY_BACKOFF_MS[retries] ?? SYNC_TELEMETRY_BACKOFF_MS[SYNC_TELEMETRY_BACKOFF_MS.length - 1];
153
+ await deps.sleep(Math.max(backoff, result.retryAfterMs ?? 0));
154
+ }
155
+ }
156
+ function tokenOutcome(err) {
157
+ if (err instanceof PersonLoginRequiredError) {
158
+ return outcome("person_login_required", `${SYNC_TELEMETRY_COMMAND} uses a person's HQ sign-in and does not accept an API key. Unset HQ_API_KEY and run \`hq login\`.`, null, SYNC_TELEMETRY_EXIT.notSignedIn);
159
+ }
160
+ if (networkTransportErrorCode(err))
161
+ return transportOutcome(err);
162
+ return notSignedIn();
163
+ }
164
+ function companyOutcome(err) {
165
+ if (isAuthError(err))
166
+ return notSignedIn(401);
167
+ if (isCompanySelectionError(err)) {
168
+ return badArguments("More than one company, or none, matches this sign-in. Pass --company <slug>.");
169
+ }
170
+ if (isExpectedUserError(err)) {
171
+ return badArguments("That company was not found among the companies this sign-in can reach. Check --company.");
172
+ }
173
+ return outcome("company_lookup_failed", "Could not look up the company on HQ. Check the connection and try again.", null, SYNC_TELEMETRY_EXIT.unavailable);
174
+ }
175
+ function report(deps, json, result) {
176
+ if (json)
177
+ deps.out(`${JSON.stringify(result.failure)}\n`);
178
+ else
179
+ deps.err(`${result.failure.message}\n`);
180
+ return result.exitCode;
181
+ }
182
+ export async function runSyncTelemetry(options, deps) {
183
+ const json = options.json === true;
184
+ const view = (options.view ?? "summary");
185
+ const window = options.window ?? "24h";
186
+ if (!TELEMETRY_VIEWS.includes(view)) {
187
+ return report(deps, json, badArguments(`--view must be one of: ${TELEMETRY_VIEWS.join(", ")}.`));
188
+ }
189
+ if (!TELEMETRY_WINDOWS.includes(window)) {
190
+ return report(deps, json, badArguments(`--window must be one of: ${TELEMETRY_WINDOWS.join(", ")}.`));
191
+ }
192
+ if (options.machine !== undefined && !MACHINE_ID_PATTERN.test(options.machine)) {
193
+ return report(deps, json, badArguments("--machine must be an install id (letters, digits, '.', '_', ':' or '-')."));
194
+ }
195
+ if (view === "ranking" && options.company !== undefined) {
196
+ return report(deps, json, badArguments("--view ranking covers every company and takes no --company."));
197
+ }
198
+ if (options.company !== undefined && looksLikeCompanyUid(options.company) && !COMPANY_UID_PATTERN.test(options.company)) {
199
+ return report(deps, json, badArguments("--company is not a valid company uid."));
200
+ }
201
+ let token;
202
+ try {
203
+ token = await deps.token();
204
+ }
205
+ catch (err) {
206
+ return report(deps, json, tokenOutcome(err));
207
+ }
208
+ const query = { view, window };
209
+ if (view !== "ranking") {
210
+ try {
211
+ query.companyUid = await deps.companyUid(token, options.company ?? deps.activeCompany());
212
+ }
213
+ catch (err) {
214
+ return report(deps, json, companyOutcome(err));
215
+ }
216
+ }
217
+ if (options.machine !== undefined)
218
+ query.machine = options.machine;
219
+ const result = await fetchTelemetry(deps, token, query);
220
+ if (!("text" in result))
221
+ return report(deps, json, result);
222
+ let body;
223
+ try {
224
+ body = JSON.parse(result.text);
225
+ }
226
+ catch {
227
+ body = undefined;
228
+ }
229
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
230
+ return report(deps, json, outcome("invalid_response", "HQ answered with something that is not a sync telemetry report. Try again shortly.", 200, SYNC_TELEMETRY_EXIT.unavailable));
231
+ }
232
+ if (json) {
233
+ deps.out(result.text.endsWith("\n") ? result.text : `${result.text}\n`);
234
+ }
235
+ else {
236
+ deps.out(`${renderTelemetryReport(body, view).join("\n")}\n`);
237
+ }
238
+ return SYNC_TELEMETRY_EXIT.ok;
239
+ }
240
+ export function createDefaultSyncTelemetryDeps() {
241
+ return {
242
+ token: async () => {
243
+ if (peekHqApiKey() !== undefined)
244
+ throw new PersonLoginRequiredError();
245
+ return ensureCognitoToken({ interactive: false });
246
+ },
247
+ activeCompany: () => {
248
+ const root = findHqRootAncestor(process.cwd());
249
+ return root ? readActiveCompanySlug(root) : undefined;
250
+ },
251
+ companyUid: async (token, company) => company !== undefined && looksLikeCompanyUid(company) ? company : getCompanyUid(token, company),
252
+ request: vaultApiFetch,
253
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
254
+ timeoutMs: SYNC_TELEMETRY_TIMEOUT_MS,
255
+ out: (text) => {
256
+ process.stdout.write(text);
257
+ },
258
+ err: (text) => {
259
+ process.stderr.write(text);
260
+ },
261
+ };
262
+ }
263
+ const HELP_TEXT = `
264
+ Reads sync health for a company from the HQ server. It changes nothing on this
265
+ computer or on the server, and it does not start or stop a sync.
266
+
267
+ You must be signed in as a person (hq login) who is an owner or admin of the
268
+ company. Agent and machine sign-ins are refused by the server.
269
+
270
+ Views:
271
+ summary overall health, held files and safety counters
272
+ machines one line per machine, failing machines first
273
+ errors recent sync errors with their codes
274
+ people billed sync use per person
275
+ folders uploads and downloads per folder
276
+ loops paths rewritten on a fixed interval
277
+ ranking companies ranked by sync use (Indigo staff; takes no --company)
278
+
279
+ A view or section the server does not record yet prints "not recorded yet".
280
+
281
+ Exit codes:
282
+ 0 report printed
283
+ 2 bad arguments
284
+ 3 not signed in
285
+ 4 refused by the server
286
+ 5 rate limited
287
+ 6 server or network failure
288
+
289
+ Examples:
290
+ hq sync telemetry --company acme
291
+ hq sync telemetry --company acme --view machines --window 7d
292
+ hq sync telemetry --company acme --view errors --machine <installId>
293
+ hq sync telemetry --company acme --json
294
+ `;
295
+ export function registerSyncTelemetryCommand(syncCmd) {
296
+ syncCmd
297
+ .command("telemetry")
298
+ .description("Show sync health, errors and usage for a company, read from the HQ server")
299
+ .option("--company <company>", "Company slug or cmp_ uid (defaults to the active company, else your only company)")
300
+ .option("--view <view>", `What to show: ${TELEMETRY_VIEWS.join(", ")}`, "summary")
301
+ .option("--window <window>", `Time window: ${TELEMETRY_WINDOWS.join(", ")}`, "24h")
302
+ .option("--machine <installId>", "Limit the report to one machine by its install id")
303
+ .option("--json", "Print the server response as JSON; failures print one JSON object")
304
+ .addHelpText("after", HELP_TEXT)
305
+ .action(async (options) => {
306
+ process.exitCode = await runSyncTelemetry(options, createDefaultSyncTelemetryDeps());
307
+ });
308
+ }
309
+ //# sourceMappingURL=sync-telemetry.js.map
package/dist/index.js CHANGED
@@ -3,6 +3,9 @@
3
3
  // Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
4
4
  import "./node-preflight.js";
5
5
  import "./node-network-compat-fast.js";
6
+ // Capture this process's starting CLI version synchronously at entry, before
7
+ // any lazy or fast-path import can load after a concurrent folder swap.
8
+ import { STARTED_CLI_VERSION } from "./started-version.js";
6
9
  import { isVersionRequest, wantsLabelledVersionReport } from "./version-request.js";
7
10
  // Dependency-light: a pure parser + table, no command graph. Safe to load on
8
11
  // every path (including --version) without reintroducing the heavy startup.
@@ -12,6 +15,7 @@ import { CLI_COMMAND_HELP_CATALOG_FLAG } from "./lib/cli-flag-keys.js";
12
15
  // heavy import (main.js) is lazy and reached only when a rejection fires.
13
16
  import { installProcessRejectionBoundary } from "./unhandled-rejection-boundary.js";
14
17
  import { daemonDirectReplacementEnv, installDaemonHelperLifetime } from "./utils/daemon-helper-lifetime.js";
18
+ import { consumeInstallTreeRecoveryMarkers, installTreeRecoveryEnv, } from "./utils/install-tree-recovery-markers.js";
15
19
  import { installFastPathStreamErrorHandlers } from "./utils/fast-stream-errors.js";
16
20
  import { installWindowsHideDefault } from "./utils/windows-hide-default.js";
17
21
  import { fileURLToPath } from "node:url";
@@ -19,7 +23,7 @@ import { parseMonitorCheckFastRequest } from "./lanes-monitor-check-argv.js";
19
23
  import { isLaneSessionStartFastRequest } from "./lanes-session-start-argv.js";
20
24
  import { writeLanesAliasDeprecationForArgv } from "./runners-alias.js";
21
25
  import { createRequire } from "node:module";
22
- import { lstatSync } from "node:fs";
26
+ import { lstatSync, realpathSync } from "node:fs";
23
27
  import { homedir } from "node:os";
24
28
  import { join } from "node:path";
25
29
  import { hookEnginePathArgs, runHookEnginePath } from "./hook-engine-path.js";
@@ -65,44 +69,72 @@ installFastPathStreamErrorHandlers();
65
69
  // markers before any command can start another hq process. Builtins only, so
66
70
  // the fast path still does not load the command graph.
67
71
  installDaemonHelperLifetime();
72
+ // Consume any one-shot torn-install recovery guard markers into process memory
73
+ // and clear them from process.env before any command or hook can spawn a child.
74
+ // Every recovery seam in this process still sees the guard via
75
+ // installTreeRecoveryEnv, while spawned descendants can recover on their own.
76
+ consumeInstallTreeRecoveryMarkers(process.env);
77
+ async function resolveEntryInstall() {
78
+ try {
79
+ const { packageRoot } = await import("./utils/hq-roots.js");
80
+ return { packageRoot: packageRoot() };
81
+ }
82
+ catch {
83
+ return { packageRoot: null };
84
+ }
85
+ }
68
86
  async function runMainWithInstallTreeRecovery() {
69
87
  let runCli;
70
- const { registerCommandsWithRecovery } = await import("./startup-registration.js");
71
88
  try {
72
- const result = await registerCommandsWithRecovery({
73
- register: async () => {
74
- runCli = (await import("./main.js")).runCli;
75
- },
76
- argv: process.argv,
77
- env: daemonDirectReplacementEnv(process.env),
78
- entryPath: fileURLToPath(import.meta.url),
79
- stderr: process.stderr,
80
- });
81
- if (result.reexecStatus !== undefined) {
82
- process.exitCode = result.reexecStatus;
83
- return;
89
+ runCli = (await import("./main.js")).runCli;
90
+ }
91
+ catch (initialError) {
92
+ // Keep the clean main startup path free of an extra packageRoot() walk;
93
+ // only a failed import of main.js pays for the recovery seam.
94
+ const [{ registerCommandsWithRecovery }, entryInstall] = await Promise.all([
95
+ import("./startup-registration.js"),
96
+ resolveEntryInstall(),
97
+ ]);
98
+ try {
99
+ const result = await registerCommandsWithRecovery({
100
+ register: async () => {
101
+ throw initialError;
102
+ },
103
+ argv: process.argv,
104
+ env: installTreeRecoveryEnv(daemonDirectReplacementEnv(process.env)),
105
+ entryPath: fileURLToPath(import.meta.url),
106
+ stderr: process.stderr,
107
+ deps: {
108
+ resolveInstall: () => entryInstall,
109
+ startedVersion: STARTED_CLI_VERSION,
110
+ },
111
+ });
112
+ if (result.reexecStatus !== undefined) {
113
+ process.exitCode = result.reexecStatus;
114
+ return;
115
+ }
84
116
  }
85
- if (!runCli)
86
- throw new Error("HQ CLI startup did not load its command runner");
87
- await runCli();
88
- }
89
- catch (error) {
90
- // main.js may be the module that is missing, so the global rejection
91
- // reporter cannot import its usual handler to print the recovery remedy.
92
- const installTree = await import("./utils/install-tree-torn.js");
93
- if (installTree.isInstallTreeTornError(error)) {
94
- process.stderr.write(`${installTree.installTreeTornStderrLine(error)}\n`);
95
- const sentry = await import("./sentry.js");
96
- sentry.initSentry();
97
- sentry.Sentry.captureException(error, installTree.installTreeTornCaptureContext(error));
98
- sentry.finishSentrySession();
99
- await sentry.Sentry.flush(2_000);
100
- sentry.closeSentryTransport();
101
- process.exitCode = 1;
102
- return;
117
+ catch (error) {
118
+ // main.js may be the module that is missing, so the global rejection
119
+ // reporter cannot import its usual handler to print the recovery remedy.
120
+ const installTree = await import("./utils/install-tree-torn.js");
121
+ if (installTree.isInstallTreeTornError(error)) {
122
+ process.stderr.write(`${installTree.installTreeTornStderrLine(error)}\n`);
123
+ const sentry = await import("./sentry.js");
124
+ sentry.initSentry();
125
+ sentry.Sentry.captureException(error, installTree.installTreeTornCaptureContext(error));
126
+ sentry.finishSentrySession();
127
+ await sentry.Sentry.flush(2_000);
128
+ sentry.closeSentryTransport();
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+ throw error;
103
133
  }
104
- throw error;
105
134
  }
135
+ if (!runCli)
136
+ throw new Error("HQ CLI startup did not load its command runner");
137
+ await runCli();
106
138
  }
107
139
  /**
108
140
  * Fast-route imports happen before main.ts command registration, so the
@@ -116,24 +148,30 @@ const recoverFastImport = async (load, options = {}) => {
116
148
  try {
117
149
  return { module: await load() };
118
150
  }
119
- catch {
151
+ catch (initialError) {
120
152
  // Keep the clean hook path free of startup-registration's update-lock and
121
153
  // package-root imports. Only a failed import pays for the recovery seam.
122
- const { registerCommandsWithRecovery } = await import("./startup-registration.js");
123
- let module;
154
+ const [{ registerCommandsWithRecovery }, entryInstall] = await Promise.all([
155
+ import("./startup-registration.js"),
156
+ resolveEntryInstall(),
157
+ ]);
124
158
  try {
125
159
  const result = await registerCommandsWithRecovery({
126
160
  register: async () => {
127
- module = await load();
161
+ throw initialError;
128
162
  },
129
163
  argv: process.argv,
130
- env: daemonDirectReplacementEnv(process.env),
164
+ env: installTreeRecoveryEnv(daemonDirectReplacementEnv(process.env)),
131
165
  entryPath: fileURLToPath(import.meta.url),
132
166
  stderr: process.stderr,
133
167
  reexecOnSettled: options.reexecOnSettled,
168
+ deps: {
169
+ resolveInstall: () => entryInstall,
170
+ startedVersion: STARTED_CLI_VERSION,
171
+ },
134
172
  });
135
173
  return result.reexecStatus === undefined
136
- ? { module }
174
+ ? {}
137
175
  : { reexecStatus: result.reexecStatus };
138
176
  }
139
177
  catch (error) {
@@ -189,6 +227,21 @@ async function runMonitorCheckFastWithRecovery(request) {
189
227
  return;
190
228
  await runMainWithInstallTreeRecovery();
191
229
  }
230
+ async function runMcpServeWithRecovery() {
231
+ const gate = await recoverFastImport(() => import("./commands/mcp-serve-gate.js"));
232
+ if (gate.reexecStatus !== undefined) {
233
+ process.exitCode = gate.reexecStatus;
234
+ return;
235
+ }
236
+ if (!gate.module || gate.module.denyMcpServeWithoutTokenCache())
237
+ return;
238
+ const loaded = await recoverFastImport(() => import("./commands/mcp-serve.js"));
239
+ if (loaded.reexecStatus !== undefined) {
240
+ process.exitCode = loaded.reexecStatus;
241
+ return;
242
+ }
243
+ await loaded.module?.runMcpServe();
244
+ }
192
245
  /**
193
246
  * The SessionStart hook runs `hq runners session-start` on every new session
194
247
  * under a 2 s cap. Load only that command's module, not the command graph.
@@ -329,7 +382,7 @@ export function stableHealWouldRun(argv, env, platform, home = homedir()) {
329
382
  return false;
330
383
  if (args[0] === "daemon")
331
384
  return false;
332
- if (!/node_modules[/\\]@indigoai-us[/\\]hq-cli[/\\]/i.test(argv[1] ?? ""))
385
+ if (!isInstalledPackagePath(argv[1] ?? "") && !isInstalledPackagePath(resolvedEntryPath(argv[1])))
333
386
  return false;
334
387
  try {
335
388
  return lstatSync(join(home, ".hq", "bin", "hq-hook", "stable")).isSymbolicLink();
@@ -338,6 +391,19 @@ export function stableHealWouldRun(argv, env, platform, home = homedir()) {
338
391
  return false;
339
392
  }
340
393
  }
394
+ function isInstalledPackagePath(entry) {
395
+ return /node_modules[/\\]@indigoai-us[/\\]hq-cli[/\\]/i.test(entry);
396
+ }
397
+ function resolvedEntryPath(entry) {
398
+ if (!entry)
399
+ return "";
400
+ try {
401
+ return realpathSync(entry);
402
+ }
403
+ catch {
404
+ return entry;
405
+ }
406
+ }
341
407
  function dispatchInstallFollowupThenCommand(versionRequest, helpRequest, parsedFastCore, monitorRequest, secretsRequest, mcpRequest) {
342
408
  if (!versionRequest && !monitorRequest && !parsedFastCore && !secretsRequest && !mcpRequest
343
409
  && installFollowupWouldDoWork(process.argv, process.env, process.platform)) {
@@ -447,9 +513,7 @@ function dispatchCliCommand(versionRequest, helpRequest, parsedFastCore, monitor
447
513
  // Without a person token cache the server is denied before mcp-serve.js
448
514
  // and its hqd protocol, lease and preload imports load; same message and
449
515
  // exit code as runMcpServe gives.
450
- void import("./commands/mcp-serve-gate.js").then(({ denyMcpServeWithoutTokenCache }) => denyMcpServeWithoutTokenCache()
451
- ? undefined
452
- : import("./commands/mcp-serve.js").then(({ runMcpServe }) => runMcpServe()));
516
+ void runMcpServeWithRecovery();
453
517
  }
454
518
  else if (parsedFastCore) {
455
519
  // Hot relocated plumbing (`hq core hq-session`, `hq core checkpoint-stop-gate`)
@@ -131,7 +131,7 @@ export function buildAgentMcpTools(clients) {
131
131
  name: "hq_search",
132
132
  description: clients.syncFiles
133
133
  ? "Search the synced company vault (local qmd index). Modes: keyword (default), semantic, hybrid."
134
- : "Search the company vault by file name and path, server-side (no local copy is kept). Content and semantic search need a kit installed with --sync-files.",
134
+ : "Search the company vault by file name and path (no local copy is kept). Slow on large companies: it lists the entire company vault, which can take minutes. If you know the path, use hq_files_read; to look inside a folder, use hq_files_list with a narrow path. Content and semantic search need a kit installed with --sync-files.",
135
135
  inputSchema: {
136
136
  type: "object",
137
137
  properties: {
@@ -155,7 +155,7 @@ export function buildAgentMcpTools(clients) {
155
155
  if (mode && mode !== "keyword") {
156
156
  throw new McpToolInputError(`"${mode}" search needs a local copy of the vault; this agent reads files on demand. Use keyword, or reinstall the kit with \`hq agent kit install --sync-files\`.`);
157
157
  }
158
- return fromRun(await clients.runHq(["files", "search", query, "--company", company]), "hq files search");
158
+ return fromRun(await clients.runHq(["files", "search", query, "--company", company, "--no-local", "--quiet"]), "hq files search");
159
159
  }
160
160
  const hqArgs = ["search", query, "--mode", mode ?? "keyword", "-n", String(count), "--json"];
161
161
  return fromRun(await clients.runHq(hqArgs), "hq search");
@@ -62,17 +62,23 @@ mark each item done.
62
62
  description: "Find things in the company vault (documents, knowledge, meeting notes) with the hq CLI.",
63
63
  body: `# HQ search
64
64
 
65
- By default this agent keeps no local copy of the vault, so search runs
66
- server-side and matches file NAMES and paths, not file contents:
65
+ By default this agent keeps no local copy of the vault. Without it, search
66
+ matches file NAMES and paths, not file contents:
67
67
 
68
68
  \`\`\`bash
69
- hq files search "<query>" --company <slug> # find files by name/path
70
- hq files browse companies/<slug>/<folder> # list a folder
69
+ hq files get companies/<slug>/<file> # fetch one file when you know its path
71
70
  hq files cat companies/<slug>/<file> # read one file
71
+ hq files browse companies/<slug>/<folder> # list one folder
72
+ hq files search "<query>" --company <slug> # find files by name/path (slow)
72
73
  \`\`\`
73
74
 
74
- A good pattern for a question you cannot answer from names alone: search or
75
- browse to narrow to a few likely files, then read them with \`hq files cat\`.
75
+ \`hq files search\` lists the entire company vault and filters it locally, so
76
+ on a large company it can take several minutes. If you know the path, use
77
+ \`hq files get\` or \`hq files cat\`. To look inside a folder, use \`hq files browse\`
78
+ with a narrow prefix. Search only when you know neither.
79
+
80
+ A good pattern for a question you cannot answer from names alone: browse a
81
+ narrow folder to find a few likely files, then read them with \`hq files cat\`.
76
82
 
77
83
  Content and semantic search need a local copy and its index, which only exists
78
84
  if the kit was installed with \`--sync-files\`. In that case (check
@@ -16,11 +16,15 @@
16
16
  *
17
17
  * The rule here is the runtime's rule, asked before anything is written: the
18
18
  * bot must run on a computer (`computeMode: "local"`), and the kind this
19
- * installation would run it as — from the settings the cloud kept for it — must
20
- * be the kind the cloud record says it is. A company bot whose saved settings
21
- * do not say "company" (the case above: no saved settings at all, so the adopt
22
- * defaults to personal) is exactly the bot the runtime refuses, and it is now
23
- * refused here instead, before it costs anything.
19
+ * installation would run it as must be the kind the cloud record says it is.
20
+ *
21
+ * When the cloud kept no settings, adopt/restore take the kind from the
22
+ * record (`botKind`), not the personal default. That is what `hq bot run`
23
+ * then checks. The old personal default is what produced the dead LaunchAgent
24
+ * above; refusing every company bot with no saved settings then made
25
+ * `hq bot status` recommend `hq bot adopt` for a command that always refused.
26
+ * A saved `kind: "personal"` on a company record is still a real mismatch and
27
+ * is still refused.
24
28
  */
25
29
  import type { MyLocalBot } from "./api.js";
26
30
  /**
@@ -28,8 +32,9 @@ import type { MyLocalBot } from "./api.js";
28
32
  * the desktop app and the `--json` consumers switch on these values.
29
33
  *
30
34
  * cloud-compute the record runs in HQ Cloud, not on any computer
31
- * company-bot it acts as a company member, and nothing here can run it
32
- * as one — the runtime would refuse it at every start
35
+ * company-bot the record is a company bot, but the settings HQ kept
36
+ * would run it as a personal bot — the runtime would refuse
37
+ * it at every start
33
38
  * kind-mismatch anything else the runtime's identity preflight would refuse
34
39
  */
35
40
  export type BotNotRunnableReason = "cloud-compute" | "company-bot" | "kind-mismatch";
@@ -41,6 +46,11 @@ export interface RemoteBotRunnability {
41
46
  }
42
47
  /** The record fields the decision reads — nothing else is consulted. */
43
48
  export type RemoteBotRunnabilityInput = Pick<MyLocalBot, "botKind" | "computeMode" | "localConfig">;
49
+ /**
50
+ * Kind this installation would write into bot.json, then run. Missing saved
51
+ * settings follow the cloud record, not the personal restore default.
52
+ */
53
+ export declare function restoreKindForRecord(bot: RemoteBotRunnabilityInput): "personal" | "company";
44
54
  /**
45
55
  * The one answer restore, adopt and `list --remote` all use. `name` only
46
56
  * shapes the sentence; the decision itself reads the record.