@indigoai-us/hq-cli 5.345.217 → 5.345.219

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 (101) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +1 -1
  3. package/assets/bot-workers/setup/skills/add-a-pack.md +3 -3
  4. package/assets/scaffold/core/scripts/hq-session.sh +4 -0
  5. package/dist/command-catalog.generated.d.ts +69 -0
  6. package/dist/command-catalog.generated.js +83 -0
  7. package/dist/commands/agents.d.ts +22 -0
  8. package/dist/commands/agents.js +92 -1
  9. package/dist/commands/cloud.d.ts +1 -1
  10. package/dist/commands/cloud.js +1 -1
  11. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  12. package/dist/commands/core-hook-registration-plan.js +21 -0
  13. package/dist/commands/core-hq-session-native.js +3 -0
  14. package/dist/commands/core.js +9 -0
  15. package/dist/commands/doctor.js +4 -0
  16. package/dist/commands/install-global.js +1 -1
  17. package/dist/commands/lanes-shared.d.ts +2 -0
  18. package/dist/commands/lanes-watch.js +28 -1
  19. package/dist/commands/lanes.d.ts +2 -0
  20. package/dist/commands/lanes.js +99 -9
  21. package/dist/commands/members.js +1 -1
  22. package/dist/commands/pack-start-bot.d.ts +1 -1
  23. package/dist/commands/pack-start-bot.js +2 -2
  24. package/dist/commands/pkg-update.js +1 -1
  25. package/dist/commands/reindex.js +6 -0
  26. package/dist/commands/sync-narrow.js +1 -1
  27. package/dist/commands/team-sync.js +1 -1
  28. package/dist/data/command-states.json +8 -1
  29. package/dist/index.js +8 -0
  30. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  31. package/dist/lib/anywhere-person-setting.js +2 -2
  32. package/dist/lib/billing/usage-cost.js +5 -2
  33. package/dist/lib/bot/pack-link.d.ts +2 -2
  34. package/dist/lib/bot/pack-link.js +2 -2
  35. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  36. package/dist/lib/daemon/anywhere-listener.js +86 -4
  37. package/dist/lib/daemon/hook-env.d.ts +32 -0
  38. package/dist/lib/daemon/hook-env.js +51 -0
  39. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  40. package/dist/lib/daemon/machine-check-owner.js +95 -0
  41. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  42. package/dist/lib/daemon/machine-check-registration.js +64 -0
  43. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  44. package/dist/lib/daemon/machine-checks.js +412 -0
  45. package/dist/lib/daemon/ops/policy.js +5 -3
  46. package/dist/lib/daemon/run.js +37 -5
  47. package/dist/lib/daemon/server.d.ts +2 -0
  48. package/dist/lib/daemon/server.js +6 -0
  49. package/dist/lib/daemon/state-file.d.ts +12 -1
  50. package/dist/lib/daemon/state-file.js +23 -1
  51. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +4 -0
  52. package/dist/lib/doctor/checks/fleet-hook-core.js +103 -0
  53. package/dist/lib/doctor/checks/host-core.d.ts +2 -0
  54. package/dist/lib/doctor/checks/host-core.js +81 -11
  55. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  56. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  57. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  58. package/dist/lib/doctor/registry.js +4 -0
  59. package/dist/lib/doctor/types.d.ts +4 -0
  60. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  61. package/dist/lib/environment/credential-shapes.js +333 -0
  62. package/dist/lib/environment/profile.js +4 -16
  63. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  64. package/dist/lib/hook-engine/canary-gate.js +147 -0
  65. package/dist/lib/hook-engine/coverage.d.ts +15 -0
  66. package/dist/lib/hook-engine/coverage.js +130 -0
  67. package/dist/lib/hook-engine/fleet-registration.d.ts +30 -0
  68. package/dist/lib/hook-engine/fleet-registration.js +132 -0
  69. package/dist/lib/hook-engine/reconcile.js +297 -116
  70. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  71. package/dist/lib/hook-engine/registration-identity.js +97 -0
  72. package/dist/lib/hook-engine/registration.d.ts +1 -23
  73. package/dist/lib/hook-engine/registration.js +1 -52
  74. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  75. package/dist/lib/hook-engine/resolve.js +7 -3
  76. package/dist/lib/install/claude-targets.js +28 -15
  77. package/dist/lib/install/codex-pack-contributions.js +1 -1
  78. package/dist/lib/install/codex-targets.js +24 -11
  79. package/dist/lib/install/hook-target.d.ts +2 -2
  80. package/dist/lib/install/hook-target.js +7 -5
  81. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  82. package/dist/lib/lanes/canonical-host.js +9 -3
  83. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  84. package/dist/lib/lanes/machine-identity.js +26 -0
  85. package/dist/lib/lanes/spawn.js +17 -3
  86. package/dist/lib/packages/setup-block.d.ts +2 -2
  87. package/dist/lib/packages/setup-block.js +2 -2
  88. package/dist/lib/packages/start-bot.d.ts +1 -1
  89. package/dist/lib/packages/start-bot.js +1 -1
  90. package/dist/main.js +1 -1
  91. package/dist/types.d.ts +1 -1
  92. package/dist/utils/callback-port-busy.d.ts +1 -1
  93. package/dist/utils/callback-port-busy.js +4 -4
  94. package/dist/utils/core-next-flag.d.ts +4 -0
  95. package/dist/utils/core-next-flag.js +22 -0
  96. package/dist/utils/core-next-kill.d.ts +16 -0
  97. package/dist/utils/core-next-kill.js +35 -0
  98. package/dist/utils/hook-trust.js +4 -1
  99. package/dist/utils/host-registration.d.ts +80 -17
  100. package/dist/utils/host-registration.js +194 -47
  101. package/package.json +8 -8
@@ -1,6 +1,16 @@
1
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
2
+ import { HQ_ANYWHERE_RUNTIME_FLAG } from "../anywhere-runtime-flag-key.js";
3
+ /**
4
+ * How often the listener checks again when no event has arrived. It is a
5
+ * correctness fallback only, for an event that was missed or a change no event
6
+ * reports (a person opting in while hqd is closed). Changes are normally
7
+ * picked up from the daemon's events: a shared registry read whose HQ
8
+ * Anywhere answer changed, or the running hqd server's runtime gate changing.
9
+ */
10
+ export const HQD_LISTENER_FALLBACK_MS = 10 * 60_000;
1
11
  /** Keep the local hqd listener aligned with the live flag and person setting. */
2
12
  export async function startHqdRuntimeListener(options) {
3
- const intervalMs = options.intervalMs ?? 60_000;
13
+ const fallbackMs = options.fallbackMs ?? HQD_LISTENER_FALLBACK_MS;
4
14
  const log = options.log ?? (() => { });
5
15
  const schedule = options.schedule ?? ((callback, delayMs) => {
6
16
  const timer = setInterval(callback, delayMs);
@@ -10,11 +20,15 @@ export async function startHqdRuntimeListener(options) {
10
20
  let server = null;
11
21
  let closed = false;
12
22
  let inFlight = null;
23
+ // An event arrived while a check was in progress: that check may have read
24
+ // the state from before the change, so one more check follows it.
25
+ let again = false;
13
26
  const refresh = () => {
14
27
  if (closed)
15
28
  return Promise.resolve();
16
29
  if (inFlight)
17
30
  return inFlight;
31
+ again = false;
18
32
  inFlight = (async () => {
19
33
  let enabled = false;
20
34
  try {
@@ -53,19 +67,35 @@ export async function startHqdRuntimeListener(options) {
53
67
  }
54
68
  })().finally(() => {
55
69
  inFlight = null;
70
+ if (again && !closed)
71
+ void refresh();
56
72
  });
57
73
  return inFlight;
58
74
  };
75
+ const notify = () => {
76
+ if (closed)
77
+ return;
78
+ if (inFlight) {
79
+ again = true;
80
+ return;
81
+ }
82
+ void refresh();
83
+ };
84
+ const unsubscribe = options.subscribe?.(notify) ?? (() => { });
59
85
  await refresh();
60
- if (closed)
61
- return { refresh, close: async () => { } };
62
- const cancel = schedule(() => { void refresh(); }, intervalMs);
86
+ if (closed) {
87
+ unsubscribe();
88
+ return { refresh, notify, close: async () => { } };
89
+ }
90
+ const cancel = schedule(() => { void refresh(); }, fallbackMs);
63
91
  return {
64
92
  refresh,
93
+ notify,
65
94
  async close() {
66
95
  if (closed)
67
96
  return;
68
97
  closed = true;
98
+ unsubscribe();
69
99
  cancel();
70
100
  await inFlight;
71
101
  const current = server;
@@ -76,4 +106,56 @@ export async function startHqdRuntimeListener(options) {
76
106
  },
77
107
  };
78
108
  }
109
+ export function createHqdRuntimeEvents() {
110
+ const listeners = new Set();
111
+ return {
112
+ emit() {
113
+ for (const notify of [...listeners]) {
114
+ try {
115
+ notify();
116
+ }
117
+ catch {
118
+ // one listener cannot stop the others
119
+ }
120
+ }
121
+ },
122
+ subscribe(notify) {
123
+ const entry = () => notify();
124
+ listeners.add(entry);
125
+ return () => { listeners.delete(entry); };
126
+ },
127
+ };
128
+ }
129
+ /**
130
+ * An observer for the daemon's shared registry reads (flag.ts `onRead`) that
131
+ * calls `onChange` when the HQ Anywhere runtime answer differs from the last
132
+ * read's: the registry value, a sign-in or sign-out, or the local override
133
+ * file. A failed read says nothing and is skipped. The first answer counts as
134
+ * a change, so a decision the listener made before the first read is checked.
135
+ */
136
+ export function observeHqdRuntimeFlag(onChange) {
137
+ let last;
138
+ return (read, env) => {
139
+ let answer;
140
+ try {
141
+ const override = readLocalOverride(HQ_ANYWHERE_RUNTIME_FLAG, env);
142
+ if (read.signedOut) {
143
+ answer = `signed-out|${String(override)}`;
144
+ }
145
+ else {
146
+ if (read.errors.length > 0 || !read.client)
147
+ return;
148
+ const resolution = read.client.explain(HQ_ANYWHERE_RUNTIME_FLAG, { fallback: true });
149
+ answer = `${resolution.source}:${String(resolution.value)}|${String(override)}`;
150
+ }
151
+ }
152
+ catch {
153
+ return;
154
+ }
155
+ if (answer === last)
156
+ return;
157
+ last = answer;
158
+ onChange();
159
+ };
160
+ }
79
161
  //# sourceMappingURL=anywhere-listener.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * HQ_HOOK_* belongs to one hook dispatch, never to the daemon.
3
+ *
4
+ * master-hook.sh exports the fields it parsed from a hook payload
5
+ * (HQ_HOOK_SESSION_ID, HQ_HOOK_AGENT_ID, HQ_HOOK_AGENT_TYPE, HQ_HOOK_CWD,
6
+ * HQ_HOOK_TOOL_NAME, HQ_HOOK_EVENT, HQ_HOOK_COMMAND, ...) so its child hooks can
7
+ * skip their own parse. A hook script that finds one of them set trusts it over
8
+ * the payload on stdin. The daemon runs hook scripts with a payload it builds
9
+ * itself, so any HQ_HOOK_* it holds describes some other call: a daemon started
10
+ * from inside a hook, or from a shell that exported one, would otherwise answer
11
+ * every check with that call's identity (a stale HQ_HOOK_AGENT_ID turns each
12
+ * main-thread check into "This call has an invalid agent_id").
13
+ *
14
+ * The whole prefix goes, tuning knobs included: the daemon's OS unit never
15
+ * carries any of them (its environment is an allowlist), so a hand-started
16
+ * daemon behaves the same as a managed one.
17
+ */
18
+ /** The HQ_HOOK_* names set in `env`, sorted. Names only: values may be private. */
19
+ export declare function hookEnvNames(env: NodeJS.ProcessEnv): string[];
20
+ /** `env` without any HQ_HOOK_* name. Returns `env` itself when it has none. */
21
+ export declare function withoutHookEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
22
+ /**
23
+ * The environment `hq daemon run` works with. HQ_HOOK_* is deleted from the
24
+ * live process environment, because hqd and the services read it directly, and
25
+ * left out of a caller-supplied one. `removed` names what was dropped, for the
26
+ * daemon log.
27
+ */
28
+ export declare function daemonStartEnv(given: NodeJS.ProcessEnv | undefined, processEnv?: NodeJS.ProcessEnv): {
29
+ env: NodeJS.ProcessEnv;
30
+ removed: string[];
31
+ };
32
+ //# sourceMappingURL=hook-env.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * HQ_HOOK_* belongs to one hook dispatch, never to the daemon.
3
+ *
4
+ * master-hook.sh exports the fields it parsed from a hook payload
5
+ * (HQ_HOOK_SESSION_ID, HQ_HOOK_AGENT_ID, HQ_HOOK_AGENT_TYPE, HQ_HOOK_CWD,
6
+ * HQ_HOOK_TOOL_NAME, HQ_HOOK_EVENT, HQ_HOOK_COMMAND, ...) so its child hooks can
7
+ * skip their own parse. A hook script that finds one of them set trusts it over
8
+ * the payload on stdin. The daemon runs hook scripts with a payload it builds
9
+ * itself, so any HQ_HOOK_* it holds describes some other call: a daemon started
10
+ * from inside a hook, or from a shell that exported one, would otherwise answer
11
+ * every check with that call's identity (a stale HQ_HOOK_AGENT_ID turns each
12
+ * main-thread check into "This call has an invalid agent_id").
13
+ *
14
+ * The whole prefix goes, tuning knobs included: the daemon's OS unit never
15
+ * carries any of them (its environment is an allowlist), so a hand-started
16
+ * daemon behaves the same as a managed one.
17
+ */
18
+ const HOOK_ENV_NAME = /^HQ_HOOK_/i;
19
+ /** The HQ_HOOK_* names set in `env`, sorted. Names only: values may be private. */
20
+ export function hookEnvNames(env) {
21
+ return Object.keys(env)
22
+ .filter((key) => HOOK_ENV_NAME.test(key))
23
+ .sort();
24
+ }
25
+ /** `env` without any HQ_HOOK_* name. Returns `env` itself when it has none. */
26
+ export function withoutHookEnv(env) {
27
+ const names = hookEnvNames(env);
28
+ if (names.length === 0)
29
+ return env;
30
+ const clean = { ...env };
31
+ for (const name of names)
32
+ delete clean[name];
33
+ return clean;
34
+ }
35
+ /**
36
+ * The environment `hq daemon run` works with. HQ_HOOK_* is deleted from the
37
+ * live process environment, because hqd and the services read it directly, and
38
+ * left out of a caller-supplied one. `removed` names what was dropped, for the
39
+ * daemon log.
40
+ */
41
+ export function daemonStartEnv(given, processEnv = process.env) {
42
+ const removed = new Set(hookEnvNames(processEnv));
43
+ for (const name of removed)
44
+ delete processEnv[name];
45
+ if (given === undefined || given === processEnv)
46
+ return { env: processEnv, removed: [...removed].sort() };
47
+ for (const name of hookEnvNames(given))
48
+ removed.add(name);
49
+ return { env: withoutHookEnv(given), removed: [...removed].sort() };
50
+ }
51
+ //# sourceMappingURL=hook-env.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * How old the daemon's machine-check results file may be and still count as
3
+ * proof the schedule is running: two hourly intervals plus the first delay,
4
+ * so one late or skipped batch does not flip the owner.
5
+ */
6
+ export declare const MACHINE_CHECK_RESULTS_FRESH_MS: number;
7
+ /** Internal, offline protocol shared with the legacy dispatcher. */
8
+ export declare function machineCheckOwner(env?: NodeJS.ProcessEnv, home?: string, options?: {
9
+ now?: Date;
10
+ platform?: NodeJS.Platform;
11
+ }): {
12
+ schema: "hq-machine-check-owner.v1";
13
+ owner: "daemon" | "legacy";
14
+ reason: string;
15
+ checks: {
16
+ id: string;
17
+ path: string;
18
+ event: import("./machine-checks.js").MachineCheckEvent;
19
+ }[];
20
+ };
21
+ //# sourceMappingURL=machine-check-owner.d.ts.map
@@ -0,0 +1,95 @@
1
+ import * as os from "node:os";
2
+ import * as path from "node:path";
3
+ import { daemonPresenceLabel, readHeartbeat, heartbeatFile } from "./heartbeat.js";
4
+ import { MACHINE_CHECKS, MACHINE_CHECKS_FIRST_DELAY_MS, MACHINE_CHECKS_INTERVAL_MS, MACHINE_CHECKS_RESULT_FILE, machineChecksScheduleOn, } from "./machine-checks.js";
5
+ import { daemonPaths, readStoreFile } from "./paths.js";
6
+ import { readDaemonConfig } from "./config.js";
7
+ import { sameHqRoot } from "../hook-engine/registration-identity.js";
8
+ import { nativeSessionStartRegistered } from "./machine-check-registration.js";
9
+ import { codexEnvEvidence, grokEnvEvidence } from "../doctor/platform.js";
10
+ /**
11
+ * How old the daemon's machine-check results file may be and still count as
12
+ * proof the schedule is running: two hourly intervals plus the first delay,
13
+ * so one late or skipped batch does not flip the owner.
14
+ */
15
+ export const MACHINE_CHECK_RESULTS_FRESH_MS = 2 * MACHINE_CHECKS_INTERVAL_MS + MACHINE_CHECKS_FIRST_DELAY_MS;
16
+ function errorName(error) {
17
+ return error instanceof Error ? error.code ?? error.name : "UnknownError";
18
+ }
19
+ /**
20
+ * The session's harness: `HQ_HARNESS` when set, else the Codex or Grok runtime
21
+ * variables (the same markers `lanes` uses for the orchestrator engine), else
22
+ * Claude. Claude stays the default because `CLAUDECODE=1` is not always set.
23
+ */
24
+ function sessionHarness(env) {
25
+ const named = env.HQ_HARNESS?.trim().toLowerCase();
26
+ if (named)
27
+ return named;
28
+ if (codexEnvEvidence(env).length > 0)
29
+ return "codex";
30
+ if (grokEnvEvidence(env).length > 0)
31
+ return "grok";
32
+ return "claude";
33
+ }
34
+ /**
35
+ * Decide who runs the machine checks, offline and fail-safe. "daemon" only
36
+ * when every host-local signal shows the schedule is really running here:
37
+ * not Windows (checks start with /bin/bash), the rollout flag is on with no
38
+ * kill switch, the daemon heartbeat file is fresh, and the schedule wrote its
39
+ * results file (which needs a resolved HQ root) within the freshness window.
40
+ * Anything that cannot be observed answers "legacy" with the reason.
41
+ */
42
+ function decideOwner(env, home, now, platform) {
43
+ if (platform === "win32")
44
+ return { owner: "legacy", reason: "windows: machine checks need /bin/bash" };
45
+ if (!machineChecksScheduleOn(env, home))
46
+ return { owner: "legacy", reason: "core.next is off or a kill switch is set" };
47
+ const sessionRoot = env.HQ_ROOT?.trim();
48
+ let daemonRoot;
49
+ try {
50
+ daemonRoot = readDaemonConfig(daemonPaths(home, env).configPath).hqRoot;
51
+ }
52
+ catch { /* fail safe */ }
53
+ if (!sessionRoot || !daemonRoot || !sameHqRoot(sessionRoot, daemonRoot))
54
+ return { owner: "legacy", reason: "session HQ root differs from daemon HQ root" };
55
+ const host = sessionHarness(env);
56
+ if ((host !== "claude" && host !== "codex") || !nativeSessionStartRegistered(sessionRoot, home, host, env)) {
57
+ return { owner: "legacy", reason: "no native SessionStart for this host and HQ root" };
58
+ }
59
+ let beat;
60
+ try {
61
+ beat = readHeartbeat(heartbeatFile(home, env));
62
+ }
63
+ catch (error) {
64
+ return { owner: "legacy", reason: `daemon heartbeat unreadable (${errorName(error)})` };
65
+ }
66
+ if (!beat)
67
+ return { owner: "legacy", reason: "daemon heartbeat missing: daemon not running" };
68
+ if (daemonPresenceLabel(beat, now) !== "daemon live")
69
+ return { owner: "legacy", reason: "daemon heartbeat stale" };
70
+ let results;
71
+ try {
72
+ results = readStoreFile(path.join(daemonPaths(home, env).root, MACHINE_CHECKS_RESULT_FILE), 256 * 1024);
73
+ }
74
+ catch (error) {
75
+ return { owner: "legacy", reason: `machine-check results unreadable (${errorName(error)})` };
76
+ }
77
+ if (!results)
78
+ return { owner: "legacy", reason: "no machine-check results: schedule has not run with an HQ root" };
79
+ const age = now.getTime() - results.mtimeMs;
80
+ if (!Number.isFinite(age) || age > MACHINE_CHECK_RESULTS_FRESH_MS) {
81
+ return { owner: "legacy", reason: "machine-check results stale" };
82
+ }
83
+ return { owner: "daemon", reason: "daemon live and schedule results fresh" };
84
+ }
85
+ /** Internal, offline protocol shared with the legacy dispatcher. */
86
+ export function machineCheckOwner(env = process.env, home = env.HOME || env.USERPROFILE || os.homedir(), options = {}) {
87
+ const decided = decideOwner(env, home, options.now ?? new Date(), options.platform ?? process.platform);
88
+ return {
89
+ schema: "hq-machine-check-owner.v1",
90
+ owner: decided.owner,
91
+ reason: decided.reason,
92
+ checks: MACHINE_CHECKS.map(({ id, path: file, event }) => ({ id, path: file, event })),
93
+ };
94
+ }
95
+ //# sourceMappingURL=machine-check-owner.js.map
@@ -0,0 +1,4 @@
1
+ export type MachineCheckHost = "claude" | "codex" | "grok";
2
+ export declare function nativeSessionStartRegistered(root: string, home: string, host: MachineCheckHost, env: NodeJS.ProcessEnv): boolean;
3
+ export declare function anyNativeSessionStartRegistered(root: string, home: string, env: NodeJS.ProcessEnv): boolean;
4
+ //# sourceMappingURL=machine-check-registration.d.ts.map
@@ -0,0 +1,64 @@
1
+ /** Read-only proof that a session can receive the daemon's findings. */
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { parse } from "smol-toml";
5
+ import { isCoreNextEntry, userHookSettingsFile } from "../hook-engine/registration-identity.js";
6
+ function readSettings(file) {
7
+ let fd;
8
+ try {
9
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0));
10
+ const stat = fs.fstatSync(fd);
11
+ if (!stat.isFile() || stat.size > 1024 * 1024)
12
+ return undefined;
13
+ const bytes = Buffer.alloc(1024 * 1024 + 1);
14
+ const length = fs.readSync(fd, bytes, 0, bytes.length, 0);
15
+ return length <= 1024 * 1024 ? bytes.toString("utf8", 0, length) : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ finally {
21
+ if (fd !== undefined)
22
+ fs.closeSync(fd);
23
+ }
24
+ }
25
+ function entries(value) {
26
+ if (!Array.isArray(value))
27
+ return [];
28
+ return value.flatMap((group) => {
29
+ if (!group || typeof group !== "object")
30
+ return [];
31
+ const hooks = group.hooks;
32
+ return Array.isArray(hooks) ? hooks.filter((entry) => !!entry && typeof entry === "object") : [];
33
+ });
34
+ }
35
+ export function nativeSessionStartRegistered(root, home, host, env) {
36
+ const files = host === "claude"
37
+ ? [userHookSettingsFile("claude", home, env), path.join(root, ".claude/settings.json"), path.join(root, ".claude/settings.local.json")]
38
+ : host === "codex"
39
+ ? [userHookSettingsFile("codex", home, env), path.join(root, ".codex/hooks.json"), path.join(root, ".codex/config.toml")]
40
+ : [path.join(home, ".grok/hooks/hq-hq-bridge.json"), path.join(root, ".grok/hooks/hq-grok-user-bridge.json")];
41
+ return files.some((file) => {
42
+ try {
43
+ const text = readSettings(file);
44
+ if (text === undefined)
45
+ return false;
46
+ const doc = (file.endsWith(".toml") ? parse(text) : JSON.parse(text));
47
+ return entries(doc.hooks?.SessionStart ?? doc.hooks?.session_start).some((entry) => {
48
+ if (!isCoreNextEntry(entry, root))
49
+ return false;
50
+ if (Array.isArray(entry.args))
51
+ return entry.args[2] === host && entry.args[3] === "SessionStart";
52
+ return typeof entry.command === "string" && entry.command.includes(`'--host' '${host}' 'SessionStart'`);
53
+ });
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ });
59
+ }
60
+ export function anyNativeSessionStartRegistered(root, home, env) {
61
+ // Grok currently has no SessionStart notice; do not transfer its checks.
62
+ return ["claude", "codex"].some((host) => nativeSessionStartRegistered(root, home, host, env));
63
+ }
64
+ //# sourceMappingURL=machine-check-registration.js.map
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Machine checks: the SessionStart and UserPromptSubmit scripts that look at
3
+ * this machine (an HQ update, a stale model pin, a missing CLI, ...). They
4
+ * used to run on every session start or prompt. They now run here, one at a
5
+ * time, on the daemon's schedule and in `hq doctor --only machine-checks`.
6
+ * The daemon puts the results in its state file; the hook engine shows each
7
+ * new finding once at a session start without starting a process
8
+ * (crates/hq-hook/src/session_start.rs).
9
+ *
10
+ * A script is run only when it passes the store read rules
11
+ * (src/lib/safe-store.ts): its path resolves inside the HQ root, it is a
12
+ * regular file with one link, owned by this user, that group and others
13
+ * cannot write, in a folder owned by this user that group and others cannot
14
+ * write, under parents owned by this user or root that group and others
15
+ * cannot write. A refused or missing script is `unknown` and is not run.
16
+ *
17
+ * Remaining window: the check opens and inspects the script, then closes it,
18
+ * and bash opens it again by path. A same-user process can swap the file or
19
+ * its folder in between. That process can already write to the HQ root, so
20
+ * it gains no access it did not have; the check keeps a link, a hardlink, a
21
+ * file of another user or a writable file from being run by mistake.
22
+ *
23
+ * Results can name local paths, so they are written only to the daemon's
24
+ * private folder (machine-checks.json, mode 0600) and the state file, and are
25
+ * never logged or sent.
26
+ */
27
+ import { coreNextEnabled } from "../../utils/core-next-flag.js";
28
+ import { type StoreFileWriteOptions } from "./paths.js";
29
+ import { type DaemonStateMachineCheck } from "./state-file.js";
30
+ export type MachineCheckEvent = "SessionStart" | "UserPromptSubmit";
31
+ export interface MachineCheckSpec {
32
+ id: string;
33
+ /** Relative to the HQ root, forward slashes. */
34
+ path: string;
35
+ event: MachineCheckEvent;
36
+ timeoutMs: number;
37
+ }
38
+ export declare const MACHINE_CHECKS: readonly MachineCheckSpec[];
39
+ export declare const MACHINE_CHECK_IDS: ReadonlySet<string>;
40
+ /** The results file in the daemon folder. */
41
+ export declare const MACHINE_CHECKS_RESULT_FILE = "machine-checks.json";
42
+ /** stdout kept per script; the rest is read and dropped. */
43
+ export declare const MACHINE_CHECK_STDOUT_BYTES: number;
44
+ export declare const MACHINE_CHECK_SUMMARY_CHARS = 240;
45
+ /** Wait between SIGTERM and SIGKILL on a timed-out script. */
46
+ export declare const MACHINE_CHECK_KILL_GRACE_MS = 2000;
47
+ /** After the script exits, how long its stdout may still deliver buffered bytes. */
48
+ export declare const MACHINE_CHECK_DRAIN_MS = 50;
49
+ export type MachineCheckResult = DaemonStateMachineCheck;
50
+ export interface RunMachineChecksOptions {
51
+ hqRoot: string;
52
+ env?: NodeJS.ProcessEnv;
53
+ now?: () => Date;
54
+ /** Write the results here (through the store rules) after the batch. */
55
+ resultsFile?: string;
56
+ resultsWrite?: StoreFileWriteOptions;
57
+ /** Test seams. */
58
+ checks?: readonly MachineCheckSpec[];
59
+ killGraceMs?: number;
60
+ drainMs?: number;
61
+ }
62
+ /** The finding text a script's stdout carries: empty means nothing to report. */
63
+ export declare function findingText(stdout: string): string;
64
+ /** First non-empty line with `<tag>` and `</tag>` markers removed, at most 240 characters. */
65
+ export declare function findingSummary(text: string): string;
66
+ /** Lowercase hex SHA-256 of `<id>\n<detail>`, the detail's invalid UTF-8 already replaced by U+FFFD. */
67
+ export declare function findingFingerprint(id: string, detail: string): string;
68
+ /** A script's result from its stdout bytes. */
69
+ export declare function resultFromStdout(id: string, stdout: Buffer, checkedAt: string): MachineCheckResult;
70
+ type ScriptCheck = {
71
+ ok: true;
72
+ file: string;
73
+ } | {
74
+ ok: false;
75
+ summary: string;
76
+ };
77
+ /** The script's absolute path when it may be run; else why not. */
78
+ export declare function checkMachineCheckScript(hqRoot: string, relative: string): ScriptCheck;
79
+ /**
80
+ * Run every machine check once, one at a time. A call while a batch is
81
+ * running returns that batch. Inside a machine check
82
+ * (HQ_MACHINE_CHECKS_RUNNING=1) nothing runs and the answer is empty.
83
+ */
84
+ export declare function runMachineChecks(options: RunMachineChecksOptions): Promise<MachineCheckResult[]>;
85
+ /** Written atomically through src/lib/safe-store.ts in the daemon's private folder. */
86
+ export declare function writeMachineCheckResults(file: string, results: readonly MachineCheckResult[], options?: StoreFileWriteOptions): void;
87
+ /**
88
+ * The latest results, or [] when the file is missing, refused by the store
89
+ * rules (a link, a second link, another user's, writable by others) or has
90
+ * any invalid field.
91
+ */
92
+ export declare function readMachineCheckResults(file: string): MachineCheckResult[];
93
+ /** First batch about a minute after the daemon starts, then hourly. */
94
+ export declare const MACHINE_CHECKS_FIRST_DELAY_MS = 60000;
95
+ export declare const MACHINE_CHECKS_INTERVAL_MS: number;
96
+ /** Batches never start closer together than this. */
97
+ export declare const MACHINE_CHECKS_MIN_INTERVAL_MS: number;
98
+ /** Use the same offline flag decision as hook registration. */
99
+ export declare const machineChecksCoreNextOn: typeof coreNextEnabled;
100
+ /**
101
+ * A switch that sends this machine back to the old hook core is set:
102
+ * HQ_CORE_NEXT is off, 0, false or no; HQ_HOOK_ENGINE is off (both trimmed,
103
+ * any ASCII case); or `<home>/.hq/state/core-next.off` or
104
+ * `<home>/.hq/hook-engine.off` exists (any file type, a link counts). These
105
+ * are the switches the hook engine checks.
106
+ */
107
+ export declare function machineChecksKillSwitchSet(env: NodeJS.ProcessEnv, home: string): boolean;
108
+ /**
109
+ * The daemon's schedule runs when the new hook core (`core.next`) is on for
110
+ * this machine and no kill switch is set, so the checks leave the hook path
111
+ * exactly when the machine moves to the new core and nothing runs twice.
112
+ */
113
+ export declare function machineChecksScheduleOn(env: NodeJS.ProcessEnv, home: string): boolean;
114
+ export interface MachineCheckScheduleOptions {
115
+ env: NodeJS.ProcessEnv;
116
+ /** The home folder that holds the kill-switch files. */
117
+ home: string;
118
+ log: (level: "info" | "warn" | "error", message: string) => void;
119
+ /** The HQ root, or undefined when none resolves. */
120
+ hqRoot: () => string | undefined;
121
+ resultsFile: string;
122
+ firstDelayMs?: number;
123
+ intervalMs?: number;
124
+ now?: () => number;
125
+ run?: (options: RunMachineChecksOptions) => Promise<MachineCheckResult[]>;
126
+ /** Test seam: the gate, read at each tick. Default machineChecksScheduleOn. */
127
+ enabled?: (env: NodeJS.ProcessEnv, home: string) => boolean;
128
+ registered?: (root: string, home: string, env: NodeJS.ProcessEnv) => boolean;
129
+ }
130
+ export interface MachineCheckSchedule {
131
+ /** One scheduled tick (tests). Resolves when the tick is done; never rejects. */
132
+ tick(): Promise<void>;
133
+ close(): void;
134
+ }
135
+ /**
136
+ * The daemon's machine-check timer. Each tick runs a batch only when the new
137
+ * hook core (`core.next`) is on for this machine and no kill switch is set;
138
+ * both are read at every tick, so turning either off stops the next run
139
+ * without a daemon restart. A batch already running finishes. A failed batch
140
+ * logs one line with the error's name only.
141
+ */
142
+ export declare function startMachineCheckSchedule(options: MachineCheckScheduleOptions): MachineCheckSchedule;
143
+ export {};
144
+ //# sourceMappingURL=machine-checks.d.ts.map