@indigoai-us/hq-cli 5.345.219 → 5.345.220

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 (88) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/command-catalog.generated.d.ts +25 -1
  3. package/dist/command-catalog.generated.js +31 -1
  4. package/dist/commands/bot.d.ts +48 -0
  5. package/dist/commands/bot.js +108 -8
  6. package/dist/commands/cloud.d.ts +16 -0
  7. package/dist/commands/cloud.js +112 -102
  8. package/dist/commands/core-checkpoint-native.d.ts +13 -0
  9. package/dist/commands/core-checkpoint-native.js +167 -52
  10. package/dist/commands/core-hook-registration-plan.js +5 -4
  11. package/dist/commands/daemon.js +21 -2
  12. package/dist/commands/integrations.js +84 -3
  13. package/dist/commands/packs.js +23 -0
  14. package/dist/commands/pkg-update.d.ts +6 -0
  15. package/dist/commands/pkg-update.js +15 -7
  16. package/dist/commands/run.js +55 -45
  17. package/dist/commands/sources.js +3 -2
  18. package/dist/lib/bot/fleet-cron.js +5 -2
  19. package/dist/lib/bot/inflight.d.ts +9 -0
  20. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +51 -0
  21. package/dist/lib/bot/jobs/hot-signal-sync.js +90 -9
  22. package/dist/lib/bot/run.d.ts +29 -5
  23. package/dist/lib/bot/run.js +203 -1
  24. package/dist/lib/bot/signals-try-now.d.ts +76 -0
  25. package/dist/lib/bot/signals-try-now.js +111 -0
  26. package/dist/lib/capacity/collectors/claude-oauth.d.ts +22 -3
  27. package/dist/lib/capacity/collectors/claude-oauth.js +78 -22
  28. package/dist/lib/capacity/scheduler.d.ts +8 -0
  29. package/dist/lib/capacity/scheduler.js +5 -2
  30. package/dist/lib/daemon/run.js +5 -0
  31. package/dist/lib/daemon/runtime-notifications.d.ts +7 -0
  32. package/dist/lib/daemon/runtime-notifications.js +50 -0
  33. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +9 -1
  34. package/dist/lib/doctor/checks/fleet-hook-core.js +39 -15
  35. package/dist/lib/hook-engine/fleet-registration.d.ts +17 -5
  36. package/dist/lib/hook-engine/fleet-registration.js +53 -17
  37. package/dist/lib/hot-channels/alert.d.ts +10 -1
  38. package/dist/lib/hot-channels/alert.js +34 -7
  39. package/dist/lib/hot-channels/signals-claude-login.d.ts +53 -0
  40. package/dist/lib/hot-channels/signals-claude-login.js +96 -0
  41. package/dist/lib/hot-channels/signals-pass.d.ts +17 -0
  42. package/dist/lib/hot-channels/signals-pass.js +31 -3
  43. package/dist/lib/search-index/index.js +11 -1
  44. package/dist/lib/signals/engine.d.ts +1 -0
  45. package/dist/lib/signals/engine.js +7 -0
  46. package/dist/lib/signals/reply.d.ts +48 -0
  47. package/dist/lib/signals/reply.js +72 -11
  48. package/dist/lib/signals/steps/adapters.js +6 -0
  49. package/dist/lib/signals/steps/extract.d.ts +50 -3
  50. package/dist/lib/signals/steps/extract.js +100 -17
  51. package/dist/lib/signals/steps/types.d.ts +19 -0
  52. package/dist/lib/sync-core/engine-home.d.ts +6 -1
  53. package/dist/lib/sync-core/engine-home.js +13 -3
  54. package/dist/lib/sync-core/reconcile.js +1 -1
  55. package/dist/lib/sync-core/release-compare.d.ts +7 -0
  56. package/dist/lib/sync-core/release-compare.js +16 -0
  57. package/dist/lib/sync-core/release.d.ts +2 -1
  58. package/dist/lib/sync-core/release.js +2 -10
  59. package/dist/run/schema-env-overrides.d.ts +24 -0
  60. package/dist/run/schema-env-overrides.js +72 -0
  61. package/dist/utils/host-registration.d.ts +1 -1
  62. package/dist/utils/host-registration.js +4 -0
  63. package/package.json +13 -9
  64. package/scripts/check-function-manifest.mjs +5 -4
  65. package/dist/commands/__fixtures__/access-vault.d.ts +0 -95
  66. package/dist/commands/__fixtures__/access-vault.js +0 -166
  67. package/dist/commands/__fixtures__/make-tar.d.ts +0 -38
  68. package/dist/commands/__fixtures__/make-tar.js +0 -102
  69. package/dist/commands/secrets-public-types.test-d.d.ts +0 -2
  70. package/dist/commands/secrets-public-types.test-d.js +0 -18
  71. package/dist/lib/decisions/fixtures/us001.d.ts +0 -137
  72. package/dist/lib/decisions/fixtures/us001.js +0 -21
  73. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +0 -226
  74. package/dist/lib/doctor/__testing__/fake-hq-tree.js +0 -408
  75. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  76. package/dist/lib/doctor/__testing__/run-doctor.js +0 -69
  77. package/dist/lib/fingerprint/fixtures.d.ts +0 -19
  78. package/dist/lib/fingerprint/fixtures.js +0 -61
  79. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.d.ts +0 -33
  80. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.js +0 -53
  81. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.d.ts +0 -38
  82. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.js +0 -64
  83. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  84. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  85. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  86. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  87. package/scripts/hook-engine-manifest.mjs +0 -22
  88. package/scripts/mesh-daemon-if-stale.mjs +0 -20
@@ -68,7 +68,11 @@ export const CLAUDE_OAUTH_REFRESH_BACKOFF_MS = 10 * 60 * 1000;
68
68
  export const CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS = 60 * 60 * 1000;
69
69
  /** Try a refresh when the token is this close to expiry, so one tick does not land on a stale token. */
70
70
  export const CLAUDE_OAUTH_REFRESH_PREFLIGHT_MS = 10 * 60 * 1000;
71
- export const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 10_000;
71
+ /**
72
+ * Claude refresh tokens are single use. A refresh the server completed but whose
73
+ * response we abandoned leaves the stored token dead, so this limit is generous.
74
+ */
75
+ export const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 30_000;
72
76
  export const CLAUDE_OAUTH_REFRESH_LAST_FILE = "claude-oauth-refresh-last.json";
73
77
  const SESSION_MINUTES = 5 * 60;
74
78
  const WEEKLY_MINUTES = 7 * 24 * 60;
@@ -1718,6 +1722,7 @@ const defaultWriteClaudeCredentials = async (request) => {
1718
1722
  // the item so the write uses the SAME selector and does not create a second entry.
1719
1723
  let selector = null;
1720
1724
  let preRead = spawnSync("security", ["find-generic-password", "-s", request.service, "-a", username, "-w"], spawnOpts);
1725
+ const firstReadStatus = preRead.status;
1721
1726
  if (preRead.status === 0) {
1722
1727
  selector = "sa";
1723
1728
  }
@@ -1744,8 +1749,15 @@ const defaultWriteClaudeCredentials = async (request) => {
1744
1749
  return { ok: false, raceDetected: true };
1745
1750
  }
1746
1751
  }
1752
+ else if (firstReadStatus === 44 && preRead.status === 44) {
1753
+ // Both selectors confirmed the item does not exist (exit 44), so there is
1754
+ // nothing to race with or duplicate. The endpoint has already rotated the
1755
+ // refresh token; writing it keeps the only valid token instead of losing it.
1756
+ selector = "sa";
1757
+ }
1747
1758
  else if (request.previousRefreshToken) {
1748
- // Fail closed: a refresh race check needs a readable prior item.
1759
+ // Unreadable for another reason (timeout, prompt, locked Keychain). Writing
1760
+ // blind could duplicate the item or clobber a newer token, so fail closed.
1749
1761
  return { ok: false, raceDetected: true };
1750
1762
  }
1751
1763
  const body = JSON.stringify(request.document);
@@ -1800,6 +1812,49 @@ const defaultWriteClaudeCredentials = async (request) => {
1800
1812
  return { ok: false, error: message };
1801
1813
  }
1802
1814
  };
1815
+ function refreshTokenFromDocumentText(text) {
1816
+ let parsed;
1817
+ try {
1818
+ parsed = JSON.parse(text.replace(/\n$/, ""));
1819
+ }
1820
+ catch {
1821
+ // Unparseable item: report it as unreadable so the caller does not act on it.
1822
+ return undefined;
1823
+ }
1824
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1825
+ return undefined;
1826
+ const oauth = parsed.claudeAiOauth;
1827
+ if (!oauth || typeof oauth !== "object" || Array.isArray(oauth))
1828
+ return null;
1829
+ const record = oauth;
1830
+ if (typeof record.refreshToken === "string")
1831
+ return record.refreshToken;
1832
+ if (typeof record.refresh_token === "string")
1833
+ return record.refresh_token;
1834
+ return null;
1835
+ }
1836
+ const defaultReadStoredRefreshToken = (request) => {
1837
+ if (request.platform === "darwin") {
1838
+ const username = os.userInfo().username;
1839
+ const spawnOpts = { encoding: "utf8", timeout: CLAUDE_OAUTH_SECURITY_TIMEOUT_MS, windowsHide: true };
1840
+ for (const args of [
1841
+ ["find-generic-password", "-s", request.service, "-a", username, "-w"],
1842
+ ["find-generic-password", "-s", request.service, "-w"],
1843
+ ]) {
1844
+ const read = spawnSync("security", args, spawnOpts);
1845
+ if (read.status === 0 && typeof read.stdout === "string")
1846
+ return refreshTokenFromDocumentText(read.stdout);
1847
+ }
1848
+ return undefined;
1849
+ }
1850
+ try {
1851
+ return refreshTokenFromDocumentText(fs.readFileSync(path.join(request.home, ".credentials.json"), "utf8"));
1852
+ }
1853
+ catch {
1854
+ // Missing or unreadable file: unknown, so the caller keeps its own judgement.
1855
+ return undefined;
1856
+ }
1857
+ };
1803
1858
  const HQ_CLI_PACKAGE_NAME = "@indigoai-us/hq-cli";
1804
1859
  const LOADER_FLAGS_WITH_VALUE = new Set(["--import", "--loader", "--experimental-loader", "--require", "-r", "--conditions", "-C"]);
1805
1860
  const LOADER_FLAGS_BARE = new Set(["--experimental-strip-types", "--experimental-transform-types"]);
@@ -2290,8 +2345,6 @@ async function attemptClaudeTokenRefresh(ctx) {
2290
2345
  }
2291
2346
  const resolvedHome = path.resolve(ctx.home);
2292
2347
  const targetHome = canonicalHomePath(ctx.home) ?? resolvedHome;
2293
- // Exact match, for the auth-failed short circuit, which records the home as revoked.
2294
- const sameHome = (candidate) => typeof candidate === "string" && candidate.length > 0 && canonicalHomePath(candidate) === targetHome;
2295
2348
  // Blocking match: a path that cannot be resolved might be this home, so it blocks.
2296
2349
  const mayHoldHome = (candidate) => {
2297
2350
  if (typeof candidate !== "string" || candidate.length === 0)
@@ -2299,24 +2352,11 @@ async function attemptClaudeTokenRefresh(ctx) {
2299
2352
  const canonical = canonicalHomePath(candidate);
2300
2353
  return canonical === null || canonical === targetHome;
2301
2354
  };
2302
- // Addendum 1: if the lane watcher classified a 401/403 on this home as
2303
- // provider_auth_failed, treat the account as already signed out and record
2304
- // revoked immediately. No token endpoint call, no response body stored.
2305
- const authFailedHere = liveLanes.find((lane) => lane.isAuthFailed && sameHome(lane.home));
2306
- if (authFailedHere) {
2307
- const fingerprint = tokenFingerprint(ctx.refreshToken);
2308
- const now = new Date(ctx.nowMs).toISOString();
2309
- recordRefresh(ctx.root, key, {
2310
- attemptedAt: now,
2311
- outcome: "revoked",
2312
- errorClass: "revoked",
2313
- revokedRefreshTokenFingerprint: fingerprint,
2314
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS).toISOString(),
2315
- }, (file) => {
2316
- file.revokedTokens[fingerprint] = now;
2317
- });
2318
- return { outcome: "revoked", errorClass: "revoked" };
2319
- }
2355
+ // A finished lane that ended with provider_auth_failed on this home is NOT
2356
+ // proof that the refresh token stored now is dead: the lane may have failed
2357
+ // on an older token, or on an access token that a refresh would renew.
2358
+ // Marking the current token revoked from that signal signed fresh sign-ins
2359
+ // out. Only the token endpoint's own answer below decides revoked.
2320
2360
  if (liveLanes.some((lane) => lane.isLive && mayHoldHome(lane.home))) {
2321
2361
  recordRefresh(ctx.root, key, { attemptedAt: new Date(ctx.nowMs).toISOString(), outcome: "skipped-live" });
2322
2362
  return { outcome: "skipped-live" };
@@ -2426,6 +2466,20 @@ async function attemptClaudeTokenRefresh(ctx) {
2426
2466
  || /\b(revoked|invalid)\b/.test(errField)
2427
2467
  || /\b(revoked|invalid)\b/.test(descField);
2428
2468
  if (revokedHit) {
2469
+ // Another process (Claude Code, a lane) may have rotated the token between
2470
+ // our read and this POST. Then our copy is stale, not the account.
2471
+ const service = ctx.service || claudeKeychainServiceName(ctx.home);
2472
+ const stored = ctx.readStoredRefreshToken({ home: ctx.home, service, platform: ctx.platform });
2473
+ if (typeof stored === "string" && stored.length > 0 && stored !== ctx.refreshToken) {
2474
+ // Back off so a store that keeps disagreeing with the read path cannot make
2475
+ // the collector POST a dead token every tick without ever deciding.
2476
+ recordRefresh(ctx.root, key, {
2477
+ attemptedAt: new Date(ctx.nowMs).toISOString(),
2478
+ outcome: "skipped-race",
2479
+ backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2480
+ });
2481
+ return { outcome: "skipped-race" };
2482
+ }
2429
2483
  const fingerprint = tokenFingerprint(ctx.refreshToken);
2430
2484
  const now = new Date(ctx.nowMs).toISOString();
2431
2485
  const errorClass = errField === "invalid_grant" ? "invalid_grant" : "revoked";
@@ -2588,7 +2642,9 @@ async function maybeRefreshAccount(params) {
2588
2642
  const tokenEndpoint = options.tokenEndpoint ?? CLAUDE_OAUTH_REFRESH_URL;
2589
2643
  const listLiveLanes = options.listLiveLanes ?? defaultListLiveLanes;
2590
2644
  const listProcesses = options.listProcesses ?? defaultListProcesses;
2645
+ const readStoredRefreshToken = options.readStoredRefreshToken ?? defaultReadStoredRefreshToken;
2591
2646
  return attemptClaudeTokenRefresh({
2647
+ readStoredRefreshToken,
2592
2648
  root,
2593
2649
  home,
2594
2650
  service,
@@ -7,6 +7,14 @@ export declare const REBUILD_TICK_MS = 60000;
7
7
  export declare const POLL_TICK_MS: number;
8
8
  export declare const CODEX_DIR_POLL_MS = 15000;
9
9
  export declare const SPOOL_POLL_MS = 15000;
10
+ export declare const RUN_TIMEOUT_MS: {
11
+ readonly "codex-tail": 15000;
12
+ readonly "codex-app-server": 30000;
13
+ readonly "claude-statusline": 10000;
14
+ readonly "claude-oauth": 180000;
15
+ readonly grok: 30000;
16
+ readonly rebuild: 10000;
17
+ };
10
18
  export interface CapacityTimers {
11
19
  setTimeout(fn: () => void, ms: number): unknown;
12
20
  clearTimeout(handle: unknown): void;
@@ -22,11 +22,14 @@ export const REBUILD_TICK_MS = 60_000;
22
22
  export const POLL_TICK_MS = 5 * 60_000;
23
23
  export const CODEX_DIR_POLL_MS = 15_000;
24
24
  export const SPOOL_POLL_MS = 15_000;
25
- const RUN_TIMEOUT_MS = {
25
+ export const RUN_TIMEOUT_MS = {
26
26
  "codex-tail": 15_000,
27
27
  "codex-app-server": 30_000,
28
28
  "claude-statusline": 10_000,
29
- "claude-oauth": 30_000,
29
+ // Must stay well above CLAUDE_OAUTH_REFRESH_TIMEOUT_MS plus Keychain reads. A run
30
+ // marked timed out keeps going, so a short budget lets a second run POST the same
31
+ // single-use refresh token and get the account marked revoked.
32
+ "claude-oauth": 180_000,
30
33
  grok: 30_000,
31
34
  rebuild: 10_000,
32
35
  };
@@ -15,6 +15,7 @@ import { loadCachedTokens } from "@indigoai-us/hq-cloud";
15
15
  import { CLI_VERSION } from "../../cli-version.js";
16
16
  import { anywhereRuntimeEnabled } from "../../commands/anywhere-runtime-flag.js";
17
17
  import { anywhereRuntimeAllowed, readHqAnywherePersonSetting, stickyPersonSettingReader } from "../anywhere-person-setting.js";
18
+ import { watchRuntimeInputs } from "./runtime-notifications.js";
18
19
  import { currentPackageUseLeaseInstall, currentPackageUseUpdateRequested } from "../../utils/package-use-lease.js";
19
20
  import { isLocalDependencyInstall, resolveRunningInstall } from "../../utils/version-gate.js";
20
21
  import { agentKitPaths } from "../agent-kit/paths.js";
@@ -1535,7 +1536,11 @@ export async function runDaemon(opts) {
1535
1536
  subscribe: (notify) => hqdRuntimeEvents.subscribe(notify),
1536
1537
  log: (error) => log("error", `hqd socket listener update failed: ${error.message ?? String(error)}`),
1537
1538
  });
1539
+ // A sign-in or daemon config change can flip the hqd gate before the next
1540
+ // shared read; the watch wakes the listener so it checks now.
1541
+ const stopHqdInputWatch = watchRuntimeInputs([paths.configPath, path.join(home, ".hq", "cognito-tokens.json")], () => hqdRuntimeEvents.emit(), (error) => log("warn", `hqd runtime input watch failed: ${error instanceof Error ? error.name : "UnknownError"}`));
1538
1542
  const closeHqd = () => {
1543
+ stopHqdInputWatch();
1539
1544
  void hqdListener.close().catch((err) => log("warn", `hqd socket did not close cleanly: ${err.message}`));
1540
1545
  };
1541
1546
  return await new Promise((resolve) => {
@@ -0,0 +1,7 @@
1
+ /** Watch the directories of the given files, so atomic replacement is seen.
2
+ * The interval only re-arms a watch that failed or whose directory did not
3
+ * exist yet; a newly armed watch reports a change, since the file may have
4
+ * appeared unseen. Missed events are covered by the hqd listener's own rare
5
+ * fallback check (anywhere-listener.ts), not here. */
6
+ export declare function watchRuntimeInputs(files: readonly string[], changed: () => void, onError: (error: unknown) => void, intervalMs?: number): () => void;
7
+ //# sourceMappingURL=runtime-notifications.d.ts.map
@@ -0,0 +1,50 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ /** Watch the directories of the given files, so atomic replacement is seen.
4
+ * The interval only re-arms a watch that failed or whose directory did not
5
+ * exist yet; a newly armed watch reports a change, since the file may have
6
+ * appeared unseen. Missed events are covered by the hqd listener's own rare
7
+ * fallback check (anywhere-listener.ts), not here. */
8
+ export function watchRuntimeInputs(files, changed, onError, intervalMs = 60_000) {
9
+ const watched = new Map();
10
+ const directories = [...new Set(files.map((file) => path.dirname(file)))];
11
+ let closed = false;
12
+ const arm = () => {
13
+ let armed = false;
14
+ for (const directory of directories) {
15
+ if (watched.has(directory))
16
+ continue;
17
+ try {
18
+ const watcher = fs.watch(directory, { persistent: false }, (_event, filename) => {
19
+ if (!filename || files.some((file) => path.dirname(file) === directory && path.basename(file) === filename.toString()))
20
+ changed();
21
+ });
22
+ watcher.on("error", (error) => {
23
+ watcher.close();
24
+ watched.delete(directory);
25
+ onError(error);
26
+ });
27
+ watcher.on("close", () => { watched.delete(directory); });
28
+ watched.set(directory, watcher);
29
+ armed = true;
30
+ }
31
+ catch (error) {
32
+ if (error.code !== "ENOENT")
33
+ onError(error);
34
+ }
35
+ }
36
+ return armed;
37
+ };
38
+ arm();
39
+ const timer = setInterval(() => { if (!closed && arm())
40
+ changed(); }, intervalMs);
41
+ timer.unref();
42
+ return () => {
43
+ closed = true;
44
+ clearInterval(timer);
45
+ for (const watcher of watched.values())
46
+ watcher.close();
47
+ watched.clear();
48
+ };
49
+ }
50
+ //# sourceMappingURL=runtime-notifications.js.map
@@ -1,4 +1,12 @@
1
1
  import { type EngineCapabilities } from '../../../utils/host-registration.js';
2
+ import { type FleetHost } from '../../hook-engine/fleet-registration.js';
2
3
  import type { CheckResult } from '../types.js';
3
- export declare function fleetHookCoreResults(home: string, env: NodeJS.ProcessEnv, inspect?: (engine: string) => EngineCapabilities): CheckResult[];
4
+ /**
5
+ * One result per hq-fleet profile: per event, which core the bot runtime uses
6
+ * (`native`, `shell`, or `shell fallback` under a kill switch) and on which
7
+ * host (`fleet-local` or `agents-v2`). A native entry passes only when the
8
+ * engine advertises its host and covers every old hook for the event, and its
9
+ * fallback is that host's exact adapter command.
10
+ */
11
+ export declare function fleetHookCoreResults(home: string, env: NodeJS.ProcessEnv, inspect?: (engine: string, host: FleetHost) => EngineCapabilities): CheckResult[];
4
12
  //# sourceMappingURL=fleet-hook-core.d.ts.map
@@ -3,9 +3,26 @@ import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { load } from 'js-yaml';
5
5
  import { coreNextKillReason, missingEvaluators } from '../../../utils/host-registration.js';
6
- import { FLEET_EVENTS, literalArgv, fallbackProblem, inspectFleetEngine } from '../../hook-engine/fleet-registration.js';
6
+ import { FLEET_ADAPTERS, FLEET_EVENTS, isFleetHost, literalArgv, fallbackProblem, inspectFleetEngine } from '../../hook-engine/fleet-registration.js';
7
7
  import { uncoveredHooks } from '../../hook-engine/coverage.js';
8
- export function fleetHookCoreResults(home, env, inspect = (engine) => inspectFleetEngine(engine, home)) {
8
+ /** The Fleet host whose shell adapter `argv` runs, if any. */
9
+ function shellHost(argv) {
10
+ if (argv[1] === 'run')
11
+ return undefined;
12
+ for (const host of Object.keys(FLEET_ADAPTERS)) {
13
+ if (argv.some(arg => path.basename(arg) === FLEET_ADAPTERS[host]))
14
+ return host;
15
+ }
16
+ return undefined;
17
+ }
18
+ /**
19
+ * One result per hq-fleet profile: per event, which core the bot runtime uses
20
+ * (`native`, `shell`, or `shell fallback` under a kill switch) and on which
21
+ * host (`fleet-local` or `agents-v2`). A native entry passes only when the
22
+ * engine advertises its host and covers every old hook for the event, and its
23
+ * fallback is that host's exact adapter command.
24
+ */
25
+ export function fleetHookCoreResults(home, env, inspect = (engine, host) => inspectFleetEngine(engine, home, undefined, undefined, undefined, host)) {
9
26
  const base = env.HQ_FLEET_HOME?.trim() || path.join(home, '.hq-fleet');
10
27
  let profiles;
11
28
  if (fs.existsSync(path.join(base, 'config.yaml')))
@@ -28,23 +45,29 @@ export function fleetHookCoreResults(home, env, inspect = (engine) => inspectFle
28
45
  continue;
29
46
  const document = load(fs.readFileSync(file, 'utf8'));
30
47
  const cores = {};
48
+ const hosts = {};
31
49
  const problems = [];
32
50
  for (const [event, entries] of Object.entries(document?.hooks ?? {})) {
33
51
  if (!Array.isArray(entries))
34
52
  continue;
35
53
  const commands = entries.map(entry => literalArgv(String(entry?.command ?? ''))).filter((argv) => argv !== null);
36
- const native = commands.filter(argv => path.basename(argv[0] ?? '') === 'hq-hook' && argv[1] === 'run' && argv[2] === '--host' && ['fleet-local', 'agents-v2'].includes(argv[3] ?? ''));
37
- const shell = commands.filter(argv => argv.some(arg => path.basename(arg) === 'hq-fleet-local-hook-adapter.sh') && argv[1] !== 'run');
54
+ const native = commands.filter(argv => path.basename(argv[0] ?? '') === 'hq-hook' && argv[1] === 'run' && argv[2] === '--host' && isFleetHost(argv[3]));
55
+ const shell = commands.filter(argv => shellHost(argv) !== undefined);
38
56
  if (!native.length && !shell.length)
39
57
  continue;
40
58
  cores[event] = native.length ? 'native' : 'shell';
41
- if (native.length && (shell.length || native.length > 1))
59
+ const seen = [...new Set([...native.map(argv => argv[3]), ...shell.map(argv => shellHost(argv))])];
60
+ hosts[event] = seen[0];
61
+ // fleet-local keeps its rule (a native entry alongside any other); any
62
+ // second entry where agents-v2 is involved is a duplicate too, so a
63
+ // toggle that leaves two adapter entries fails.
64
+ const duplicate = native.length ? shell.length > 0 || native.length > 1 : seen.includes('agents-v2') && shell.length > 1;
65
+ if (duplicate)
42
66
  problems.push(`${event}: duplicate hook registrations`);
67
+ if (seen.length > 1)
68
+ problems.push(`${event}: registrations for more than one fleet host (${seen.join(', ')})`);
43
69
  for (const argv of native) {
44
- if (argv[3] === 'agents-v2') {
45
- problems.push(`${event}: agents-v2 native registration is unsupported`);
46
- continue;
47
- }
70
+ const host = argv[3];
48
71
  const value = (flag) => { const index = argv.indexOf(flag); return index < 0 ? undefined : argv[index + 1]; };
49
72
  const killed = coreNextKillReason(home, env);
50
73
  if (killed) {
@@ -58,7 +81,7 @@ export function fleetHookCoreResults(home, env, inspect = (engine) => inspectFle
58
81
  catch {
59
82
  fallback = null;
60
83
  }
61
- const invalid = fallbackProblem(fallback);
84
+ const invalid = fallbackProblem(fallback, host, event);
62
85
  if (invalid)
63
86
  problems.push(`${event}: ${invalid}`);
64
87
  if (argv[4] !== event || !path.isAbsolute(value('--hq-root') ?? '')) {
@@ -66,15 +89,16 @@ export function fleetHookCoreResults(home, env, inspect = (engine) => inspectFle
66
89
  continue;
67
90
  }
68
91
  const engine = argv[0];
69
- let caps = cache.get(engine);
92
+ const key = `${host}\0${engine}`;
93
+ let caps = cache.get(key);
70
94
  if (!caps) {
71
95
  try {
72
- caps = inspect(engine);
96
+ caps = inspect(engine, host);
73
97
  }
74
98
  catch (error) {
75
99
  caps = error;
76
100
  }
77
- cache.set(engine, caps);
101
+ cache.set(key, caps);
78
102
  }
79
103
  if (caps instanceof Error) {
80
104
  problems.push(`${event}: ${caps.message}`);
@@ -85,14 +109,14 @@ export function fleetHookCoreResults(home, env, inspect = (engine) => inspectFle
85
109
  if (missing === null || missing.length)
86
110
  problems.push(`${event}: required evaluators are missing`);
87
111
  if (canonical) {
88
- const left = uncoveredHooks(value('--hq-root'), 'fleet-local', canonical, caps.covers);
112
+ const left = uncoveredHooks(value('--hq-root'), host, canonical, caps.covers);
89
113
  if (left.length)
90
114
  problems.push(`${event}: uncovered hooks: ${left.join(', ')}`);
91
115
  }
92
116
  }
93
117
  }
94
118
  results.push({ status: problems.length ? 'FAIL' : 'PASS', checkId: `fleet-hook-core:${name}`, target: file,
95
- message: `Fleet profile ${name}: ${problems.length ? problems.join('; ') : Object.entries(cores).map(([event, core]) => `${event}=${core}`).join(', ') || 'no HQ hook registrations'}.`, details: { cores, problems } });
119
+ message: `Fleet profile ${name}: ${problems.length ? problems.join('; ') : Object.entries(cores).map(([event, core]) => `${event}=${core}${hosts[event] === 'agents-v2' ? ' (agents-v2)' : ''}`).join(', ') || 'no HQ hook registrations'}.`, details: { cores, problems, ...(Object.keys(hosts).length ? { hosts } : {}) } });
96
120
  }
97
121
  catch {
98
122
  results.push({ status: 'WARN', checkId: `fleet-hook-core:${name}`, target: file, message: `Fleet profile ${name} hook configuration could not be read.` });
@@ -3,15 +3,27 @@ import { verifyHookEngine } from './resolve.js';
3
3
  export declare const FLEET_EVENTS: Record<string, string>;
4
4
  /** Literal POSIX argv only. Never expands variables or executes shell syntax. */
5
5
  export declare function literalArgv(command: string): string[] | null;
6
- export declare function fallbackProblem(argv: unknown): string | null;
6
+ export type FleetHost = 'fleet-local' | 'agents-v2';
7
+ /** The shell adapter each Fleet host's profile registers. */
8
+ export declare const FLEET_ADAPTERS: Readonly<Record<FleetHost, string>>;
9
+ export declare function isFleetHost(value: unknown): value is FleetHost;
10
+ /**
11
+ * Why `argv` is not `host`'s exact adapter command, or null. The agents-v2
12
+ * adapter takes the event as its one positional argument and the rest from
13
+ * its environment contract, so its fallback is exactly
14
+ * `[<bash|sh>, <abs>/hq-agents-v2-hook-adapter.sh, <event>]`.
15
+ */
16
+ export declare function fallbackProblem(argv: unknown, host?: FleetHost, event?: string): string | null;
7
17
  export type FleetEngineLookup = CoreNextEngineLookup;
8
- /** Self-check, then probe, then the fleet-local host claim. */
9
- export declare function fleetEngineCapabilities(engine: string, probe?: typeof probeEngine, verify?: typeof verifyHookEngine): EngineCapabilities;
10
- export declare function inspectFleetEngine(engine: string, home: string, probe?: typeof probeEngine, verify?: typeof verifyHookEngine, lookup?: FleetEngineLookup): EngineCapabilities;
18
+ /** Self-check, then probe, then the host claim. */
19
+ export declare function fleetEngineCapabilities(engine: string, probe?: typeof probeEngine, verify?: typeof verifyHookEngine, host?: FleetHost): EngineCapabilities;
20
+ export declare function inspectFleetEngine(engine: string, home: string, probe?: typeof probeEngine, verify?: typeof verifyHookEngine, lookup?: FleetEngineLookup, host?: FleetHost): EngineCapabilities;
11
21
  export interface FleetPlanOptions {
12
22
  home: string;
13
23
  env?: NodeJS.ProcessEnv;
14
24
  platform?: NodeJS.Platform;
25
+ /** Registration host; fleet-local when absent. */
26
+ host?: FleetHost;
15
27
  inspect?: (engine: string) => EngineCapabilities;
16
28
  /** Test injection. Production passes nothing and uses the desktop lookup. */
17
29
  lookup?: FleetEngineLookup;
@@ -24,7 +36,7 @@ export interface FleetPlanEntry {
24
36
  }
25
37
  export declare function fleetRegistrationPlan(root: string, fallbacks: Record<string, string[]>, options: FleetPlanOptions): {
26
38
  schema: string;
27
- host: string;
39
+ host: FleetHost;
28
40
  events: Record<string, FleetPlanEntry>;
29
41
  };
30
42
  //# sourceMappingURL=fleet-registration.d.ts.map
@@ -1,4 +1,13 @@
1
- /** Fleet uses the same flag, evaluator and complete-hook gate as reindex. */
1
+ /**
2
+ * Fleet uses the same flag, evaluator and complete-hook gate as reindex.
3
+ *
4
+ * Two hq-fleet runtimes register here (US-040): `fleet-local` (local bots)
5
+ * and `agents-v2` (hosted agents). Each event gets exactly one entry: the
6
+ * native `hq-hook run --host <host>` call when the engine advertises the host
7
+ * and covers every old hook for the event (including `<host>-adapter:<Event>`),
8
+ * else the host's shell adapter command, which is also the native entry's
9
+ * `--fleet-fallback` argv, verbatim.
10
+ */
2
11
  import * as fs from 'node:fs';
3
12
  import * as path from 'node:path';
4
13
  import { checkStableEngine, coreNextOffReason, capableEvents, probeEngine, missingEvaluators, resolveCoreNextEngine } from '../../utils/host-registration.js';
@@ -62,7 +71,21 @@ export function literalArgv(command) {
62
71
  out.push(word);
63
72
  return out;
64
73
  }
65
- export function fallbackProblem(argv) {
74
+ /** The shell adapter each Fleet host's profile registers. */
75
+ export const FLEET_ADAPTERS = {
76
+ 'fleet-local': 'hq-fleet-local-hook-adapter.sh',
77
+ 'agents-v2': 'hq-agents-v2-hook-adapter.sh',
78
+ };
79
+ export function isFleetHost(value) {
80
+ return value === 'fleet-local' || value === 'agents-v2';
81
+ }
82
+ /**
83
+ * Why `argv` is not `host`'s exact adapter command, or null. The agents-v2
84
+ * adapter takes the event as its one positional argument and the rest from
85
+ * its environment contract, so its fallback is exactly
86
+ * `[<bash|sh>, <abs>/hq-agents-v2-hook-adapter.sh, <event>]`.
87
+ */
88
+ export function fallbackProblem(argv, host = 'fleet-local', event) {
66
89
  if (!Array.isArray(argv) || argv.length < 2 || !argv.every(v => typeof v === 'string' && !v.includes('\0')))
67
90
  return 'fallback must be a nonempty argv vector';
68
91
  if (!path.isAbsolute(argv[0]))
@@ -73,43 +96,49 @@ export function fallbackProblem(argv) {
73
96
  catch {
74
97
  return 'fallback executable is unavailable';
75
98
  }
99
+ const fleet = host === 'fleet-local';
76
100
  if (['bash', 'sh'].includes(path.basename(argv[0]))) {
77
- if (!path.isAbsolute(argv[1]) || path.basename(argv[1]) !== 'hq-fleet-local-hook-adapter.sh')
78
- return 'fallback must name the fleet adapter script';
101
+ if (!path.isAbsolute(argv[1]) || path.basename(argv[1]) !== FLEET_ADAPTERS[host])
102
+ return fleet ? 'fallback must name the fleet adapter script' : 'fallback must name the agents-v2 adapter script';
79
103
  try {
80
104
  fs.accessSync(argv[1], fs.constants.R_OK);
81
105
  }
82
106
  catch {
83
107
  return 'fallback adapter is unavailable';
84
108
  }
109
+ if (!fleet && (event === undefined || argv.length !== 3 || argv[2] !== event))
110
+ return 'fallback must pass exactly the event to the agents-v2 adapter';
85
111
  }
86
112
  else
87
- return 'fallback must use the fleet shell adapter';
113
+ return fleet ? 'fallback must use the fleet shell adapter' : 'fallback must use the agents-v2 shell adapter';
88
114
  return null;
89
115
  }
90
- /** Self-check, then probe, then the fleet-local host claim. */
91
- export function fleetEngineCapabilities(engine, probe = probeEngine, verify = verifyHookEngine) {
116
+ /** Self-check, then probe, then the host claim. */
117
+ export function fleetEngineCapabilities(engine, probe = probeEngine, verify = verifyHookEngine, host = 'fleet-local') {
92
118
  const problem = verify(engine);
93
119
  if (problem)
94
120
  throw new Error(problem);
95
121
  const caps = probe(engine);
96
- if (!caps.registrationHosts?.includes('fleet-local'))
97
- throw new Error('engine does not support fleet-local registration');
122
+ if (!caps.registrationHosts?.includes(host))
123
+ throw new Error(`engine does not support ${host} registration`);
98
124
  return caps;
99
125
  }
100
- export function inspectFleetEngine(engine, home, probe = probeEngine, verify = verifyHookEngine, lookup = {}) {
101
- const resolved = resolveCoreNextEngine(home, { mode: 'read-only', lookup, probe: e => fleetEngineCapabilities(e, probe, verify) });
126
+ export function inspectFleetEngine(engine, home, probe = probeEngine, verify = verifyHookEngine, lookup = {}, host = 'fleet-local') {
127
+ const resolved = resolveCoreNextEngine(home, { mode: 'read-only', lookup, probe: e => fleetEngineCapabilities(e, probe, verify, host) });
102
128
  checkStableEngine(engine, resolved.pinned);
103
129
  return resolved.caps;
104
130
  }
105
131
  export function fleetRegistrationPlan(root, fallbacks, options) {
132
+ const host = options.host ?? 'fleet-local';
133
+ if (!isFleetHost(host))
134
+ throw new Error(`unsupported fleet registration host: ${String(host)}`);
106
135
  const env = options.env ?? process.env;
107
136
  let reason = coreNextOffReason(options.home, env, options.platform ?? process.platform);
108
137
  let caps;
109
138
  let engine = '';
110
139
  if (!reason) {
111
140
  try {
112
- const resolved = resolveCoreNextEngine(options.home, { mode: 'read-only', platform: options.platform, lookup: options.lookup, probe: options.inspect ?? (e => fleetEngineCapabilities(e)) });
141
+ const resolved = resolveCoreNextEngine(options.home, { mode: 'read-only', platform: options.platform, lookup: options.lookup, probe: options.inspect ?? (e => fleetEngineCapabilities(e, undefined, undefined, host)) });
113
142
  engine = resolved.stable;
114
143
  caps = resolved.caps;
115
144
  }
@@ -117,16 +146,23 @@ export function fleetRegistrationPlan(root, fallbacks, options) {
117
146
  reason = error.message;
118
147
  }
119
148
  }
120
- const target = caps ? forHost({ coreNext: engine, events: capableEvents(caps), covers: caps.covers }, root, 'fleet-local') : null;
149
+ // An injected inspect skips fleetEngineCapabilities, so check the host claim here too.
150
+ if (caps && !caps.registrationHosts?.includes(host)) {
151
+ reason = `engine does not support ${host} registration`;
152
+ caps = undefined;
153
+ }
154
+ const target = caps ? forHost({ coreNext: engine, events: capableEvents(caps), covers: caps.covers }, root, host) : null;
121
155
  const events = {};
122
156
  for (const [event, canonical] of Object.entries(FLEET_EVENTS)) {
123
157
  const fallback = fallbacks[event] ?? [];
124
- const problem = fallbackProblem(fallback);
158
+ if (!Array.isArray(fallback) || !fallback.every(arg => typeof arg === 'string'))
159
+ throw new Error(`${event}: fallback must be an argv vector`);
160
+ const problem = fallbackProblem(fallback, host, event);
125
161
  const native = !reason && !problem && target?.events.includes(canonical);
126
- const argv = native ? [engine, 'run', '--host', 'fleet-local', event, '--hq-root', root, '--fleet-fallback', JSON.stringify(fallback)] : fallback;
127
- const why = native ? 'complete evaluator and hook coverage' : reason ?? problem ?? (caps && missingEvaluators(caps, canonical)?.length ? 'required evaluators are missing' : `uncovered hooks: ${uncoveredHooks(root, 'fleet-local', canonical, caps?.covers).join(', ')}`);
162
+ const argv = native ? [engine, 'run', '--host', host, event, '--hq-root', root, '--fleet-fallback', JSON.stringify(fallback)] : fallback;
163
+ const why = native ? 'complete evaluator and hook coverage' : reason ?? problem ?? (caps && missingEvaluators(caps, canonical)?.length ? 'required evaluators are missing' : `uncovered hooks: ${uncoveredHooks(root, host, canonical, caps?.covers).join(', ')}`);
128
164
  events[event] = { mode: native ? 'native' : 'shell', argv, command: argv.map(quotePosix).join(' '), reason: why };
129
165
  }
130
- return { schema: 'hq.hook-registration-plan.v1', host: 'fleet-local', events };
166
+ return { schema: 'hq.hook-registration-plan.v1', host, events };
131
167
  }
132
168
  //# sourceMappingURL=fleet-registration.js.map
@@ -15,6 +15,10 @@
15
15
  */
16
16
  import type { RunLedgerEntry } from "./ledger.js";
17
17
  import type { OnDemandSyncDeps } from "./run.js";
18
+ /** Pass failures that mean Claude Code is signed out (or missing) on this computer. */
19
+ export declare const SIGNED_OUT_SIGNALS_CODES: ReadonlySet<string>;
20
+ /** A failed ledger line whose pass found Claude Code signed out. */
21
+ export declare function isSignedOutSignalsFailure(entry: Pick<RunLedgerEntry, "status" | "error">): boolean;
18
22
  export declare const SIGNALS_HEALTH_RULE: string;
19
23
  /** One alert per adapter and connection per hour. */
20
24
  export declare const SIGNALS_ALERT_DEDUPE_MS: number;
@@ -25,11 +29,16 @@ export declare const SIGNALS_ALERT_CHANNEL_FIELD = "signals_alert_channel";
25
29
  export declare const SLACK_POST_TOOL = "slack.messages.post";
26
30
  /**
27
31
  * Ledger lines that landed sources and either generated no signals, whatever
28
- * their status, or failed partway after generating some.
32
+ * their status, or failed partway after generating some. A line whose pass
33
+ * failed because Claude Code is signed out counts too when it landed nothing:
34
+ * the pass only checks the login when queued documents are waiting, so that
35
+ * run had backlog it could not process, and the owner must hear about it.
29
36
  */
30
37
  export declare function findSignalsFailures(entries: readonly RunLedgerEntry[]): RunLedgerEntry[];
31
38
  /** The dedupe key: one adapter on one connection. */
32
39
  export declare function signalsAlertKey(entry: Pick<RunLedgerEntry, "adapter" | "connectionId">): string;
40
+ /** The dedupe key shared by every connection of one adapter that failed signed out. */
41
+ export declare function signedOutAlertKey(entry: Pick<RunLedgerEntry, "adapter">): string;
33
42
  /** The first words of every signals-failure alert; the Fleet job script finds the alert by them. */
34
43
  export declare const SIGNALS_FAILURE_PREFIX = "Signals failure for ";
35
44
  export declare function formatSignalsFailureAlert(entry: RunLedgerEntry, options?: {