@indigoai-us/hq-cli 5.345.218 → 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 (62) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/command-catalog.generated.d.ts +69 -0
  3. package/dist/command-catalog.generated.js +83 -0
  4. package/dist/commands/agents.d.ts +22 -0
  5. package/dist/commands/agents.js +92 -1
  6. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  7. package/dist/commands/core-hook-registration-plan.js +21 -0
  8. package/dist/commands/core.js +9 -0
  9. package/dist/commands/doctor.js +4 -0
  10. package/dist/commands/lanes-shared.d.ts +2 -0
  11. package/dist/commands/lanes-watch.js +28 -1
  12. package/dist/commands/lanes.d.ts +2 -0
  13. package/dist/commands/lanes.js +99 -9
  14. package/dist/commands/reindex.js +6 -0
  15. package/dist/index.js +8 -0
  16. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  17. package/dist/lib/anywhere-person-setting.js +2 -2
  18. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  19. package/dist/lib/daemon/anywhere-listener.js +86 -4
  20. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  21. package/dist/lib/daemon/machine-check-owner.js +95 -0
  22. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  23. package/dist/lib/daemon/machine-check-registration.js +64 -0
  24. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  25. package/dist/lib/daemon/machine-checks.js +412 -0
  26. package/dist/lib/daemon/run.js +30 -4
  27. package/dist/lib/daemon/server.d.ts +2 -0
  28. package/dist/lib/daemon/server.js +6 -0
  29. package/dist/lib/daemon/state-file.d.ts +12 -1
  30. package/dist/lib/daemon/state-file.js +23 -1
  31. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +4 -0
  32. package/dist/lib/doctor/checks/fleet-hook-core.js +103 -0
  33. package/dist/lib/doctor/checks/host-core.js +3 -1
  34. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  35. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  36. package/dist/lib/doctor/registry.js +4 -0
  37. package/dist/lib/doctor/types.d.ts +4 -0
  38. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  39. package/dist/lib/hook-engine/canary-gate.js +147 -0
  40. package/dist/lib/hook-engine/coverage.d.ts +3 -1
  41. package/dist/lib/hook-engine/coverage.js +8 -2
  42. package/dist/lib/hook-engine/fleet-registration.d.ts +30 -0
  43. package/dist/lib/hook-engine/fleet-registration.js +132 -0
  44. package/dist/lib/hook-engine/reconcile.js +3 -2
  45. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  46. package/dist/lib/hook-engine/registration-identity.js +97 -0
  47. package/dist/lib/hook-engine/registration.d.ts +1 -30
  48. package/dist/lib/hook-engine/registration.js +1 -88
  49. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  50. package/dist/lib/hook-engine/resolve.js +7 -3
  51. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  52. package/dist/lib/lanes/canonical-host.js +9 -3
  53. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  54. package/dist/lib/lanes/machine-identity.js +26 -0
  55. package/dist/lib/lanes/spawn.js +17 -3
  56. package/dist/utils/core-next-flag.d.ts +4 -0
  57. package/dist/utils/core-next-flag.js +22 -0
  58. package/dist/utils/core-next-kill.d.ts +16 -0
  59. package/dist/utils/core-next-kill.js +35 -0
  60. package/dist/utils/host-registration.d.ts +33 -23
  61. package/dist/utils/host-registration.js +86 -66
  62. package/package.json +8 -8
@@ -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
@@ -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
@@ -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,7 +51,7 @@ 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";
55
56
  import { daemonStartEnv } from "./hook-env.js";
56
57
  import { createProtocolTail, ensureProtocolFifo, openProtocolWriter } from "./protocol-tail.js";
@@ -922,14 +923,37 @@ export async function runDaemon(opts) {
922
923
  const configured = readDaemonConfig(paths.configPath).hqRoot ?? (env.HQ_ROOT?.trim() || undefined);
923
924
  return readVaultAccessManifest(configured && fs.existsSync(configured) ? configured : undefined);
924
925
  },
925
- 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
+ },
926
941
  });
927
- const flagSnapshots = createDaemonFlagSnapshotSource({ onRead: stateWriter.onRegistryRead });
928
942
  const killSwitches = createDaemonKillSwitchMonitors({ env, log, snapshots: flagSnapshots });
929
943
  const childBootstrapHandoffWatchFlag = killSwitches.childBootstrapHandoffWatch;
930
944
  const lanesReconcileFileWatchFlag = killSwitches.lanesReconcileFileWatch;
931
945
  const searchIndexRunnerOwnsIndexFlag = killSwitches.searchIndexRunnerOwnsIndex;
932
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
+ });
933
957
  let laneReconcileWatcher = null;
934
958
  let laneReconcileWatcherRoot = null;
935
959
  let laneReconcileWatchFailedRoot = null;
@@ -957,6 +981,7 @@ export async function runDaemon(opts) {
957
981
  laneReconcileWatcher = null;
958
982
  laneReconcileWatcherRoot = null;
959
983
  killSwitches.close();
984
+ machineChecks.close();
960
985
  flagSnapshots.close();
961
986
  stateWriter.close();
962
987
  };
@@ -1488,6 +1513,7 @@ export async function runDaemon(opts) {
1488
1513
  hqRoot,
1489
1514
  log,
1490
1515
  flagSnapshots,
1516
+ onRuntimeChange: () => hqdRuntimeEvents.emit(),
1491
1517
  onShutdown: () => hqdShutdown?.(),
1492
1518
  reportError: reportHqdCrash,
1493
1519
  observeError: (err) => tccEpermGuard.observe(err),
@@ -1506,7 +1532,7 @@ export async function runDaemon(opts) {
1506
1532
  log,
1507
1533
  });
1508
1534
  },
1509
- intervalMs: 60_000,
1535
+ subscribe: (notify) => hqdRuntimeEvents.subscribe(notify),
1510
1536
  log: (error) => log("error", `hqd socket listener update failed: ${error.message ?? String(error)}`),
1511
1537
  });
1512
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`);