@indigoai-us/hq-cli 5.345.203 → 5.345.205

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 (95) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/command-catalog.generated.d.ts +51 -1
  3. package/dist/command-catalog.generated.js +63 -1
  4. package/dist/commands/bot.d.ts +67 -0
  5. package/dist/commands/bot.js +308 -41
  6. package/dist/commands/cloud-off-gate.d.ts +9 -2
  7. package/dist/commands/cloud-off-gate.js +49 -13
  8. package/dist/commands/cloud.d.ts +14 -2
  9. package/dist/commands/cloud.js +25 -16
  10. package/dist/commands/feedback.d.ts +26 -0
  11. package/dist/commands/feedback.js +91 -5
  12. package/dist/commands/install-global.d.ts +3 -1
  13. package/dist/commands/install-global.js +15 -4
  14. package/dist/commands/lanes.d.ts +2 -0
  15. package/dist/commands/lanes.js +9 -3
  16. package/dist/commands/mcp-serve.d.ts +5 -2
  17. package/dist/commands/mcp-serve.js +45 -3
  18. package/dist/commands/mcp-status.d.ts +3 -1
  19. package/dist/commands/mcp-status.js +24 -14
  20. package/dist/commands/secrets.js +11 -1
  21. package/dist/commands/sources.js +10 -15
  22. package/dist/commands/sync-core.js +2 -0
  23. package/dist/index.js +7 -2
  24. package/dist/lib/bot/claude-login.d.ts +7 -1
  25. package/dist/lib/bot/claude-login.js +56 -16
  26. package/dist/lib/bot/executive-settings.d.ts +13 -0
  27. package/dist/lib/bot/executive-settings.js +20 -17
  28. package/dist/lib/bot/executive-sync.d.ts +12 -0
  29. package/dist/lib/bot/executive-sync.js +36 -0
  30. package/dist/lib/bot/executive.d.ts +51 -0
  31. package/dist/lib/bot/executive.js +144 -0
  32. package/dist/lib/bot/fleet-cron.d.ts +7 -0
  33. package/dist/lib/bot/fleet-cron.js +2 -1
  34. package/dist/lib/bot/jobs/executive-handover.d.ts +6 -0
  35. package/dist/lib/bot/jobs/executive-handover.js +33 -0
  36. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +22 -0
  37. package/dist/lib/bot/jobs/hot-signal-sync.js +47 -0
  38. package/dist/lib/bot/listed-running.d.ts +16 -0
  39. package/dist/lib/bot/listed-running.js +16 -0
  40. package/dist/lib/bot/pending-switch.d.ts +51 -0
  41. package/dist/lib/bot/pending-switch.js +103 -0
  42. package/dist/lib/bot/run.js +27 -3
  43. package/dist/lib/bot/runtime-failure.js +19 -3
  44. package/dist/lib/bot/status.d.ts +20 -0
  45. package/dist/lib/capacity/collectors/claude-oauth.d.ts +53 -5
  46. package/dist/lib/capacity/collectors/claude-oauth.js +251 -71
  47. package/dist/lib/company-skill-wrapper.js +29 -0
  48. package/dist/lib/daemon/catalog.js +2 -2
  49. package/dist/lib/daemon/hq-child-bootstrap.mjs +197 -2
  50. package/dist/lib/daemon/resolver.d.ts +14 -0
  51. package/dist/lib/daemon/resolver.js +96 -0
  52. package/dist/lib/daemon/run.d.ts +11 -0
  53. package/dist/lib/daemon/run.js +60 -8
  54. package/dist/lib/daemon/server.d.ts +2 -9
  55. package/dist/lib/daemon/server.js +3 -89
  56. package/dist/lib/doctor/checks/claude-wiring.js +41 -0
  57. package/dist/lib/doctor/checks/sync-health.d.ts +8 -0
  58. package/dist/lib/doctor/checks/sync-health.js +34 -2
  59. package/dist/lib/doctor/duplicate-hook-registrations.d.ts +34 -0
  60. package/dist/lib/doctor/duplicate-hook-registrations.js +130 -0
  61. package/dist/lib/doctor/fix/apply.js +79 -3
  62. package/dist/lib/doctor/fix/remediation.d.ts +1 -1
  63. package/dist/lib/doctor/fix/remediation.js +15 -0
  64. package/dist/lib/doctor/types.d.ts +1 -1
  65. package/dist/lib/doctor/types.js +1 -0
  66. package/dist/lib/lanes/config.js +13 -0
  67. package/dist/lib/lanes/throttle.d.ts +12 -1
  68. package/dist/lib/lanes/throttle.js +27 -8
  69. package/dist/lib/lanes/types.d.ts +5 -0
  70. package/dist/lib/mcp/local-native-tools.d.ts +40 -0
  71. package/dist/lib/mcp/local-native-tools.js +111 -0
  72. package/dist/lib/mcp/tools.d.ts +2 -0
  73. package/dist/lib/mcp/tools.js +2 -0
  74. package/dist/lib/signals/steps/extract.d.ts +111 -5
  75. package/dist/lib/signals/steps/extract.js +524 -55
  76. package/dist/lib/sync-core/engine-home.d.ts +2 -1
  77. package/dist/lib/sync-core/engine-home.js +25 -8
  78. package/dist/lib/sync-core/reconcile.d.ts +3 -1
  79. package/dist/lib/sync-core/reconcile.js +21 -8
  80. package/dist/lib/sync-core/release.d.ts +14 -5
  81. package/dist/lib/sync-core/release.js +58 -14
  82. package/dist/sentry-init.js +6 -0
  83. package/dist/utils/cli-network-lifecycle.d.ts +11 -1
  84. package/dist/utils/cli-network-lifecycle.js +36 -2
  85. package/dist/utils/daemon-helper-lifetime.d.ts +39 -0
  86. package/dist/utils/daemon-helper-lifetime.js +209 -0
  87. package/dist/utils/daemon-helper-markers.d.ts +24 -0
  88. package/dist/utils/daemon-helper-markers.js +53 -0
  89. package/dist/utils/mcp-launcher.d.ts +28 -0
  90. package/dist/utils/mcp-launcher.js +117 -0
  91. package/dist/utils/package-use-lease.d.ts +10 -0
  92. package/dist/utils/package-use-lease.js +31 -0
  93. package/dist/utils/resident-package-preload.js +4 -1
  94. package/docs/anywhere-runtime.md +7 -0
  95. package/package.json +7 -7
@@ -8,8 +8,11 @@
8
8
  * under 100ms. The MCP SDK is not loaded either: the stdio transport is
9
9
  * newline-delimited JSON-RPC 2.0 and is handled here directly.
10
10
  *
11
- * When hqd is unreachable every tool call returns an isError result naming
12
- * `hq daemon status`, and the server keeps running.
11
+ * When hqd is not running, hq_resolve_company, hq_policy_check and
12
+ * hq_journal_append are answered in process with the same checks
13
+ * (src/lib/mcp/local-native-tools.ts), provided an HQ root is known. Every
14
+ * other tool call returns an isError result naming `hq daemon status`, and
15
+ * the server keeps running.
13
16
  */
14
17
  import * as fs from "node:fs";
15
18
  import * as os from "node:os";
@@ -21,6 +24,9 @@ import { releaseCurrentPackageUseLease, releasePackageUseLeaseAfterResidentPrelo
21
24
  import { preloadResidentPackageModules, reportResidentPackagePreloadFailure, RESIDENT_PACKAGE_MODULES } from "../utils/resident-package-preload.js";
22
25
  export const MCP_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
23
26
  const UNREACHABLE_CODES = new Set(["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE", "ETIMEDOUT", "ESOCKET", "EACCES"]);
27
+ /** hqd is not running, so the request never reached it and a local answer cannot repeat a write. */
28
+ const NOT_RUNNING_CODES = new Set(["ENOENT", "ECONNREFUSED"]);
29
+ const LOCAL_GATE_TTL_MS = 60_000;
24
30
  function hasPersonTokenCache(env, home) {
25
31
  // Mirrors personTokenCacheFile() in utils/cognito-session.ts; duplicated so this path does not load that module.
26
32
  const stateDir = env.HQ_STATE_DIR?.trim() || path.join(home, ".hq");
@@ -101,6 +107,39 @@ export async function runMcpServe(opts = {}) {
101
107
  };
102
108
  const reply = (id, result) => send({ id, result });
103
109
  const replyError = (id, code, message) => send({ id, error: { code, message } });
110
+ // hqd keeps a gate decision for at most 60 seconds; the local fallback does the same.
111
+ let gateAllowedAt;
112
+ const localRuntimeEnabled = async () => {
113
+ if (gateAllowedAt !== undefined && Date.now() - gateAllowedAt < LOCAL_GATE_TTL_MS)
114
+ return true;
115
+ gateAllowedAt = undefined;
116
+ const allowed = await runtimeAllowed();
117
+ if (allowed)
118
+ gateAllowedAt = Date.now();
119
+ return allowed;
120
+ };
121
+ /**
122
+ * Answer a local-only native tool in process when hqd is unreachable.
123
+ * Returns undefined when the tool needs hqd or no HQ root is known.
124
+ */
125
+ const callLocally = async (name, args) => {
126
+ const local = await import("../lib/mcp/local-native-tools.js");
127
+ if (!local.LOCAL_NATIVE_TOOL_NAMES.has(name))
128
+ return undefined;
129
+ const hqRoot = readHqRoot(env, home);
130
+ if (!hqRoot)
131
+ return undefined;
132
+ try {
133
+ const value = await local.callLocalNativeTool(name, args, { hqRoot, home, env, cwd, runtimeEnabled: localRuntimeEnabled });
134
+ return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }], structuredContent: value };
135
+ }
136
+ catch (err) {
137
+ const code = local.localToolErrorCode(err);
138
+ if (code === null)
139
+ return toolError("internal", err instanceof Error ? err.message : String(err));
140
+ return toolError(code, err.message);
141
+ }
142
+ };
104
143
  const callTool = async (params) => {
105
144
  const { tools } = await getPackageHandlers();
106
145
  const name = params.name;
@@ -115,6 +154,9 @@ export async function runMcpServe(opts = {}) {
115
154
  if (!(err instanceof HqdClientError))
116
155
  throw err;
117
156
  if (UNREACHABLE_CODES.has(err.code)) {
157
+ const local = NOT_RUNNING_CODES.has(err.code) ? await callLocally(name, args) : undefined;
158
+ if (local !== undefined)
159
+ return local;
118
160
  return toolError("hqd_unreachable", `The HQ daemon (hqd) is not reachable at ${socketPath}. Run \`hq daemon status\` to check it, and \`hq daemon install\` if it is not installed. (${err.code})`);
119
161
  }
120
162
  return toolError(err.code, err.message);
@@ -132,7 +174,7 @@ export async function runMcpServe(opts = {}) {
132
174
  protocolVersion,
133
175
  capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
134
176
  serverInfo: { name: "hq", version: CLI_VERSION },
135
- instructions: "HQ tools, answered by the local HQ daemon. hq_resolve_company tells you which company the current repo belongs to; call it before company-scoped tools. If a tool returns hqd_unreachable, ask the user to run `hq daemon status`.",
177
+ instructions: "HQ tools, answered by the local HQ daemon. hq_resolve_company tells you which company the current repo belongs to; call it before company-scoped tools. hq_resolve_company, hq_policy_check and hq_journal_append still work when hqd is stopped. If a tool returns hqd_unreachable, ask the user to run `hq daemon status`.",
136
178
  });
137
179
  return;
138
180
  }
@@ -93,7 +93,9 @@ export interface McpStatusReport {
93
93
  * differ). A malformed config marks that runtime `parses:false`/`unparseable`
94
94
  * rather than throwing. Header VALUES are never read into the report.
95
95
  */
96
- export declare function computeMcpStatus(env: SafeWriteEnv): McpStatusReport;
96
+ export declare function computeMcpStatus(env: SafeWriteEnv, opts?: {
97
+ runningCliEntry?: string;
98
+ }): McpStatusReport;
97
99
  /**
98
100
  * Render the report as human-readable text. Per server: name, pack, transport,
99
101
  * target, and a per-runtime line. PARTIAL servers are marked loudly with the
@@ -23,9 +23,10 @@
23
23
  */
24
24
  import * as fs from 'fs';
25
25
  import * as path from 'path';
26
- import { isExecutableOnPath } from '../utils/resolve-executable.js';
26
+ import { findExecutableOnPath } from '../utils/resolve-executable.js';
27
+ import { isStaleVersionedStorePath } from '../utils/mcp-launcher.js';
27
28
  import { anywhereRuntimeEnabled } from './anywhere-runtime-flag.js';
28
- import { claudeTargets, MCP_SUBPROCESS_PATH } from '../lib/install/claude-targets.js';
29
+ import { claudeTargets, HQ_MCP_SERVER_NAME, MCP_SUBPROCESS_PATH } from '../lib/install/claude-targets.js';
29
30
  import { HQ_PACK_PROVENANCE_KEY, SECRET_REDACTION, backupRoot, claudeConfigFormat, claudeConfigPath, codexConfigFormat, codexConfigPath, CODEX_MCP_SERVERS_KEY, ConfigParseError, isCodexInstalled, readConfigDoc, resolveEnv, } from './mcp-registration.js';
30
31
  // ---------------------------------------------------------------------------
31
32
  // Pure status computation.
@@ -136,7 +137,7 @@ function pluginAndCodexMcpEquivalent(plugin, codex) {
136
137
  const pluginEnv = plugin.env && typeof plugin.env === 'object' ? plugin.env : {};
137
138
  const codexEnv = codex.env && typeof codex.env === 'object' ? codex.env : {};
138
139
  const envMatch = JSON.stringify(envKeysOf(plugin)) === JSON.stringify(envKeysOf(codex)) ||
139
- (globalNodeEntry && Object.keys(pluginEnv).length === 0 && Object.keys(codexEnv).length === 1 && codexEnv.PATH === MCP_SUBPROCESS_PATH);
140
+ (globalNodeEntry && Object.keys(pluginEnv).length === 0 && Object.keys(codexEnv).length === 1 && typeof codexEnv.PATH === 'string' && codexEnv.PATH.endsWith(MCP_SUBPROCESS_PATH));
140
141
  return pluginTarget && codexTarget && JSON.stringify(headerKeysOf(plugin)) === JSON.stringify(headerKeysOf(codex)) && envMatch;
141
142
  }
142
143
  /** Scan the Claude runtime: read `~/.claude.json`, collect HQ-owned servers. */
@@ -197,7 +198,7 @@ function scanCodex(env) {
197
198
  return { installed: true, parses, configPath, hqServers };
198
199
  }
199
200
  /** Build the per-runtime, per-server status from a scan (or its absence). */
200
- function runtimeServerStatus(scan, name, checkHealth) {
201
+ function runtimeServerStatus(scan, name, checkHealth, runningCliEntry) {
201
202
  if (!scan.installed)
202
203
  return { presence: 'not-installed' };
203
204
  if (!scan.parses)
@@ -211,22 +212,30 @@ function runtimeServerStatus(scan, name, checkHealth) {
211
212
  target: targetOf(found.def),
212
213
  headerKeys: headerKeysOf(found.def),
213
214
  envKeys: envKeysOf(found.def),
214
- ...(checkHealth ? { healthy: isLaunchable(found.def) } : {}),
215
+ ...(checkHealth ? { healthy: isLaunchable(name, found.def, runningCliEntry) } : {}),
215
216
  };
216
217
  }
217
218
  /** True when a def can launch (see {@link RuntimeServerStatus.healthy}). */
218
- function isLaunchable(def) {
219
+ function isLaunchable(name, def, runningCliEntry) {
219
220
  if (transportOf(def) !== 'stdio')
220
221
  return true;
221
222
  const command = def.command;
222
- if (typeof command !== 'string' || !commandIsLaunchable(command))
223
+ if (typeof command !== 'string' || !commandIsLaunchable(command, def))
223
224
  return false;
224
225
  const args = Array.isArray(def.args) ? def.args : [];
226
+ // The hq server's entry script pinned to a version-pinned store path other than
227
+ // the running CLI launches an old CLI. Only args[0] of the `hq` server is judged.
228
+ if (name === HQ_MCP_SERVER_NAME && typeof args[0] === 'string' && isStaleVersionedStorePath(args[0], runningCliEntry))
229
+ return false;
225
230
  return args.every((a) => typeof a !== 'string' || !path.isAbsolute(a) || fs.existsSync(a));
226
231
  }
227
- /** Codex resolves bare MCP commands through the host process PATH. */
228
- function commandIsLaunchable(command) {
229
- return isExecutableOnPath(command);
232
+ /**
233
+ * Absolute commands must exist and be executable. Bare commands resolve under the
234
+ * PATH the host will hand the server (the registered env.PATH), else the host PATH.
235
+ */
236
+ function commandIsLaunchable(command, def) {
237
+ const registered = def.env && typeof def.env === 'object' ? def.env.PATH : undefined;
238
+ return findExecutableOnPath(command, typeof registered === 'string' ? registered : undefined) !== undefined;
230
239
  }
231
240
  /** List the most-recent backup dir names under `backupRoot` (newest first, capped). */
232
241
  function recentBackups(env) {
@@ -255,7 +264,8 @@ function recentBackups(env) {
255
264
  * differ). A malformed config marks that runtime `parses:false`/`unparseable`
256
265
  * rather than throwing. Header VALUES are never read into the report.
257
266
  */
258
- export function computeMcpStatus(env) {
267
+ export function computeMcpStatus(env, opts = {}) {
268
+ const runningCliEntry = opts.runningCliEntry ?? process.argv[1];
259
269
  const checkHealth = anywhereRuntimeEnabled();
260
270
  const claudeScan = scanClaude(env);
261
271
  const codexScan = scanCodex(env);
@@ -274,8 +284,8 @@ export function computeMcpStatus(env) {
274
284
  const names = new Set([...claudeScan.hqServers.keys(), ...codexScan.hqServers.keys()]);
275
285
  const servers = [];
276
286
  for (const name of [...names].sort()) {
277
- const claude = runtimeServerStatus(claudeScan, name, checkHealth);
278
- const codex = runtimeServerStatus(codexScan, name, checkHealth);
287
+ const claude = runtimeServerStatus(claudeScan, name, checkHealth, runningCliEntry);
288
+ const codex = runtimeServerStatus(codexScan, name, checkHealth, runningCliEntry);
279
289
  // Prefer whichever runtime has the def for the top-level transport/target.
280
290
  const claudeFound = claudeScan.hqServers.get(name);
281
291
  const codexFound = codexScan.hqServers.get(name);
@@ -346,7 +356,7 @@ function renderRuntimeLine(label, st) {
346
356
  case 'present': {
347
357
  const parts = st.healthy === undefined
348
358
  ? ['present']
349
- : [st.healthy ? 'present (healthy)' : 'present (UNHEALTHY: command not launchable)'];
359
+ : [st.healthy ? 'present (healthy)' : 'present (UNHEALTHY: command not launchable (missing, or pinned to an old CLI path; re-run `hq install --global`))'];
350
360
  if (st.headerKeys && st.headerKeys.length > 0) {
351
361
  parts.push(`headers: ${st.headerKeys.map((k) => `${k}=${SECRET_REDACTION}`).join(', ')}`);
352
362
  }
@@ -68,6 +68,7 @@ export const SECRETS_EXEC_UNATTENDED_NO_COMPANY_MESSAGE = "hq secrets exec has n
68
68
  "Pass --company <slug> (or --personal), or set HQ_SESSION_ID to the session this job runs under.";
69
69
  import { removeCacheEntry, clearAllCache } from "../utils/secrets-cache.js";
70
70
  import { isHqCliChild, releaseChildWrapperPackageUseLeaseAfterStart } from "../utils/child-wrapper-lease.js";
71
+ import { withPackageUseLeaseReleasedDuring } from "../utils/package-use-lease.js";
71
72
  import { resolveDefaultHqRoot } from "../utils/hq-root-resolver.js";
72
73
  import { fastFlagEnabledDefaultOn } from "../native-fast-route.js";
73
74
  import { MULTI_COMPANY_SESSION_LOCK_FLAG } from "../lib/cli-flag-keys.js";
@@ -214,7 +215,16 @@ function parseDuration(input) {
214
215
  return value * 24 * 60 * 60 * 1000;
215
216
  return null;
216
217
  }
218
+ // Waiting on a person is not package use. Drop the package-use lease while a
219
+ // prompt is open so a forgotten prompt cannot block HQ CLI updates for days
220
+ // (feedback_77165502); the lease is taken again once the answer arrives.
217
221
  function confirmPrompt(message) {
222
+ return withPackageUseLeaseReleasedDuring(() => readConfirmationFromTerminal(message));
223
+ }
224
+ function promptSecretInteractively() {
225
+ return withPackageUseLeaseReleasedDuring(readSecretFromTerminal);
226
+ }
227
+ function readConfirmationFromTerminal(message) {
218
228
  return import("node:readline").then(({ createInterface }) => {
219
229
  const rl = createInterface({
220
230
  input: process.stdin,
@@ -239,7 +249,7 @@ function readFromPipedStdin() {
239
249
  process.stdin.on("error", reject);
240
250
  });
241
251
  }
242
- function promptSecretInteractively() {
252
+ function readSecretFromTerminal() {
243
253
  return new Promise((resolve, reject) => {
244
254
  process.stdout.write("Enter secret value: ");
245
255
  if (process.stdin.isTTY) {
@@ -47,6 +47,7 @@ import { S3Client } from "@aws-sdk/client-s3";
47
47
  import { resolveCanonicalPersonUid } from "./cloud.js";
48
48
  import { botsRoot as defaultBotsRoot } from "../lib/bot/paths.js";
49
49
  import { ensureHotSignalSyncJob } from "../lib/bot/jobs/hot-signal-sync.js";
50
+ import { resolveExecutiveBot } from "../lib/bot/executive.js";
50
51
  import { companyOfHotSignalSyncJob, fleetCronOps } from "../lib/bot/fleet-cron.js";
51
52
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../lib/bot/config.js";
52
53
  import { findHotSignalSyncJobs, lastRunsPerAdapter, parseDailyAt, renderScheduleReport, rescheduleDaily, toJobView, } from "../lib/hot-channels/schedule.js";
@@ -863,24 +864,18 @@ export async function runSchedule(options, overrides = {}) {
863
864
  }
864
865
  return finishScheduleReport(options, overrides, company, fleetJobView(fleetFound), [], now);
865
866
  }
866
- if (options.at !== undefined && fleetBotsIn(botsRootDir).some((bot) => bot.botName === "setup")) {
867
- throw new Error(`The setup bot runs on the HQ Fleet Runtime and has no hot-signal-sync job for ${company} yet. Start it once with \`hq bot start setup\` so it adds the job, then set the time again.`);
867
+ // The daily sync belongs to the Executive bot (hq bot eb).
868
+ const executiveBot = resolveExecutiveBot({ root: botsRootDir });
869
+ if (options.at !== undefined && executiveBot && fleetBotsIn(botsRootDir).some((bot) => bot.botName === executiveBot.name)) {
870
+ throw new Error(`The Executive bot ${executiveBot.name} runs on the HQ Fleet Runtime and has no hot-signal-sync job for ${company} yet. Start it once with \`hq bot start ${executiveBot.name}\` so it adds the job, then set the time again.`);
868
871
  }
869
872
  let found = findHotSignalSyncJobs(botsRootDir, company);
870
873
  if (options.at !== undefined) {
871
- if (found.length === 0) {
872
- // Setting a time turns the daily sync on: register it on the personal setup bot.
873
- const root = overrides.botsRoot ?? defaultBotsRoot();
874
- const setupDir = path.join(root, "setup");
875
- if (fs.existsSync(setupDir)) {
876
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
877
- const otherBotDirs = fs
878
- .readdirSync(root, { withFileTypes: true })
879
- .filter((d) => d.isDirectory())
880
- .map((d) => path.join(root, d.name));
881
- ensureHotSignalSyncJob(setupDir, { company, timezone, otherBotDirs }, now);
882
- found = findHotSignalSyncJobs(root, company);
883
- }
874
+ if (found.length === 0 && executiveBot) {
875
+ // Setting a time turns the daily sync on: register it on the Executive bot.
876
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
877
+ ensureHotSignalSyncJob(executiveBot.dir, { company, timezone }, now);
878
+ found = findHotSignalSyncJobs(botsRootDir, company);
884
879
  }
885
880
  if (found.length === 0)
886
881
  throw new NoHotSignalSyncJobError(company);
@@ -59,6 +59,8 @@ export async function runSyncCoreReconcile(opts, d = defaultDeps()) {
59
59
  }),
60
60
  readRolloutFlag: (companyUid) => readCompanyRolloutFlag(companyUid, token, { env: d.env }),
61
61
  ensureBinary: (release) => ensureSyncCoreBinary({ home: d.home, platform: d.platform, arch: d.arch, release, env: d.env }),
62
+ platform: d.platform,
63
+ env: d.env,
62
64
  readPin: () => readSyncCorePin({ env: d.env }),
63
65
  log: opts.json ? () => { } : d.out,
64
66
  });
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { CLI_COMMAND_HELP_CATALOG_FLAG } from "./lib/cli-flag-keys.js";
11
11
  // Also dependency-light: registers a process-level rejection boundary; its only
12
12
  // heavy import (main.js) is lazy and reached only when a rejection fires.
13
13
  import { installProcessRejectionBoundary } from "./unhandled-rejection-boundary.js";
14
+ import { daemonDirectReplacementEnv, installDaemonHelperLifetime } from "./utils/daemon-helper-lifetime.js";
14
15
  import { installFastPathStreamErrorHandlers } from "./utils/fast-stream-errors.js";
15
16
  import { installWindowsHideDefault } from "./utils/windows-hide-default.js";
16
17
  import { fileURLToPath } from "node:url";
@@ -35,6 +36,10 @@ function cygpathMixedPath(value) {
35
36
  // so runCli's finally still finalizes release health and flushes Sentry.
36
37
  installProcessRejectionBoundary();
37
38
  installFastPathStreamErrorHandlers();
39
+ // No-op unless the daemon spawned this process. Clears the one-shot owner
40
+ // markers before any command can start another hq process. Builtins only, so
41
+ // the fast path still does not load the command graph.
42
+ installDaemonHelperLifetime();
38
43
  async function runMainWithInstallTreeRecovery() {
39
44
  let runCli;
40
45
  const { registerCommandsWithRecovery } = await import("./startup-registration.js");
@@ -44,7 +49,7 @@ async function runMainWithInstallTreeRecovery() {
44
49
  runCli = (await import("./main.js")).runCli;
45
50
  },
46
51
  argv: process.argv,
47
- env: process.env,
52
+ env: daemonDirectReplacementEnv(process.env),
48
53
  entryPath: fileURLToPath(import.meta.url),
49
54
  stderr: process.stderr,
50
55
  });
@@ -96,7 +101,7 @@ const recoverFastImport = async (load, options = {}) => {
96
101
  module = await load();
97
102
  },
98
103
  argv: process.argv,
99
- env: process.env,
104
+ env: daemonDirectReplacementEnv(process.env),
100
105
  entryPath: fileURLToPath(import.meta.url),
101
106
  stderr: process.stderr,
102
107
  reexecOnSettled: options.reexecOnSettled,
@@ -21,7 +21,13 @@ export interface ClaudeLoginDeps {
21
21
  env?: NodeJS.ProcessEnv;
22
22
  home?: string;
23
23
  platform?: NodeJS.Platform;
24
- readKeychain?: () => KeychainRead;
24
+ /**
25
+ * Reads the Keychain item; `account` scopes the read to one account name.
26
+ * Omitted account means "any item for the service" (the first one found).
27
+ */
28
+ readKeychain?: (account?: string) => KeychainRead;
29
+ /** The login user's account name; null when unknown. */
30
+ username?: string | null;
25
31
  now?: () => number;
26
32
  }
27
33
  export declare function checkClaudeCodeLogin(deps?: ClaudeLoginDeps): ClaudeLoginCheck;
@@ -17,9 +17,20 @@ import * as path from "node:path";
17
17
  import { fleetHome } from "./fleet-local.js";
18
18
  export const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials";
19
19
  export const CLAUDE_LOGIN_ENV_VARS = ["ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY"];
20
- function readKeychainWithSecurity() {
20
+ function safeUsername() {
21
21
  try {
22
- const stdout = execFileSync("security", ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-w"], {
22
+ return os.userInfo().username || null;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ function readKeychainWithSecurity(account) {
29
+ const args = account
30
+ ? ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-a", account, "-w"]
31
+ : ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-w"];
32
+ try {
33
+ const stdout = execFileSync("security", args, {
23
34
  encoding: "utf8",
24
35
  stdio: ["ignore", "pipe", "pipe"],
25
36
  timeout: 5000,
@@ -113,30 +124,59 @@ export function checkClaudeCodeLogin(deps = {}) {
113
124
  sources.push({ source: "macos_keychain", status: "skipped", reason: "not macOS" });
114
125
  }
115
126
  else {
116
- const read = (deps.readKeychain ?? readKeychainWithSecurity)();
117
- if (read.code !== 0) {
118
- const detail = read.stderr.replace(/\s+/g, " ").trim().slice(0, 200) || `exit ${read.code}`;
119
- sources.push({ source: "macos_keychain", status: "missing", reason: `no readable '${CLAUDE_KEYCHAIN_SERVICE}' item (${detail})` });
120
- }
121
- else {
127
+ // Claude Code (and the HQ desktop sign-in, which runs `claude auth login`)
128
+ // writes its login under the login user's account name. Another item with
129
+ // the same service can exist under a different account (an old one written
130
+ // as "unknown", or one holding only MCP OAuth), and an unscoped read
131
+ // returns whichever the Keychain finds first. Ask for the user's item
132
+ // first, then fall back to any item for the service.
133
+ const readKeychain = deps.readKeychain ?? readKeychainWithSecurity;
134
+ const username = deps.username === undefined ? safeUsername() : deps.username;
135
+ const recordOf = (result) => {
136
+ if (result.code !== 0)
137
+ return null;
122
138
  let payload;
123
139
  try {
124
- payload = JSON.parse(read.stdout.trim());
140
+ payload = JSON.parse(result.stdout.trim());
125
141
  }
126
142
  catch {
127
143
  payload = null;
128
144
  }
129
- const record = payload && typeof payload === "object" ? oauthRecord(payload.claudeAiOauth) : null;
130
- if (record) {
131
- const described = describeRecord(record, now);
132
- sources.push({ source: "macos_keychain", status: described.status, reason: described.reason });
133
- if (described.usable)
134
- found("macos_keychain");
145
+ return payload && typeof payload === "object" ? oauthRecord(payload.claudeAiOauth) : null;
146
+ };
147
+ const scoped = username ? readKeychain(username) : null;
148
+ const scopedRecord = scoped ? recordOf(scoped) : null;
149
+ let read;
150
+ let record;
151
+ if (scoped && scopedRecord) {
152
+ read = scoped;
153
+ record = scopedRecord;
154
+ }
155
+ else {
156
+ const any = readKeychain();
157
+ const anyRecord = recordOf(any);
158
+ if (anyRecord || !scoped || scoped.code !== 0) {
159
+ read = any;
160
+ record = anyRecord;
135
161
  }
136
162
  else {
137
- sources.push({ source: "macos_keychain", status: "missing", reason: "keychain item has no claudeAiOauth access token" });
163
+ read = scoped;
164
+ record = null;
138
165
  }
139
166
  }
167
+ if (read.code !== 0) {
168
+ const detail = read.stderr.replace(/\s+/g, " ").trim().slice(0, 200) || `exit ${read.code}`;
169
+ sources.push({ source: "macos_keychain", status: "missing", reason: `no readable '${CLAUDE_KEYCHAIN_SERVICE}' item (${detail})` });
170
+ }
171
+ else if (record) {
172
+ const described = describeRecord(record, now);
173
+ sources.push({ source: "macos_keychain", status: described.status, reason: described.reason });
174
+ if (described.usable)
175
+ found("macos_keychain");
176
+ }
177
+ else {
178
+ sources.push({ source: "macos_keychain", status: "missing", reason: "keychain item has no claudeAiOauth access token" });
179
+ }
140
180
  }
141
181
  return { signedIn: via !== null, via, sources };
142
182
  }
@@ -1,8 +1,21 @@
1
1
  import { type BotConfig } from "./config.js";
2
2
  export declare function executiveEnabled(home?: string): boolean;
3
+ /**
4
+ * Identity only: whether this bot is the Executive bot on this computer (the
5
+ * one resolver, lib/bot/executive.ts: chosen with hq bot eb, else the earliest
6
+ * personal bot). It never turns an Executive feature on; the daily
7
+ * hot-channel sync follows it for every user, opted in or not.
8
+ */
9
+ export declare function isExecutiveIdentity(config: Pick<BotConfig, "name" | "kind" | "workerId">, home?: string): boolean;
10
+ /**
11
+ * Feature gate: whether this bot runs the Executive features (meeting rider,
12
+ * meeting detection, signal-to-lane, source report DMs). Requires BOTH the
13
+ * opt-in (executive.enabled === true) and the Executive identity.
14
+ */
3
15
  export declare function isExecutiveBot(config: Pick<BotConfig, "name" | "kind" | "workerId">, home?: string): boolean;
4
16
  export declare function executiveStatus(config: Pick<BotConfig, "name" | "kind" | "workerId">, dir: string, home?: string): {
5
17
  is_executive: boolean;
18
+ executive_identity: boolean;
6
19
  rider_enabled: boolean;
7
20
  detect_source_last: string | null;
8
21
  last_detected_at: string | null;
@@ -12,6 +12,7 @@ import * as path from "node:path";
12
12
  import * as os from "node:os";
13
13
  import { effectiveBotKind } from "./config.js";
14
14
  import { tailBotEvents } from "./events.js";
15
+ import { isExecutiveBotName } from "./executive.js";
15
16
  export function executiveEnabled(home = os.homedir()) {
16
17
  try {
17
18
  const settings = JSON.parse(fs.readFileSync(path.join(home, ".hq/menubar.json"), "utf8"));
@@ -21,30 +22,32 @@ export function executiveEnabled(home = os.homedir()) {
21
22
  return false;
22
23
  }
23
24
  }
24
- export function isExecutiveBot(config, home = os.homedir()) {
25
+ /**
26
+ * Identity only: whether this bot is the Executive bot on this computer (the
27
+ * one resolver, lib/bot/executive.ts: chosen with hq bot eb, else the earliest
28
+ * personal bot). It never turns an Executive feature on; the daily
29
+ * hot-channel sync follows it for every user, opted in or not.
30
+ */
31
+ export function isExecutiveIdentity(config, home) {
25
32
  if (effectiveBotKind(config) !== "personal")
26
33
  return false;
34
+ // No explicit home: the resolver's own defaults (the real home, HQ_BOTS_ROOT and HQ_EXECUTIVE_FILE honored).
35
+ return isExecutiveBotName(config.name, home ? { home } : {});
36
+ }
37
+ /**
38
+ * Feature gate: whether this bot runs the Executive features (meeting rider,
39
+ * meeting detection, signal-to-lane, source report DMs). Requires BOTH the
40
+ * opt-in (executive.enabled === true) and the Executive identity.
41
+ */
42
+ export function isExecutiveBot(config, home) {
27
43
  if (!executiveEnabled(home))
28
44
  return false;
29
- let name = "setup";
30
- try {
31
- const value = JSON.parse(fs.readFileSync(path.join(home, ".hq/executive.json"), "utf8"));
32
- if (value?.bot != null) {
33
- if (typeof value.bot !== "string" || !value.bot.trim())
34
- return false;
35
- name = value.bot;
36
- }
37
- }
38
- catch (err) {
39
- if (err.code !== "ENOENT")
40
- return false;
41
- }
42
- return config.name === name;
45
+ return isExecutiveIdentity(config, home);
43
46
  }
44
- export function executiveStatus(config, dir, home = os.homedir()) {
47
+ export function executiveStatus(config, dir, home) {
45
48
  const last = tailBotEvents(dir, (event) => event.event === "meeting.detected").at(-1);
46
49
  return {
47
- is_executive: isExecutiveBot(config, home), rider_enabled: executiveEnabled(home),
50
+ is_executive: isExecutiveBot(config, home), executive_identity: isExecutiveIdentity(config, home), rider_enabled: executiveEnabled(home),
48
51
  // The first desktop producer did not set source.
49
52
  detect_source_last: last ? (last.payload.source === "poll" ? "poll" : "desktop") : null,
50
53
  last_detected_at: last?.at ?? null,
@@ -0,0 +1,12 @@
1
+ import type { ExecutiveBot } from "./executive.js";
2
+ import { type FleetCronJob } from "./fleet-cron.js";
3
+ /**
4
+ * Companies the Executive bot actually covers for the daily hot-channel sync.
5
+ * A local job counts only while `hq bot list` would show this bot running:
6
+ * jobs.json has no enabled flag, and a bot that ran once then stopped leaves
7
+ * the job behind. An enabled HQ Fleet job still counts when the local process
8
+ * is stopped. Registration markers, and a Fleet list that cannot be read, are
9
+ * not coverage.
10
+ */
11
+ export declare function executiveHotSignalSyncCompanies(bot: ExecutiveBot, listFleet?: (agentUid: string) => FleetCronJob[]): string[];
12
+ //# sourceMappingURL=executive-sync.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { readLocalJobs } from "./local-jobs.js";
2
+ import { hotSignalSyncJobCompany } from "./jobs/hot-signal-sync.js";
3
+ import { companyOfHotSignalSyncJob, fleetCronOps } from "./fleet-cron.js";
4
+ import { readBotListedProcess } from "./listed-running.js";
5
+ /**
6
+ * Companies the Executive bot actually covers for the daily hot-channel sync.
7
+ * A local job counts only while `hq bot list` would show this bot running:
8
+ * jobs.json has no enabled flag, and a bot that ran once then stopped leaves
9
+ * the job behind. An enabled HQ Fleet job still counts when the local process
10
+ * is stopped. Registration markers, and a Fleet list that cannot be read, are
11
+ * not coverage.
12
+ */
13
+ export function executiveHotSignalSyncCompanies(bot, listFleet = (uid) => fleetCronOps(uid).list()) {
14
+ const companies = new Set();
15
+ if (readBotListedProcess(bot.dir, bot.config).running) {
16
+ for (const job of readLocalJobs(bot.dir)) {
17
+ const company = hotSignalSyncJobCompany(job.context);
18
+ if (company)
19
+ companies.add(company);
20
+ }
21
+ }
22
+ if (bot.config.agentUid) {
23
+ try {
24
+ for (const job of listFleet(bot.config.agentUid)) {
25
+ const company = companyOfHotSignalSyncJob(job);
26
+ if (company && job.enabled !== false)
27
+ companies.add(company);
28
+ }
29
+ }
30
+ catch {
31
+ // No readable Fleet schedule is not evidence of a replacement job.
32
+ }
33
+ }
34
+ return [...companies];
35
+ }
36
+ //# sourceMappingURL=executive-sync.js.map
@@ -0,0 +1,51 @@
1
+ import { type BotConfig, type BotRuntimeId } from "./config.js";
2
+ export declare const EXECUTIVE_FILE_REL: string;
3
+ export type ExecutiveBotSource = "chosen" | "default";
4
+ export interface ExecutiveBot {
5
+ name: string;
6
+ source: ExecutiveBotSource;
7
+ config: BotConfig;
8
+ /** ~/.hq/bots/<name> */
9
+ dir: string;
10
+ }
11
+ export interface ExecutiveChoice {
12
+ bot: string;
13
+ setAt?: string;
14
+ }
15
+ export interface PersonalBotEntry {
16
+ name: string;
17
+ dir: string;
18
+ config: BotConfig;
19
+ createdAtMs: number;
20
+ }
21
+ export interface SetExecutiveBotResult {
22
+ name: string;
23
+ source: "chosen";
24
+ runtime: BotRuntimeId;
25
+ /** The effective Executive bot is a different bot than before the set. */
26
+ changed: boolean;
27
+ }
28
+ /** Where the store and the bots live. Defaults: the real home and ~/.hq/bots (HQ_BOTS_ROOT honored). */
29
+ export interface ExecutiveLocations {
30
+ home?: string;
31
+ /** The bots root; default botsRoot(home). */
32
+ root?: string;
33
+ env?: NodeJS.ProcessEnv;
34
+ }
35
+ /** ~/.hq/executive.json. With no explicit home, HQ_EXECUTIVE_FILE overrides the path (tests). */
36
+ export declare function executiveFilePath(home?: string, env?: NodeJS.ProcessEnv): string;
37
+ /** The stored choice, or null when the file is missing or does not name a bot. */
38
+ export declare function readExecutiveChoice(opts?: ExecutiveLocations): ExecutiveChoice | null;
39
+ export declare function writeExecutiveChoice(name: string, opts?: ExecutiveLocations, now?: Date): ExecutiveChoice;
40
+ /** Every personal bot set up here, earliest created first (name order breaks ties). */
41
+ export declare function listPersonalBots(opts?: ExecutiveLocations): PersonalBotEntry[];
42
+ export declare function resolveExecutiveBot(opts?: ExecutiveLocations): ExecutiveBot | null;
43
+ export declare function isExecutiveBotName(name: string, opts?: ExecutiveLocations): boolean;
44
+ /**
45
+ * Make `name` the Executive bot. The bot must be set up on this computer and
46
+ * be a personal bot; a company bot is refused.
47
+ */
48
+ export declare function setExecutiveBot(name: string, opts?: ExecutiveLocations, now?: Date): SetExecutiveBotResult;
49
+ /** One plain sentence saying how the Executive bot was decided. */
50
+ export declare function describeExecutiveBotSource(bot: ExecutiveBot | null): string;
51
+ //# sourceMappingURL=executive.d.ts.map