@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
@@ -0,0 +1,412 @@
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 { spawn } from "node:child_process";
28
+ import { createHash } from "node:crypto";
29
+ import * as fs from "node:fs";
30
+ import * as path from "node:path";
31
+ import { coreNextEnabled } from "../../utils/core-next-flag.js";
32
+ import { coreNextKillReason } from "../../utils/core-next-kill.js";
33
+ import { anyNativeSessionStartRegistered } from "./machine-check-registration.js";
34
+ import { openStoreDir } from "../safe-store.js";
35
+ import { readStoreFile, writeStoreFile } from "./paths.js";
36
+ import { cutUtf8, MACHINE_CHECK_DETAIL_BYTES } from "./state-file.js";
37
+ export const MACHINE_CHECKS = [
38
+ { id: "check-hq-update", path: ".claude/hooks/check-hq-update.sh", event: "SessionStart", timeoutMs: 30_000 },
39
+ { id: "check-client-health", path: ".claude/hooks/check-client-health.sh", event: "SessionStart", timeoutMs: 30_000 },
40
+ { id: "check-stale-model-pin", path: ".claude/hooks/check-stale-model-pin.sh", event: "SessionStart", timeoutMs: 15_000 },
41
+ { id: "desktop-memory-leak-check", path: ".claude/hooks/check-claude-desktop-bridge-health.sh", event: "SessionStart", timeoutMs: 30_000 },
42
+ { id: "repair-stale-review-base", path: ".claude/hooks/repair-stale-review-base.sh", event: "SessionStart", timeoutMs: 30_000 },
43
+ { id: "welcome-brief-ready", path: ".claude/hooks/welcome-brief-ready.sh", event: "SessionStart", timeoutMs: 10_000 },
44
+ { id: "refresh-vault-access", path: "core/scripts/refresh-vault-access-session-start.sh", event: "SessionStart", timeoutMs: 5_000 },
45
+ { id: "setup-completeness-nag", path: "core/hooks/SessionStart/20-setup-completeness-nag.sh", event: "SessionStart", timeoutMs: 60_000 },
46
+ { id: "fingerprint-hooks-enable", path: "core/hooks/SessionStart/40-fingerprint-hooks-enable.sh", event: "SessionStart", timeoutMs: 60_000 },
47
+ { id: "agent-browser-presence-check", path: "core/hooks/SessionStart/50-agent-browser-presence-check.sh", event: "SessionStart", timeoutMs: 60_000 },
48
+ { id: "ensure-hq-cli", path: "core/hooks/UserPromptSubmit/30-ensure-hq-cli.sh", event: "UserPromptSubmit", timeoutMs: 60_000 },
49
+ { id: "ensure-hq-desktop", path: "core/hooks/UserPromptSubmit/31-ensure-hq-desktop.sh", event: "UserPromptSubmit", timeoutMs: 60_000 },
50
+ ];
51
+ export const MACHINE_CHECK_IDS = new Set(MACHINE_CHECKS.map((check) => check.id));
52
+ /** The results file in the daemon folder. */
53
+ export const MACHINE_CHECKS_RESULT_FILE = "machine-checks.json";
54
+ /** stdout kept per script; the rest is read and dropped. */
55
+ export const MACHINE_CHECK_STDOUT_BYTES = 64 * 1024;
56
+ export const MACHINE_CHECK_SUMMARY_CHARS = 240;
57
+ /** Wait between SIGTERM and SIGKILL on a timed-out script. */
58
+ export const MACHINE_CHECK_KILL_GRACE_MS = 2_000;
59
+ /** After the script exits, how long its stdout may still deliver buffered bytes. */
60
+ export const MACHINE_CHECK_DRAIN_MS = 50;
61
+ const SESSION_ID = "hq-machine-checks";
62
+ const FINGERPRINT = /^[0-9a-f]{64}$/;
63
+ const STATUSES = new Set(["ok", "warn", "fail", "unknown"]);
64
+ /** The finding text a script's stdout carries: empty means nothing to report. */
65
+ export function findingText(stdout) {
66
+ const trimmed = stdout.trim();
67
+ if (!trimmed)
68
+ return "";
69
+ if (trimmed.startsWith("{")) {
70
+ try {
71
+ const parsed = JSON.parse(trimmed);
72
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
73
+ const hook = parsed.hookSpecificOutput;
74
+ const context = hook && typeof hook === "object" ? hook.additionalContext : undefined;
75
+ if (typeof context === "string")
76
+ return context.trim();
77
+ }
78
+ }
79
+ catch {
80
+ // not JSON: the text is stdout itself
81
+ }
82
+ }
83
+ return trimmed;
84
+ }
85
+ /** First non-empty line with `<tag>` and `</tag>` markers removed, at most 240 characters. */
86
+ export function findingSummary(text) {
87
+ for (const line of text.split(/\r?\n/)) {
88
+ const plain = line.replace(/<\/?[A-Za-z][\w.:-]*\s*\/?>/g, "").trim();
89
+ if (plain)
90
+ return Array.from(plain).slice(0, MACHINE_CHECK_SUMMARY_CHARS).join("");
91
+ }
92
+ return "";
93
+ }
94
+ /** Lowercase hex SHA-256 of `<id>\n<detail>`, the detail's invalid UTF-8 already replaced by U+FFFD. */
95
+ export function findingFingerprint(id, detail) {
96
+ return createHash("sha256").update(Buffer.from(`${id}\n${detail}`, "utf8")).digest("hex");
97
+ }
98
+ /** A script's result from its stdout bytes. */
99
+ export function resultFromStdout(id, stdout, checkedAt) {
100
+ // toString replaces every invalid UTF-8 sequence with U+FFFD.
101
+ const text = findingText(stdout.toString("utf8"));
102
+ if (!text)
103
+ return { id, status: "ok", checked_at: checkedAt };
104
+ const detail = cutUtf8(text, MACHINE_CHECK_DETAIL_BYTES);
105
+ const summary = findingSummary(detail);
106
+ return {
107
+ id,
108
+ status: "warn",
109
+ checked_at: checkedAt,
110
+ ...(summary ? { summary } : {}),
111
+ detail,
112
+ fingerprint: findingFingerprint(id, detail),
113
+ };
114
+ }
115
+ function disabledIds(env) {
116
+ return new Set((env.HQ_DISABLED_HOOKS ?? "").split(",").map((id) => id.trim()).filter(Boolean));
117
+ }
118
+ /** The script's absolute path when it may be run; else why not. */
119
+ export function checkMachineCheckScript(hqRoot, relative) {
120
+ const root = path.resolve(hqRoot);
121
+ const file = path.resolve(root, ...relative.split("/"));
122
+ if (!file.startsWith(root + path.sep))
123
+ return { ok: false, summary: "refused: outside-root" };
124
+ const opened = openStoreDir(path.dirname(file));
125
+ if (!opened.ok) {
126
+ return { ok: false, summary: opened.code === "folder-missing" ? "not installed" : `refused: ${opened.code}` };
127
+ }
128
+ const store = opened.value;
129
+ try {
130
+ // The folder, followed through every link above it, must still be inside the root.
131
+ let realRoot;
132
+ let realFolder;
133
+ try {
134
+ realRoot = fs.realpathSync(root);
135
+ realFolder = fs.realpathSync(path.dirname(file));
136
+ }
137
+ catch {
138
+ return { ok: false, summary: "refused: io-error" };
139
+ }
140
+ if (!realFolder.startsWith(realRoot + path.sep))
141
+ return { ok: false, summary: "refused: outside-root" };
142
+ const stat = store.stat(path.basename(file));
143
+ if (!stat.ok)
144
+ return { ok: false, summary: stat.code === "missing" ? "not installed" : `refused: ${stat.code}` };
145
+ return { ok: true, file };
146
+ }
147
+ finally {
148
+ store.close();
149
+ }
150
+ }
151
+ function payload(event, hqRoot) {
152
+ return event === "SessionStart"
153
+ ? JSON.stringify({ hook_event_name: "SessionStart", source: "startup", session_id: SESSION_ID, cwd: hqRoot })
154
+ : JSON.stringify({ hook_event_name: "UserPromptSubmit", prompt: "", session_id: SESSION_ID, cwd: hqRoot });
155
+ }
156
+ /**
157
+ * `/bin/bash <file>` with the payload on stdin. Waits for the direct child's
158
+ * exit, not for stdout to close, so a detached grandchild holding stdout open
159
+ * does not delay the result. A timeout sends SIGTERM and then SIGKILL to the
160
+ * direct child only, never to its process group.
161
+ */
162
+ function runScript(file, spec, hqRoot, env, killGraceMs, drainMs) {
163
+ return new Promise((resolve) => {
164
+ const chunks = [];
165
+ let kept = 0;
166
+ let child;
167
+ try {
168
+ child = spawn("/bin/bash", [file], {
169
+ cwd: hqRoot,
170
+ env: {
171
+ ...env,
172
+ CLAUDE_PROJECT_DIR: hqRoot,
173
+ HQ_ROOT: hqRoot,
174
+ HQ_MACHINE_CHECK: "1",
175
+ HQ_MACHINE_CHECKS_RUNNING: "1",
176
+ },
177
+ stdio: ["pipe", "pipe", "ignore"],
178
+ shell: false,
179
+ windowsHide: true,
180
+ });
181
+ }
182
+ catch {
183
+ resolve({ stdout: Buffer.alloc(0), outcome: "crashed", code: null, signal: null });
184
+ return;
185
+ }
186
+ let timedOut = false;
187
+ let settled = false;
188
+ let killTimer;
189
+ const timeout = setTimeout(() => {
190
+ timedOut = true;
191
+ child.kill("SIGTERM");
192
+ killTimer = setTimeout(() => child.kill("SIGKILL"), killGraceMs);
193
+ }, spec.timeoutMs);
194
+ child.stdout?.on("data", (chunk) => {
195
+ if (kept >= MACHINE_CHECK_STDOUT_BYTES)
196
+ return;
197
+ const part = chunk.subarray(0, MACHINE_CHECK_STDOUT_BYTES - kept);
198
+ chunks.push(part);
199
+ kept += part.length;
200
+ });
201
+ child.stdout?.on("error", () => { });
202
+ child.stdin?.on("error", () => { });
203
+ const finish = (run) => {
204
+ if (settled)
205
+ return;
206
+ settled = true;
207
+ clearTimeout(timeout);
208
+ if (killTimer)
209
+ clearTimeout(killTimer);
210
+ setTimeout(() => {
211
+ child.stdout?.destroy();
212
+ resolve({ ...run, stdout: Buffer.concat(chunks) });
213
+ }, drainMs);
214
+ };
215
+ child.on("error", () => finish({ outcome: "crashed", code: null, signal: null }));
216
+ child.on("exit", (code, signal) => {
217
+ finish({ outcome: timedOut ? "timed-out" : signal ? "crashed" : "exited", code, signal });
218
+ });
219
+ child.stdin?.end(payload(spec.event, hqRoot));
220
+ });
221
+ }
222
+ async function runOne(spec, options, env, disabled) {
223
+ const now = options.now ?? (() => new Date());
224
+ const at = () => now().toISOString();
225
+ if (disabled.has(spec.id))
226
+ return { id: spec.id, status: "ok", checked_at: at(), summary: "disabled by HQ_DISABLED_HOOKS" };
227
+ const checked = checkMachineCheckScript(options.hqRoot, spec.path);
228
+ if (!checked.ok)
229
+ return { id: spec.id, status: "unknown", checked_at: at(), summary: checked.summary };
230
+ const run = await runScript(checked.file, spec, path.resolve(options.hqRoot), env, options.killGraceMs ?? MACHINE_CHECK_KILL_GRACE_MS, options.drainMs ?? MACHINE_CHECK_DRAIN_MS);
231
+ if (run.outcome === "timed-out") {
232
+ return { id: spec.id, status: "unknown", checked_at: at(), summary: `timed out after ${Math.round(spec.timeoutMs / 1000)}s` };
233
+ }
234
+ if (run.outcome === "crashed") {
235
+ return { id: spec.id, status: "unknown", checked_at: at(), summary: run.signal ? `crashed (${run.signal})` : "could not start" };
236
+ }
237
+ if (run.code !== 0) {
238
+ return { id: spec.id, status: "unknown", checked_at: at(), summary: `exited with status ${run.code}` };
239
+ }
240
+ return resultFromStdout(spec.id, run.stdout, at());
241
+ }
242
+ let inFlight;
243
+ /**
244
+ * Run every machine check once, one at a time. A call while a batch is
245
+ * running returns that batch. Inside a machine check
246
+ * (HQ_MACHINE_CHECKS_RUNNING=1) nothing runs and the answer is empty.
247
+ */
248
+ export function runMachineChecks(options) {
249
+ const env = options.env ?? process.env;
250
+ if (env.HQ_MACHINE_CHECKS_RUNNING === "1")
251
+ return Promise.resolve([]);
252
+ if (inFlight)
253
+ return inFlight;
254
+ const batch = (async () => {
255
+ const disabled = disabledIds(env);
256
+ const results = [];
257
+ for (const spec of options.checks ?? MACHINE_CHECKS) {
258
+ results.push(await runOne(spec, options, env, disabled));
259
+ }
260
+ if (options.resultsFile)
261
+ writeMachineCheckResults(options.resultsFile, results, options.resultsWrite);
262
+ return results;
263
+ })();
264
+ inFlight = batch;
265
+ const clear = () => {
266
+ if (inFlight === batch)
267
+ inFlight = undefined;
268
+ };
269
+ batch.then(clear, clear);
270
+ return batch;
271
+ }
272
+ /** Written atomically through src/lib/safe-store.ts in the daemon's private folder. */
273
+ export function writeMachineCheckResults(file, results, options = {}) {
274
+ writeStoreFile(file, `${JSON.stringify({ results })}\n`, { create: true, ...options });
275
+ }
276
+ function validResult(value) {
277
+ if (!value || typeof value !== "object" || Array.isArray(value))
278
+ return null;
279
+ const entry = value;
280
+ const allowed = new Set(["id", "status", "checked_at", "summary", "detail", "fingerprint"]);
281
+ if (Object.keys(entry).some((key) => !allowed.has(key)))
282
+ return null;
283
+ if (typeof entry.id !== "string" || !MACHINE_CHECK_IDS.has(entry.id))
284
+ return null;
285
+ if (typeof entry.status !== "string" || !STATUSES.has(entry.status))
286
+ return null;
287
+ if (typeof entry.checked_at !== "string" || !Number.isFinite(Date.parse(entry.checked_at)))
288
+ return null;
289
+ if (entry.summary !== undefined && (typeof entry.summary !== "string" || entry.summary.length > MACHINE_CHECK_SUMMARY_CHARS * 2))
290
+ return null;
291
+ if (entry.detail !== undefined
292
+ && (typeof entry.detail !== "string" || Buffer.byteLength(entry.detail, "utf8") > MACHINE_CHECK_DETAIL_BYTES))
293
+ return null;
294
+ if (entry.fingerprint !== undefined && (typeof entry.fingerprint !== "string" || !FINGERPRINT.test(entry.fingerprint)))
295
+ return null;
296
+ return {
297
+ id: entry.id,
298
+ status: entry.status,
299
+ checked_at: entry.checked_at,
300
+ ...(entry.summary !== undefined ? { summary: entry.summary } : {}),
301
+ ...(entry.detail !== undefined ? { detail: entry.detail } : {}),
302
+ ...(entry.fingerprint !== undefined ? { fingerprint: entry.fingerprint } : {}),
303
+ };
304
+ }
305
+ /**
306
+ * The latest results, or [] when the file is missing, refused by the store
307
+ * rules (a link, a second link, another user's, writable by others) or has
308
+ * any invalid field.
309
+ */
310
+ export function readMachineCheckResults(file) {
311
+ const read = readStoreFile(file, 256 * 1024);
312
+ if (!read)
313
+ return [];
314
+ try {
315
+ const parsed = JSON.parse(read.text);
316
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
317
+ return [];
318
+ const results = parsed.results;
319
+ if (!Array.isArray(results) || results.length > MACHINE_CHECKS.length)
320
+ return [];
321
+ const out = [];
322
+ for (const each of results) {
323
+ const valid = validResult(each);
324
+ if (!valid)
325
+ return [];
326
+ out.push(valid);
327
+ }
328
+ return out;
329
+ }
330
+ catch {
331
+ return [];
332
+ }
333
+ }
334
+ /** First batch about a minute after the daemon starts, then hourly. */
335
+ export const MACHINE_CHECKS_FIRST_DELAY_MS = 60_000;
336
+ export const MACHINE_CHECKS_INTERVAL_MS = 60 * 60_000;
337
+ /** Batches never start closer together than this. */
338
+ export const MACHINE_CHECKS_MIN_INTERVAL_MS = 15 * 60_000;
339
+ /** Use the same offline flag decision as hook registration. */
340
+ export const machineChecksCoreNextOn = coreNextEnabled;
341
+ /**
342
+ * A switch that sends this machine back to the old hook core is set:
343
+ * HQ_CORE_NEXT is off, 0, false or no; HQ_HOOK_ENGINE is off (both trimmed,
344
+ * any ASCII case); or `<home>/.hq/state/core-next.off` or
345
+ * `<home>/.hq/hook-engine.off` exists (any file type, a link counts). These
346
+ * are the switches the hook engine checks.
347
+ */
348
+ export function machineChecksKillSwitchSet(env, home) {
349
+ return coreNextKillReason(home, env) !== null;
350
+ }
351
+ /**
352
+ * The daemon's schedule runs when the new hook core (`core.next`) is on for
353
+ * this machine and no kill switch is set, so the checks leave the hook path
354
+ * exactly when the machine moves to the new core and nothing runs twice.
355
+ */
356
+ export function machineChecksScheduleOn(env, home) {
357
+ return !machineChecksKillSwitchSet(env, home) && machineChecksCoreNextOn(env);
358
+ }
359
+ /**
360
+ * The daemon's machine-check timer. Each tick runs a batch only when the new
361
+ * hook core (`core.next`) is on for this machine and no kill switch is set;
362
+ * both are read at every tick, so turning either off stops the next run
363
+ * without a daemon restart. A batch already running finishes. A failed batch
364
+ * logs one line with the error's name only.
365
+ */
366
+ export function startMachineCheckSchedule(options) {
367
+ const now = options.now ?? (() => Date.now());
368
+ const interval = Math.max(options.intervalMs ?? MACHINE_CHECKS_INTERVAL_MS, MACHINE_CHECKS_MIN_INTERVAL_MS);
369
+ const run = options.run ?? runMachineChecks;
370
+ const enabled = options.enabled ?? machineChecksScheduleOn;
371
+ let lastStart;
372
+ let closed = false;
373
+ const tick = async () => {
374
+ try {
375
+ if (closed)
376
+ return;
377
+ if (lastStart !== undefined && now() - lastStart < MACHINE_CHECKS_MIN_INTERVAL_MS)
378
+ return;
379
+ if (!enabled(options.env, options.home))
380
+ return;
381
+ const hqRoot = options.hqRoot();
382
+ if (!hqRoot || closed)
383
+ return;
384
+ if (process.platform === "win32" || !(options.registered ?? anyNativeSessionStartRegistered)(hqRoot, options.home, options.env)) {
385
+ options.log("info", "machine checks skipped: no native SessionStart");
386
+ return;
387
+ }
388
+ lastStart = now();
389
+ await run({ hqRoot, env: options.env, resultsFile: options.resultsFile });
390
+ }
391
+ catch (error) {
392
+ options.log("warn", `machine checks failed (${error instanceof Error ? error.name : "UnknownError"})`);
393
+ }
394
+ };
395
+ let repeat;
396
+ const first = setTimeout(() => {
397
+ void tick();
398
+ repeat = setInterval(() => void tick(), interval);
399
+ repeat.unref?.();
400
+ }, options.firstDelayMs ?? MACHINE_CHECKS_FIRST_DELAY_MS);
401
+ first.unref?.();
402
+ return {
403
+ tick,
404
+ close() {
405
+ closed = true;
406
+ clearTimeout(first);
407
+ if (repeat)
408
+ clearInterval(repeat);
409
+ },
410
+ };
411
+ }
412
+ //# sourceMappingURL=machine-checks.js.map
@@ -21,6 +21,7 @@ import { spawn } from "node:child_process";
21
21
  import * as fs from "node:fs";
22
22
  import * as path from "node:path";
23
23
  import { sessionMetaCompanies } from "../../core-utils/session-company.js";
24
+ import { withoutHookEnv } from "../hook-env.js";
24
25
  export const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
25
26
  export const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
26
27
  const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
@@ -328,8 +329,11 @@ export async function policyCheck(args, deps) {
328
329
  tool_input: args.input ?? {},
329
330
  cwd: args.cwd ?? hqRoot,
330
331
  });
332
+ // Identity reaches the hook scripts through the payload above and nowhere
333
+ // else. They trust HQ_HOOK_* over the payload, so nothing with that prefix
334
+ // may pass from the daemon's environment (see ../hook-env.ts).
331
335
  const env = {
332
- ...(deps.env ?? process.env),
336
+ ...withoutHookEnv(deps.env ?? process.env),
333
337
  HQ_ROOT: hqRoot,
334
338
  CLAUDE_PROJECT_DIR: hqRoot,
335
339
  BASH_ENV: "/dev/null",
@@ -338,8 +342,6 @@ export async function policyCheck(args, deps) {
338
342
  delete env.HQ_POLICY_COMPANY;
339
343
  else
340
344
  env.HQ_POLICY_COMPANY = args.company;
341
- delete env.HQ_HOOK_SESSION_ID;
342
- delete env.HQ_HOOK_TOOL_NAME;
343
345
  const timeoutMs = deps.timeoutMs ?? 15_000;
344
346
  const reasons = [];
345
347
  let decision = "allow";
@@ -32,6 +32,7 @@ import { daemonLanesReconcileHandler } from "../lanes/daemon-reconcile.js";
32
32
  import { ensureDaemonLanesReconcileHandler } from "./lanes-reconcile-loader.js";
33
33
  import { SUPERVISOR_HANDOFF_FLAG, createDaemonFlagSnapshotSource, readDaemonFlag } from "./flag.js";
34
34
  import { createDaemonKillSwitchMonitors } from "./timed-flag-monitors.js";
35
+ import { MACHINE_CHECKS_RESULT_FILE, readMachineCheckResults, startMachineCheckSchedule } from "./machine-checks.js";
35
36
  import { createLanesReconcileWatcher } from "./lanes-reconcile-watcher.js";
36
37
  import { findLegacyUnits, legacyMeshUnitsToRetire, legacyOwnerLookup, } from "./legacy.js";
37
38
  import { readLegacySyncEnv } from "./legacy-sync-env.js";
@@ -50,8 +51,9 @@ import { SELF_CHECK_RESULT_FILE, readSelfCheckResult } from "./selfcheck.js";
50
51
  import { createDaemonStateWriter, daemonStateFilePath, defaultDaemonStateFilePath, readVaultAccessManifest, selfCheckMachineChecks, } from "./state-file.js";
51
52
  import { hqdSocketPath } from "./protocol.js";
52
53
  import { startHqdServer, syncHqdEnabledMarker } from "./server.js";
53
- import { startHqdRuntimeListener } from "./anywhere-listener.js";
54
+ import { createHqdRuntimeEvents, observeHqdRuntimeFlag, startHqdRuntimeListener } from "./anywhere-listener.js";
54
55
  import { heartbeatFile, startHeartbeat } from "./heartbeat.js";
56
+ import { daemonStartEnv } from "./hook-env.js";
55
57
  import { createProtocolTail, ensureProtocolFifo, openProtocolWriter } from "./protocol-tail.js";
56
58
  import { takeControlRequests } from "./requests.js";
57
59
  import { currentHqCloud, currentHqCloudAfterLeaseRelease, hqCloudRunners, hqCloudVersionOlder } from "./hq-cloud.js";
@@ -652,7 +654,9 @@ export function withUserRuntimeDir(env, host) {
652
654
  return host.exists(dir) ? { ...env, XDG_RUNTIME_DIR: dir } : env;
653
655
  }
654
656
  export async function runDaemon(opts) {
655
- const env = withUserRuntimeDir(opts.env ?? process.env, {
657
+ // Before anything reads the environment: hqd and every service inherit it.
658
+ const started = daemonStartEnv(opts.env);
659
+ const env = withUserRuntimeDir(started.env, {
656
660
  platform: process.platform,
657
661
  uid: process.getuid?.() ?? -1,
658
662
  exists: fs.existsSync,
@@ -747,6 +751,9 @@ export async function runDaemon(opts) {
747
751
  }
748
752
  const hostNote = opts.host ? `, hosted by the ${opts.host} app` : "";
749
753
  log("info", `starting hq daemon (pid ${process.pid}) as ${machineType} (${detected.detail})${hostNote}`);
754
+ if (started.removed.length > 0) {
755
+ log("warn", `started with hook fields in the environment; dropped them so policy checks use their own payload: ${started.removed.join(", ")}`);
756
+ }
750
757
  try {
751
758
  scheduleDaemonPlistRefresh({
752
759
  platform,
@@ -916,14 +923,37 @@ export async function runDaemon(opts) {
916
923
  const configured = readDaemonConfig(paths.configPath).hqRoot ?? (env.HQ_ROOT?.trim() || undefined);
917
924
  return readVaultAccessManifest(configured && fs.existsSync(configured) ? configured : undefined);
918
925
  },
919
- readMachineChecks: () => selfCheckMachineChecks(readSelfCheckResult(path.join(paths.root, SELF_CHECK_RESULT_FILE))),
926
+ readMachineChecks: () => [
927
+ ...selfCheckMachineChecks(readSelfCheckResult(path.join(paths.root, SELF_CHECK_RESULT_FILE))),
928
+ ...readMachineCheckResults(path.join(paths.root, MACHINE_CHECKS_RESULT_FILE)),
929
+ ],
930
+ });
931
+ // The hqd listener checks again when a shared read's HQ Anywhere answer
932
+ // changes, or the running server's runtime gate changes; it has no timer of
933
+ // its own beyond a rare fallback (anywhere-listener.ts).
934
+ const hqdRuntimeEvents = createHqdRuntimeEvents();
935
+ const observeHqdRuntime = observeHqdRuntimeFlag(() => hqdRuntimeEvents.emit());
936
+ const flagSnapshots = createDaemonFlagSnapshotSource({
937
+ onRead: (read, readEnv) => {
938
+ observeHqdRuntime(read, readEnv);
939
+ stateWriter.onRegistryRead(read, readEnv);
940
+ },
920
941
  });
921
- const flagSnapshots = createDaemonFlagSnapshotSource({ onRead: stateWriter.onRegistryRead });
922
942
  const killSwitches = createDaemonKillSwitchMonitors({ env, log, snapshots: flagSnapshots });
923
943
  const childBootstrapHandoffWatchFlag = killSwitches.childBootstrapHandoffWatch;
924
944
  const lanesReconcileFileWatchFlag = killSwitches.lanesReconcileFileWatch;
925
945
  const searchIndexRunnerOwnsIndexFlag = killSwitches.searchIndexRunnerOwnsIndex;
926
946
  const syncProcessScanOnMissingFlag = killSwitches.syncProcessScanOnMissing;
947
+ const machineChecks = startMachineCheckSchedule({
948
+ env,
949
+ home,
950
+ log,
951
+ hqRoot: () => {
952
+ const configured = readDaemonConfig(paths.configPath).hqRoot ?? (env.HQ_ROOT?.trim() || undefined);
953
+ return configured && fs.existsSync(configured) ? configured : undefined;
954
+ },
955
+ resultsFile: path.join(paths.root, MACHINE_CHECKS_RESULT_FILE),
956
+ });
927
957
  let laneReconcileWatcher = null;
928
958
  let laneReconcileWatcherRoot = null;
929
959
  let laneReconcileWatchFailedRoot = null;
@@ -951,6 +981,7 @@ export async function runDaemon(opts) {
951
981
  laneReconcileWatcher = null;
952
982
  laneReconcileWatcherRoot = null;
953
983
  killSwitches.close();
984
+ machineChecks.close();
954
985
  flagSnapshots.close();
955
986
  stateWriter.close();
956
987
  };
@@ -1482,6 +1513,7 @@ export async function runDaemon(opts) {
1482
1513
  hqRoot,
1483
1514
  log,
1484
1515
  flagSnapshots,
1516
+ onRuntimeChange: () => hqdRuntimeEvents.emit(),
1485
1517
  onShutdown: () => hqdShutdown?.(),
1486
1518
  reportError: reportHqdCrash,
1487
1519
  observeError: (err) => tccEpermGuard.observe(err),
@@ -1500,7 +1532,7 @@ export async function runDaemon(opts) {
1500
1532
  log,
1501
1533
  });
1502
1534
  },
1503
- intervalMs: 60_000,
1535
+ subscribe: (notify) => hqdRuntimeEvents.subscribe(notify),
1504
1536
  log: (error) => log("error", `hqd socket listener update failed: ${error.message ?? String(error)}`),
1505
1537
  });
1506
1538
  const closeHqd = () => {
@@ -47,6 +47,8 @@ export interface HqdServerOptions {
47
47
  personSettingReader?: () => Promise<boolean | null>;
48
48
  /** The daemon's shared flag read, so this server's runtime gate adds no registry request of its own. */
49
49
  flagSnapshots?: DaemonFlagSnapshotSource;
50
+ /** Told when this server's runtime gate (flag and person setting) changes, so the daemon's listener checks at once. */
51
+ onRuntimeChange?: (enabled: boolean) => void;
50
52
  /** Test seam for the hosted Streamable HTTP MCP transport. */
51
53
  mcpBridge?: HqMcpBridge;
52
54
  /** Test seam for machine login while keeping production credentials off disk. */
@@ -411,6 +411,12 @@ export async function startHqdServer(opts) {
411
411
  ephemeralMachineToken = undefined;
412
412
  sessions.clear();
413
413
  }
414
+ try {
415
+ opts.onRuntimeChange?.(enabled);
416
+ }
417
+ catch (error) {
418
+ log("warn", `hqd runtime change observer failed (${error instanceof Error ? error.name : "UnknownError"})`);
419
+ }
414
420
  },
415
421
  onReadError: (error) => {
416
422
  log("warn", `hqd runtime flag refresh failed (${error instanceof Error ? error.name : "UnknownError"}); retaining the last decision only until its 60-second limit`);
@@ -10,7 +10,10 @@
10
10
  * list is enforced, and the granted paths with their permission. It is
11
11
  * copied from <hqRoot>/.hq/vault-access.json, field by field;
12
12
  * - machine_checks: the latest results of the machine checks the daemon has
13
- * today (id, status, time, optional one-line summary).
13
+ * today (id, status, time, optional one-line summary, and for a finding
14
+ * its text, cut to 4096 bytes, and a fingerprint the hook engine uses to
15
+ * show it once). The finding text can name local paths, so like the rest
16
+ * of the file it is never logged or sent.
14
17
  *
15
18
  * No token, key or other secret is written. The vault access list tells which
16
19
  * companies and paths a person can reach, so the file lives in the per-host
@@ -64,7 +67,15 @@ export interface DaemonStateMachineCheck {
64
67
  status: "ok" | "warn" | "fail" | "unknown";
65
68
  checked_at: string;
66
69
  summary?: string;
70
+ /** The finding text, at most MACHINE_CHECK_DETAIL_BYTES, cut on a UTF-8 boundary. */
71
+ detail?: string;
72
+ /** 64 lowercase hex characters; any other value is dropped. */
73
+ fingerprint?: string;
67
74
  }
75
+ /** The longest machine-check `detail` written, in UTF-8 bytes. */
76
+ export declare const MACHINE_CHECK_DETAIL_BYTES = 4096;
77
+ /** `text` cut to at most `maxBytes` of UTF-8, never inside a character. */
78
+ export declare function cutUtf8(text: string, maxBytes: number): string;
68
79
  export interface DaemonStateFile {
69
80
  schema: typeof DAEMON_STATE_SCHEMA;
70
81
  written_at: string;
@@ -10,7 +10,10 @@
10
10
  * list is enforced, and the granted paths with their permission. It is
11
11
  * copied from <hqRoot>/.hq/vault-access.json, field by field;
12
12
  * - machine_checks: the latest results of the machine checks the daemon has
13
- * today (id, status, time, optional one-line summary).
13
+ * today (id, status, time, optional one-line summary, and for a finding
14
+ * its text, cut to 4096 bytes, and a fingerprint the hook engine uses to
15
+ * show it once). The finding text can name local paths, so like the rest
16
+ * of the file it is never logged or sent.
14
17
  *
15
18
  * No token, key or other secret is written. The vault access list tells which
16
19
  * companies and paths a person can reach, so the file lives in the per-host
@@ -54,6 +57,19 @@ const HOOK_ENGINE_PORT_MODES = new Set(["off", "shadow", "on"]);
54
57
  const VAULT_PERMISSIONS = new Set(["read", "write", "admin"]);
55
58
  const VAULT_ROLES = new Set(["owner", "admin", "member", "guest", "unknown"]);
56
59
  const MACHINE_CHECK_STATUSES = new Set(["ok", "warn", "fail", "unknown"]);
60
+ /** The longest machine-check `detail` written, in UTF-8 bytes. */
61
+ export const MACHINE_CHECK_DETAIL_BYTES = 4096;
62
+ const FINGERPRINT = /^[0-9a-f]{64}$/;
63
+ /** `text` cut to at most `maxBytes` of UTF-8, never inside a character. */
64
+ export function cutUtf8(text, maxBytes) {
65
+ const bytes = Buffer.from(text, "utf8");
66
+ if (bytes.length <= maxBytes)
67
+ return bytes.toString("utf8");
68
+ let end = maxBytes;
69
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
70
+ end -= 1;
71
+ return bytes.subarray(0, end).toString("utf8");
72
+ }
57
73
  /** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
58
74
  export function daemonStateFilePath(home, env = process.env) {
59
75
  const explicit = env.HQ_STATE_FILE?.trim();
@@ -176,6 +192,12 @@ function machineChecksOf(results) {
176
192
  status: result.status,
177
193
  checked_at: result.checked_at,
178
194
  ...(typeof result.summary === "string" && result.summary ? { summary: result.summary.slice(0, 240) } : {}),
195
+ ...(typeof result.detail === "string" && result.detail
196
+ ? { detail: cutUtf8(result.detail, MACHINE_CHECK_DETAIL_BYTES) }
197
+ : {}),
198
+ ...(typeof result.fingerprint === "string" && FINGERPRINT.test(result.fingerprint)
199
+ ? { fingerprint: result.fingerprint }
200
+ : {}),
179
201
  });
180
202
  }
181
203
  return out;
@@ -0,0 +1,4 @@
1
+ import { type EngineCapabilities } from '../../../utils/host-registration.js';
2
+ import type { CheckResult } from '../types.js';
3
+ export declare function fleetHookCoreResults(home: string, env: NodeJS.ProcessEnv, inspect?: (engine: string) => EngineCapabilities): CheckResult[];
4
+ //# sourceMappingURL=fleet-hook-core.d.ts.map