@indigoai-us/hq-cli 5.345.220 → 5.345.222

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 (184) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/dist/command-catalog.generated.d.ts +175 -2
  3. package/dist/command-catalog.generated.js +213 -2
  4. package/dist/commands/auth.js +6 -2
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-delegate-w1b.js +9 -3
  10. package/dist/commands/core-stop-autosave.d.ts +21 -0
  11. package/dist/commands/core-stop-autosave.js +300 -0
  12. package/dist/commands/core.js +2 -0
  13. package/dist/commands/daemon.d.ts +6 -0
  14. package/dist/commands/daemon.js +46 -8
  15. package/dist/commands/doctor-usage.d.ts +5 -0
  16. package/dist/commands/doctor-usage.js +25 -0
  17. package/dist/commands/env.d.ts +49 -4
  18. package/dist/commands/env.js +355 -5
  19. package/dist/commands/lanes-shared.d.ts +3 -0
  20. package/dist/commands/lanes.d.ts +3 -0
  21. package/dist/commands/lanes.js +87 -3
  22. package/dist/commands/link.d.ts +2 -0
  23. package/dist/commands/link.js +14 -2
  24. package/dist/commands/mesh.js +23 -3
  25. package/dist/commands/sources.js +3 -3
  26. package/dist/commands/sync-core.d.ts +7 -0
  27. package/dist/commands/sync-core.js +132 -3
  28. package/dist/commands/whoami.js +96 -80
  29. package/dist/data/command-states.json +3 -0
  30. package/dist/lib/bot/config.d.ts +17 -0
  31. package/dist/lib/bot/config.js +13 -0
  32. package/dist/lib/bot/fleet-cron.js +24 -2
  33. package/dist/lib/bot/fleet-local.d.ts +30 -2
  34. package/dist/lib/bot/fleet-local.js +60 -1
  35. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  36. package/dist/lib/bot/grok-login-scope.js +93 -0
  37. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  38. package/dist/lib/bot/legacy-provider-login.js +28 -22
  39. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  40. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  41. package/dist/lib/core-utils/sentry-report.js +2 -0
  42. package/dist/lib/daemon/catalog.js +2 -0
  43. package/dist/lib/daemon/install.d.ts +2 -1
  44. package/dist/lib/daemon/install.js +9 -0
  45. package/dist/lib/daemon/legacy.d.ts +1 -0
  46. package/dist/lib/daemon/legacy.js +5 -2
  47. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  48. package/dist/lib/daemon/machine-check-owner.js +6 -1
  49. package/dist/lib/daemon/machine-checks.d.ts +29 -2
  50. package/dist/lib/daemon/machine-checks.js +64 -13
  51. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  52. package/dist/lib/daemon/mesh-owner.js +166 -0
  53. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  54. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  55. package/dist/lib/daemon/run.d.ts +15 -0
  56. package/dist/lib/daemon/run.js +137 -11
  57. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  58. package/dist/lib/daemon/selfcheck.js +118 -9
  59. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  60. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  61. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  62. package/dist/lib/daemon/stop-autosave.js +111 -0
  63. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  64. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  65. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  66. package/dist/lib/daemon/stop-job-executor.js +126 -0
  67. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  68. package/dist/lib/daemon/stop-jobs.js +599 -0
  69. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  70. package/dist/lib/doctor/checks/host-core.js +1 -1
  71. package/dist/lib/environment/access-probes.d.ts +234 -0
  72. package/dist/lib/environment/access-probes.js +918 -0
  73. package/dist/lib/environment/profile.d.ts +15 -2
  74. package/dist/lib/environment/profile.js +55 -20
  75. package/dist/lib/environment/rfc3339.d.ts +8 -0
  76. package/dist/lib/environment/rfc3339.js +26 -0
  77. package/dist/lib/environment/work-requirements.d.ts +169 -0
  78. package/dist/lib/environment/work-requirements.js +389 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +146 -7
  80. package/dist/lib/hook-engine/coverage.js +1480 -4
  81. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  82. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  83. package/dist/lib/hook-engine/native-stop-compatibility.json +362 -0
  84. package/dist/lib/hook-engine/reconcile.js +2 -2
  85. package/dist/lib/hot-channels/alert.d.ts +2 -2
  86. package/dist/lib/hot-channels/alert.js +8 -5
  87. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  88. package/dist/lib/hot-channels/signals-pass.js +296 -17
  89. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  90. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  91. package/dist/lib/install/hook-target.js +1 -1
  92. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  93. package/dist/lib/lanes/host-capacity.js +17 -2
  94. package/dist/lib/lanes/host-compute.d.ts +90 -0
  95. package/dist/lib/lanes/host-compute.js +185 -0
  96. package/dist/lib/lanes/index.d.ts +2 -0
  97. package/dist/lib/lanes/index.js +1 -0
  98. package/dist/lib/lanes/reconcile.js +22 -1
  99. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  100. package/dist/lib/lanes/resource-usage.js +589 -0
  101. package/dist/lib/lanes/run-size.d.ts +46 -0
  102. package/dist/lib/lanes/run-size.js +197 -0
  103. package/dist/lib/lanes/store.js +27 -0
  104. package/dist/lib/lanes/throttle.d.ts +36 -1
  105. package/dist/lib/lanes/throttle.js +47 -10
  106. package/dist/lib/lanes/types.d.ts +40 -0
  107. package/dist/lib/lanes/types.js +2 -2
  108. package/dist/lib/lanes/watcher.js +13 -4
  109. package/dist/lib/lanes/worker-process.d.ts +25 -2
  110. package/dist/lib/lanes/worker-process.js +71 -19
  111. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  112. package/dist/lib/mesh/live/daemon/config.js +16 -0
  113. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  114. package/dist/lib/mesh/live/daemon/install.js +142 -1
  115. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  116. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  117. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  118. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  119. package/dist/lib/placement/match.d.ts +192 -0
  120. package/dist/lib/placement/match.js +667 -0
  121. package/dist/lib/registry/registry.d.ts +35 -7
  122. package/dist/lib/registry/registry.js +88 -13
  123. package/dist/lib/safe-store.d.ts +14 -0
  124. package/dist/lib/safe-store.js +77 -4
  125. package/dist/lib/scan-packages/index.js +24 -2
  126. package/dist/lib/search-index/index.d.ts +88 -4
  127. package/dist/lib/search-index/index.js +288 -24
  128. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  129. package/dist/lib/search-index/max-doc-bytes.js +49 -23
  130. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  131. package/dist/lib/service-manager/startup-migration.js +3 -0
  132. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  133. package/dist/lib/signals/codex-lockdown.js +271 -0
  134. package/dist/lib/signals/codex-login.d.ts +37 -0
  135. package/dist/lib/signals/codex-login.js +83 -0
  136. package/dist/lib/signals/engine.d.ts +27 -0
  137. package/dist/lib/signals/engine.js +70 -0
  138. package/dist/lib/signals/reply.js +22 -1
  139. package/dist/lib/signals/run-record.js +6 -1
  140. package/dist/lib/signals/settings.d.ts +5 -0
  141. package/dist/lib/signals/settings.js +2 -0
  142. package/dist/lib/signals/steps/extract.d.ts +85 -9
  143. package/dist/lib/signals/steps/extract.js +317 -68
  144. package/dist/lib/signals/steps/types.d.ts +2 -0
  145. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  146. package/dist/lib/sync-core/engine-holds.js +60 -0
  147. package/dist/lib/sync-core/engine-home.d.ts +37 -1
  148. package/dist/lib/sync-core/engine-home.js +119 -16
  149. package/dist/lib/sync-core/reconcile.js +8 -0
  150. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  151. package/dist/lib/sync-core/rollout-state.js +5 -2
  152. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  153. package/dist/lib/sync-core/vault-settings.js +131 -0
  154. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  155. package/dist/lib/sync-core/vault-uid.js +4 -0
  156. package/dist/lib/windows/install-followup.d.ts +2 -0
  157. package/dist/lib/windows/install-followup.js +4 -1
  158. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  159. package/dist/utils/auth-session-check.d.ts +16 -0
  160. package/dist/utils/auth-session-check.js +16 -0
  161. package/dist/utils/client-health-contract.d.ts +6 -0
  162. package/dist/utils/client-health-contract.js +13 -0
  163. package/dist/utils/client-health.d.ts +7 -0
  164. package/dist/utils/client-health.js +22 -1
  165. package/dist/utils/command-usage.d.ts +40 -0
  166. package/dist/utils/command-usage.js +61 -0
  167. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  168. package/dist/utils/duplicate-command-usage.js +125 -0
  169. package/dist/utils/host-registration.js +5 -2
  170. package/dist/utils/pack-contributions.d.ts +3 -0
  171. package/dist/utils/pack-contributions.js +110 -23
  172. package/dist/utils/resident-package-preload.js +4 -0
  173. package/dist/utils/self-update.d.ts +3 -1
  174. package/dist/utils/self-update.js +56 -11
  175. package/dist/utils/sentry-fingerprint.js +9 -0
  176. package/dist/utils/update-lock.d.ts +151 -14
  177. package/dist/utils/update-lock.js +782 -46
  178. package/dist/utils/version-gate.js +12 -2
  179. package/dist/utils/windows-bash.d.ts +2 -0
  180. package/dist/utils/windows-bash.js +2 -1
  181. package/package.json +9 -8
  182. package/scripts/bench-core-compare.mjs +313 -0
  183. package/scripts/bench-core.mjs +399 -12
  184. package/scripts/check-function-manifest.mjs +116 -3
@@ -20,6 +20,14 @@
20
20
  * it gains no access it did not have; the check keeps a link, a hardlink, a
21
21
  * file of another user or a writable file from being run by mistake.
22
22
  *
23
+ * On Windows (only `hq doctor --only machine-checks` runs there; the daemon
24
+ * schedule skips Windows) each script is run with the trusted Git Bash that
25
+ * src/utils/windows-bash.ts resolves, never System32\bash.exe (WSL) or a
26
+ * WindowsApps alias. With no trusted Git Bash every check is `unknown` and
27
+ * nothing is run. The store read rules there are safe-store's Windows rules:
28
+ * a real folder (not a symlink or junction) and a regular single-link file
29
+ * that is not a symlink; Windows has no POSIX owner or mode bits to check.
30
+ *
23
31
  * Results can name local paths, so they are written only to the daemon's
24
32
  * private folder (machine-checks.json, mode 0600) and the state file, and are
25
33
  * never logged or sent.
@@ -58,7 +66,20 @@ export interface RunMachineChecksOptions {
58
66
  checks?: readonly MachineCheckSpec[];
59
67
  killGraceMs?: number;
60
68
  drainMs?: number;
69
+ /** Platform whose rules apply. Default process.platform. */
70
+ platform?: NodeJS.Platform;
71
+ /** Windows only: the trusted Git Bash, or undefined when none. Default resolveWindowsBash. */
72
+ resolveBash?: (env: NodeJS.ProcessEnv) => string | undefined;
61
73
  }
74
+ /** The summary of every check on Windows when no trusted Git Bash is found. */
75
+ export declare const MACHINE_CHECK_NO_GIT_BASH = "not run: Git Bash was not found (set CLAUDE_CODE_GIT_BASH_PATH or install Git for Windows)";
76
+ /**
77
+ * The shell that runs every script: /bin/bash off Windows; on Windows the
78
+ * trusted Git Bash, or undefined when none is found. A resolver answer that
79
+ * windows-bash.ts excludes (System32\bash.exe, a WindowsApps alias) or that
80
+ * is not an absolute path counts as none.
81
+ */
82
+ export declare function machineCheckShell(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, resolveBash?: (env: NodeJS.ProcessEnv) => string | undefined): string | undefined;
62
83
  /** The finding text a script's stdout carries: empty means nothing to report. */
63
84
  export declare function findingText(stdout: string): string;
64
85
  /** First non-empty line with `<tag>` and `</tag>` markers removed, at most 240 characters. */
@@ -75,7 +96,7 @@ type ScriptCheck = {
75
96
  summary: string;
76
97
  };
77
98
  /** The script's absolute path when it may be run; else why not. */
78
- export declare function checkMachineCheckScript(hqRoot: string, relative: string): ScriptCheck;
99
+ export declare function checkMachineCheckScript(hqRoot: string, relative: string, platform?: NodeJS.Platform): ScriptCheck;
79
100
  /**
80
101
  * Run every machine check once, one at a time. A call while a batch is
81
102
  * running returns that batch. Inside a machine check
@@ -126,6 +147,8 @@ export interface MachineCheckScheduleOptions {
126
147
  /** Test seam: the gate, read at each tick. Default machineChecksScheduleOn. */
127
148
  enabled?: (env: NodeJS.ProcessEnv, home: string) => boolean;
128
149
  registered?: (root: string, home: string, env: NodeJS.ProcessEnv) => boolean;
150
+ /** Test seam: whether the native notice can use its ledger. Default nativeNoticeLedgerUsable. */
151
+ ledgerUsable?: (env: NodeJS.ProcessEnv, home: string) => boolean;
129
152
  }
130
153
  export interface MachineCheckSchedule {
131
154
  /** One scheduled tick (tests). Resolves when the tick is done; never rejects. */
@@ -136,7 +159,11 @@ export interface MachineCheckSchedule {
136
159
  * The daemon's machine-check timer. Each tick runs a batch only when the new
137
160
  * hook core (`core.next`) is on for this machine and no kill switch is set;
138
161
  * 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
162
+ * without a daemon restart. It also runs none when the native notice cannot
163
+ * use its ledger (nativeNoticeLedgerUsable, the rule the machine-check owner
164
+ * applies): the owner then hands the checks to the legacy hooks, and a batch
165
+ * here would run them a second time and leave cooldown stamps that silence
166
+ * the legacy run, so neither path would show the finding. A batch already running finishes. A failed batch
140
167
  * logs one line with the error's name only.
141
168
  */
142
169
  export declare function startMachineCheckSchedule(options: MachineCheckScheduleOptions): MachineCheckSchedule;
@@ -20,6 +20,14 @@
20
20
  * it gains no access it did not have; the check keeps a link, a hardlink, a
21
21
  * file of another user or a writable file from being run by mistake.
22
22
  *
23
+ * On Windows (only `hq doctor --only machine-checks` runs there; the daemon
24
+ * schedule skips Windows) each script is run with the trusted Git Bash that
25
+ * src/utils/windows-bash.ts resolves, never System32\bash.exe (WSL) or a
26
+ * WindowsApps alias. With no trusted Git Bash every check is `unknown` and
27
+ * nothing is run. The store read rules there are safe-store's Windows rules:
28
+ * a real folder (not a symlink or junction) and a regular single-link file
29
+ * that is not a symlink; Windows has no POSIX owner or mode bits to check.
30
+ *
23
31
  * Results can name local paths, so they are written only to the daemon's
24
32
  * private folder (machine-checks.json, mode 0600) and the state file, and are
25
33
  * never logged or sent.
@@ -30,7 +38,9 @@ import * as fs from "node:fs";
30
38
  import * as path from "node:path";
31
39
  import { coreNextEnabled } from "../../utils/core-next-flag.js";
32
40
  import { coreNextKillReason } from "../../utils/core-next-kill.js";
41
+ import { isExcludedWindowsBash, resolveWindowsBash } from "../../utils/windows-bash.js";
33
42
  import { anyNativeSessionStartRegistered } from "./machine-check-registration.js";
43
+ import { nativeNoticeLedgerUsable } from "./native-notice-ledger.js";
34
44
  import { openStoreDir } from "../safe-store.js";
35
45
  import { readStoreFile, writeStoreFile } from "./paths.js";
36
46
  import { cutUtf8, MACHINE_CHECK_DETAIL_BYTES } from "./state-file.js";
@@ -61,6 +71,33 @@ export const MACHINE_CHECK_DRAIN_MS = 50;
61
71
  const SESSION_ID = "hq-machine-checks";
62
72
  const FINGERPRINT = /^[0-9a-f]{64}$/;
63
73
  const STATUSES = new Set(["ok", "warn", "fail", "unknown"]);
74
+ /** The summary of every check on Windows when no trusted Git Bash is found. */
75
+ export const MACHINE_CHECK_NO_GIT_BASH = "not run: Git Bash was not found (set CLAUDE_CODE_GIT_BASH_PATH or install Git for Windows)";
76
+ function defaultResolveBash(env) {
77
+ return resolveWindowsBash(env).executable;
78
+ }
79
+ /**
80
+ * The shell that runs every script: /bin/bash off Windows; on Windows the
81
+ * trusted Git Bash, or undefined when none is found. A resolver answer that
82
+ * windows-bash.ts excludes (System32\bash.exe, a WindowsApps alias) or that
83
+ * is not an absolute path counts as none.
84
+ */
85
+ export function machineCheckShell(platform, env, resolveBash = defaultResolveBash) {
86
+ if (platform !== "win32")
87
+ return "/bin/bash";
88
+ let bash;
89
+ try {
90
+ bash = resolveBash(env);
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ if (!bash || isExcludedWindowsBash(bash, env))
96
+ return undefined;
97
+ if (!path.win32.isAbsolute(bash) && !path.posix.isAbsolute(bash))
98
+ return undefined;
99
+ return bash;
100
+ }
64
101
  /** The finding text a script's stdout carries: empty means nothing to report. */
65
102
  export function findingText(stdout) {
66
103
  const trimmed = stdout.trim();
@@ -116,12 +153,12 @@ function disabledIds(env) {
116
153
  return new Set((env.HQ_DISABLED_HOOKS ?? "").split(",").map((id) => id.trim()).filter(Boolean));
117
154
  }
118
155
  /** The script's absolute path when it may be run; else why not. */
119
- export function checkMachineCheckScript(hqRoot, relative) {
156
+ export function checkMachineCheckScript(hqRoot, relative, platform = process.platform) {
120
157
  const root = path.resolve(hqRoot);
121
158
  const file = path.resolve(root, ...relative.split("/"));
122
159
  if (!file.startsWith(root + path.sep))
123
160
  return { ok: false, summary: "refused: outside-root" };
124
- const opened = openStoreDir(path.dirname(file));
161
+ const opened = openStoreDir(path.dirname(file), platform === process.platform ? {} : { platform });
125
162
  if (!opened.ok) {
126
163
  return { ok: false, summary: opened.code === "folder-missing" ? "not installed" : `refused: ${opened.code}` };
127
164
  }
@@ -154,18 +191,21 @@ function payload(event, hqRoot) {
154
191
  : JSON.stringify({ hook_event_name: "UserPromptSubmit", prompt: "", session_id: SESSION_ID, cwd: hqRoot });
155
192
  }
156
193
  /**
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.
194
+ * `<shell> <file>` with the payload on stdin (shell: /bin/bash, or Git Bash
195
+ * on Windows). Waits for the direct child's exit, not for stdout to close, so
196
+ * a detached grandchild holding stdout open does not delay the result. A
197
+ * timeout sends SIGTERM and then SIGKILL to the direct child only, never to
198
+ * its process group. On Windows Node ends the direct child with
199
+ * TerminateProcess for either signal (there are no POSIX process groups), so
200
+ * the first kill already ends it and the second is a no-op.
161
201
  */
162
- function runScript(file, spec, hqRoot, env, killGraceMs, drainMs) {
202
+ function runScript(shell, file, spec, hqRoot, env, killGraceMs, drainMs) {
163
203
  return new Promise((resolve) => {
164
204
  const chunks = [];
165
205
  let kept = 0;
166
206
  let child;
167
207
  try {
168
- child = spawn("/bin/bash", [file], {
208
+ child = spawn(shell, [file], {
169
209
  cwd: hqRoot,
170
210
  env: {
171
211
  ...env,
@@ -219,15 +259,17 @@ function runScript(file, spec, hqRoot, env, killGraceMs, drainMs) {
219
259
  child.stdin?.end(payload(spec.event, hqRoot));
220
260
  });
221
261
  }
222
- async function runOne(spec, options, env, disabled) {
262
+ async function runOne(spec, options, env, disabled, shell) {
223
263
  const now = options.now ?? (() => new Date());
224
264
  const at = () => now().toISOString();
225
265
  if (disabled.has(spec.id))
226
266
  return { id: spec.id, status: "ok", checked_at: at(), summary: "disabled by HQ_DISABLED_HOOKS" };
227
- const checked = checkMachineCheckScript(options.hqRoot, spec.path);
267
+ if (shell === undefined)
268
+ return { id: spec.id, status: "unknown", checked_at: at(), summary: MACHINE_CHECK_NO_GIT_BASH };
269
+ const checked = checkMachineCheckScript(options.hqRoot, spec.path, options.platform ?? process.platform);
228
270
  if (!checked.ok)
229
271
  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);
272
+ const run = await runScript(shell, checked.file, spec, path.resolve(options.hqRoot), env, options.killGraceMs ?? MACHINE_CHECK_KILL_GRACE_MS, options.drainMs ?? MACHINE_CHECK_DRAIN_MS);
231
273
  if (run.outcome === "timed-out") {
232
274
  return { id: spec.id, status: "unknown", checked_at: at(), summary: `timed out after ${Math.round(spec.timeoutMs / 1000)}s` };
233
275
  }
@@ -253,9 +295,10 @@ export function runMachineChecks(options) {
253
295
  return inFlight;
254
296
  const batch = (async () => {
255
297
  const disabled = disabledIds(env);
298
+ const shell = machineCheckShell(options.platform ?? process.platform, env, options.resolveBash);
256
299
  const results = [];
257
300
  for (const spec of options.checks ?? MACHINE_CHECKS) {
258
- results.push(await runOne(spec, options, env, disabled));
301
+ results.push(await runOne(spec, options, env, disabled, shell));
259
302
  }
260
303
  if (options.resultsFile)
261
304
  writeMachineCheckResults(options.resultsFile, results, options.resultsWrite);
@@ -360,7 +403,11 @@ export function machineChecksScheduleOn(env, home) {
360
403
  * The daemon's machine-check timer. Each tick runs a batch only when the new
361
404
  * hook core (`core.next`) is on for this machine and no kill switch is set;
362
405
  * 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
406
+ * without a daemon restart. It also runs none when the native notice cannot
407
+ * use its ledger (nativeNoticeLedgerUsable, the rule the machine-check owner
408
+ * applies): the owner then hands the checks to the legacy hooks, and a batch
409
+ * here would run them a second time and leave cooldown stamps that silence
410
+ * the legacy run, so neither path would show the finding. A batch already running finishes. A failed batch
364
411
  * logs one line with the error's name only.
365
412
  */
366
413
  export function startMachineCheckSchedule(options) {
@@ -385,6 +432,10 @@ export function startMachineCheckSchedule(options) {
385
432
  options.log("info", "machine checks skipped: no native SessionStart");
386
433
  return;
387
434
  }
435
+ if (!(options.ledgerUsable ?? nativeNoticeLedgerUsable)(options.env, options.home)) {
436
+ options.log("info", "machine checks skipped: the native notice cannot use its ledger");
437
+ return;
438
+ }
388
439
  lastStart = now();
389
440
  await run({ hqRoot, env: options.env, resultsFile: options.resultsFile });
390
441
  }
@@ -0,0 +1,45 @@
1
+ import * as fs from "node:fs";
2
+ import { daemonPaths } from "./paths.js";
3
+ import { type RunCommand, type SleepFn } from "../service-manager/launchd.js";
4
+ import { type MeshOwner } from "../mesh/live/daemon/install.js";
5
+ export interface MeshOwnerDeps {
6
+ run?: RunCommand;
7
+ uid?: number;
8
+ hosted?: (paths: ReturnType<typeof daemonPaths>) => boolean;
9
+ }
10
+ export declare function meshOwnerHere(home: string, env: NodeJS.ProcessEnv, deps?: MeshOwnerDeps): MeshOwner;
11
+ export interface HqDaemonUnitRepair {
12
+ repaired: boolean;
13
+ action?: "replaced" | "removed";
14
+ from?: string;
15
+ message?: string;
16
+ }
17
+ export declare function repairHqDaemonUnitFromOtherHome(opts: {
18
+ home: string;
19
+ loginHome?: string;
20
+ uid: number;
21
+ env?: NodeJS.ProcessEnv;
22
+ run?: RunCommand;
23
+ existsSync?: typeof fs.existsSync;
24
+ sleep?: SleepFn;
25
+ daemonRunsElsewhere?: () => boolean;
26
+ }): HqDaemonUnitRepair;
27
+ export interface ServiceUnitsRepair {
28
+ messages: string[];
29
+ meshReplaced: boolean;
30
+ failed: boolean;
31
+ }
32
+ export declare function repairServiceUnitsFromOtherHome(opts: {
33
+ home: string;
34
+ env: NodeJS.ProcessEnv;
35
+ hqRoot?: string;
36
+ loginHome?: string;
37
+ uid?: number;
38
+ platform?: NodeJS.Platform;
39
+ run?: RunCommand;
40
+ existsSync?: typeof fs.existsSync;
41
+ sleep?: SleepFn;
42
+ hosted?: MeshOwnerDeps["hosted"];
43
+ daemonRunsElsewhere?: () => boolean;
44
+ }): ServiceUnitsRepair;
45
+ //# sourceMappingURL=mesh-owner.d.ts.map
@@ -0,0 +1,166 @@
1
+ import * as fs from "node:fs";
2
+ import { enabledServices } from "./catalog.js";
3
+ import { readDaemonConfig } from "./config.js";
4
+ import { hostedDaemonRunning, recentlyHostedDaemon } from "./handoff.js";
5
+ import { clearHealPending, healPending, homeIsLoginSafe, isLoginHome, jobLoadedFromHome, meshUnitFromOtherHome, removeMeshUnitFromOtherHome } from "../mesh/live/daemon/unit-home.js";
6
+ import { DAEMON_LAUNCHD_LABEL } from "./install.js";
7
+ import { runningDaemonPid } from "./lock.js";
8
+ import { detectMachineType } from "./machine-type.js";
9
+ import { daemonPaths } from "./paths.js";
10
+ import { activateLaunchd, defaultRunCommand, launchdPlistPath } from "../service-manager/launchd.js";
11
+ import { repairMeshUnitFromOtherHome } from "../mesh/live/daemon/install.js";
12
+ export function meshOwnerHere(home, env, deps = {}) {
13
+ const paths = daemonPaths(home, env);
14
+ const run = deps.run ?? defaultRunCommand;
15
+ const uid = deps.uid ?? process.getuid?.() ?? 0;
16
+ const hosted = deps.hosted ?? ((p) => hostedDaemonRunning(p) || recentlyHostedDaemon(p));
17
+ const printed = run("launchctl", ["print", `gui/${uid}/${DAEMON_LAUNCHD_LABEL}`]);
18
+ const loadedHere = printed.status === 0 && jobLoadedFromHome(printed.stdout ?? "", home);
19
+ if (!loadedHere && !hosted(paths))
20
+ return null;
21
+ const config = readDaemonConfig(paths.configPath);
22
+ const machineType = detectMachineType(undefined, {
23
+ platform: process.platform,
24
+ env,
25
+ home,
26
+ savedType: config.machineType,
27
+ existsSync: fs.existsSync,
28
+ readFileSync: (p) => fs.readFileSync(p, "utf8"),
29
+ }).type;
30
+ return enabledServices(machineType, config).includes("mesh") ? "hq-daemon" : "hq-daemon-mesh-off";
31
+ }
32
+ function daemonRunsElsewhere(home, env) {
33
+ const paths = daemonPaths(home, env);
34
+ return hostedDaemonRunning(paths) || recentlyHostedDaemon(paths) || runningDaemonPid(paths.lockPath) !== null;
35
+ }
36
+ export function repairHqDaemonUnitFromOtherHome(opts) {
37
+ const run = opts.run ?? defaultRunCommand;
38
+ const existsSync = opts.existsSync ?? fs.existsSync;
39
+ if (!isLoginHome(opts.home, opts.loginHome))
40
+ return { repaired: false };
41
+ const plist = launchdPlistPath(opts.home, { label: DAEMON_LAUNCHD_LABEL });
42
+ const unit = { home: opts.home, loginHome: opts.loginHome, uid: opts.uid, run, label: DAEMON_LAUNCHD_LABEL, sleep: opts.sleep };
43
+ const runsElsewhereCheck = opts.daemonRunsElsewhere ?? (() => daemonRunsElsewhere(opts.home, opts.env ?? process.env));
44
+ const runsElsewhere = () => {
45
+ try {
46
+ return runsElsewhereCheck();
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ };
52
+ if (!meshUnitFromOtherHome(unit)) {
53
+ if (!healPending(opts.home, DAEMON_LAUNCHD_LABEL))
54
+ return { repaired: false };
55
+ if (run("launchctl", ["print", `gui/${opts.uid}/${DAEMON_LAUNCHD_LABEL}`]).status === 0 || !existsSync(plist)) {
56
+ clearHealPending(opts.home, DAEMON_LAUNCHD_LABEL);
57
+ return { repaired: false };
58
+ }
59
+ const elsewhere = runsElsewhere();
60
+ if (elsewhere === undefined)
61
+ return { repaired: false };
62
+ if (elsewhere) {
63
+ clearHealPending(opts.home, DAEMON_LAUNCHD_LABEL);
64
+ return { repaired: false };
65
+ }
66
+ try {
67
+ activateLaunchd(plist, run, opts.uid, { sleep: opts.sleep });
68
+ }
69
+ catch (error) {
70
+ return {
71
+ repaired: false,
72
+ message: `An earlier repair stopped an hq daemon service from another home folder, and loading ${plist} failed again: ${error instanceof Error ? error.message : String(error)}. Run: hq daemon start`,
73
+ };
74
+ }
75
+ clearHealPending(opts.home, DAEMON_LAUNCHD_LABEL);
76
+ return { repaired: true, action: "replaced", message: `Finished an earlier repair: loaded ${plist}.` };
77
+ }
78
+ const other = removeMeshUnitFromOtherHome({ ...unit, markPending: true });
79
+ if (!other.from)
80
+ return { repaired: false };
81
+ const found = `The hq daemon service was loaded from ${other.from}, which is not in this account's home folder.`;
82
+ if (!other.removed)
83
+ return { repaired: false, from: other.from, message: `${found} Stopping it failed: ${other.error}` };
84
+ if (!existsSync(plist)) {
85
+ clearHealPending(opts.home, DAEMON_LAUNCHD_LABEL);
86
+ return { repaired: true, action: "removed", from: other.from, message: `${found} Stopped it.` };
87
+ }
88
+ const elsewhere = runsElsewhere();
89
+ if (elsewhere) {
90
+ clearHealPending(opts.home, DAEMON_LAUNCHD_LABEL);
91
+ return { repaired: true, action: "removed", from: other.from, message: `${found} Stopped it; hq daemon already runs for this account.` };
92
+ }
93
+ if (elsewhere === undefined) {
94
+ return { repaired: false, action: "removed", from: other.from, message: `${found} Stopped it, but could not tell whether hq daemon already runs; will check again.` };
95
+ }
96
+ try {
97
+ activateLaunchd(plist, run, opts.uid, { sleep: opts.sleep });
98
+ clearHealPending(opts.home, DAEMON_LAUNCHD_LABEL);
99
+ return { repaired: true, action: "replaced", from: other.from, message: `${found} Loaded ${plist} in its place.` };
100
+ }
101
+ catch (error) {
102
+ return {
103
+ repaired: false,
104
+ action: "removed",
105
+ from: other.from,
106
+ message: `${found} Stopped it, but loading ${plist} failed: ${error instanceof Error ? error.message : String(error)}. Run: hq daemon start`,
107
+ };
108
+ }
109
+ }
110
+ export function repairServiceUnitsFromOtherHome(opts) {
111
+ const result = { messages: [], meshReplaced: false, failed: false };
112
+ if ((opts.platform ?? process.platform) !== "darwin")
113
+ return result;
114
+ if (!homeIsLoginSafe(opts.home, opts.loginHome))
115
+ return result;
116
+ const uid = opts.uid ?? process.getuid?.();
117
+ if (typeof uid !== "number")
118
+ return result;
119
+ const run = opts.run ?? defaultRunCommand;
120
+ try {
121
+ const daemon = repairHqDaemonUnitFromOtherHome({
122
+ home: opts.home,
123
+ loginHome: opts.loginHome,
124
+ uid,
125
+ env: opts.env,
126
+ run,
127
+ existsSync: opts.existsSync,
128
+ sleep: opts.sleep,
129
+ daemonRunsElsewhere: opts.daemonRunsElsewhere,
130
+ });
131
+ if (daemon.message)
132
+ result.messages.push(daemon.message);
133
+ if (daemon.message && !daemon.repaired)
134
+ result.failed = true;
135
+ }
136
+ catch (error) {
137
+ result.messages.push(`Could not check the hq daemon service: ${error instanceof Error ? error.message : String(error)}`);
138
+ result.failed = true;
139
+ }
140
+ try {
141
+ const mesh = repairMeshUnitFromOtherHome({
142
+ platform: "darwin",
143
+ home: opts.home,
144
+ loginHome: opts.loginHome,
145
+ uid,
146
+ env: opts.env,
147
+ hqRoot: opts.hqRoot,
148
+ run,
149
+ existsSync: opts.existsSync,
150
+ sleep: opts.sleep,
151
+ meshOwner: () => meshOwnerHere(opts.home, opts.env, { run, uid, hosted: opts.hosted }),
152
+ });
153
+ if (mesh.message)
154
+ result.messages.push(mesh.message);
155
+ if (mesh.message && !mesh.repaired)
156
+ result.failed = true;
157
+ if (mesh.repaired && mesh.action === "replaced")
158
+ result.meshReplaced = true;
159
+ }
160
+ catch (error) {
161
+ result.messages.push(`Could not check the Work Mesh service: ${error instanceof Error ? error.message : String(error)}`);
162
+ result.failed = true;
163
+ }
164
+ return result;
165
+ }
166
+ //# sourceMappingURL=mesh-owner.js.map
@@ -0,0 +1,27 @@
1
+ /** The native SessionStart notice's shown-once ledger (`FILE_NAME` in crates/hq-hook/src/session_start.rs). */
2
+ export declare const NATIVE_NOTICE_LEDGER_FILE = "machine-check-shown.v1";
3
+ /** The legacy reason when that ledger would be refused. The Rust port gives the same text. */
4
+ export declare const NATIVE_NOTICE_LEDGER_REFUSED = "the native notice cannot use its ledger: a link, a shared folder or another account's folder is on its path";
5
+ /**
6
+ * Whether the native SessionStart notice could open its ledger, without
7
+ * creating or changing anything. The notice shows nothing when it cannot
8
+ * (session_start.rs), so the daemon must not own the checks then, and its
9
+ * schedule runs no batch (the checks' cooldown stamps would silence the
10
+ * legacy hooks that own them instead).
11
+ *
12
+ * The ledger is `HQ_HOOK_STATE_DIR` (when non-empty) or
13
+ * `<home>/.hq/state/hq-hook`, plus `NATIVE_NOTICE_LEDGER_FILE`, and must be
14
+ * absolute (`ledger_path`). It is opened through the hq-hook store
15
+ * (`walk` and `file_refusal` in crates/hq-hook/src/host/store.rs), which is
16
+ * stricter than src/lib/safe-store.ts about parents: from `/` down, a link is
17
+ * followed only when root owns it and every folder before it is root's and
18
+ * writable by root alone (`/var`, `/tmp` on macOS); any other link, a `..`, or
19
+ * a name that is not a folder is refused. Folders above must belong to root
20
+ * or this account and not be writable by group or others (root's sticky
21
+ * folders aside); the ledger folder must be this account's and not shared.
22
+ * A missing folder or file is fine: the store creates it 0700 / 0600. An
23
+ * existing file must be a regular file with one link, this account's, not
24
+ * shared. Reading is by lstat, a handful of calls, no process.
25
+ */
26
+ export declare function nativeNoticeLedgerUsable(env: NodeJS.ProcessEnv, home: string): boolean;
27
+ //# sourceMappingURL=native-notice-ledger.d.ts.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The native SessionStart notice's ledger rule, shared by the machine-check
3
+ * owner (machine-check-owner.ts) and the daemon's schedule (machine-checks.ts)
4
+ * so both stand down under the same test. Kept apart from both so neither
5
+ * module imports the other for it.
6
+ */
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ /** The native SessionStart notice's shown-once ledger (`FILE_NAME` in crates/hq-hook/src/session_start.rs). */
10
+ export const NATIVE_NOTICE_LEDGER_FILE = "machine-check-shown.v1";
11
+ /** The legacy reason when that ledger would be refused. The Rust port gives the same text. */
12
+ export const NATIVE_NOTICE_LEDGER_REFUSED = "the native notice cannot use its ledger: a link, a shared folder or another account's folder is on its path";
13
+ /** How many root-owned links one walk follows (`SYSTEM_LINKS` in crates/hq-hook/src/host/store.rs). */
14
+ const SYSTEM_LINKS = 8;
15
+ /**
16
+ * Whether the native SessionStart notice could open its ledger, without
17
+ * creating or changing anything. The notice shows nothing when it cannot
18
+ * (session_start.rs), so the daemon must not own the checks then, and its
19
+ * schedule runs no batch (the checks' cooldown stamps would silence the
20
+ * legacy hooks that own them instead).
21
+ *
22
+ * The ledger is `HQ_HOOK_STATE_DIR` (when non-empty) or
23
+ * `<home>/.hq/state/hq-hook`, plus `NATIVE_NOTICE_LEDGER_FILE`, and must be
24
+ * absolute (`ledger_path`). It is opened through the hq-hook store
25
+ * (`walk` and `file_refusal` in crates/hq-hook/src/host/store.rs), which is
26
+ * stricter than src/lib/safe-store.ts about parents: from `/` down, a link is
27
+ * followed only when root owns it and every folder before it is root's and
28
+ * writable by root alone (`/var`, `/tmp` on macOS); any other link, a `..`, or
29
+ * a name that is not a folder is refused. Folders above must belong to root
30
+ * or this account and not be writable by group or others (root's sticky
31
+ * folders aside); the ledger folder must be this account's and not shared.
32
+ * A missing folder or file is fine: the store creates it 0700 / 0600. An
33
+ * existing file must be a regular file with one link, this account's, not
34
+ * shared. Reading is by lstat, a handful of calls, no process.
35
+ */
36
+ export function nativeNoticeLedgerUsable(env, home) {
37
+ const override = env.HQ_HOOK_STATE_DIR;
38
+ const folder = override ? override : home ? `${home}/.hq/state/hq-hook` : "";
39
+ if (!path.posix.isAbsolute(folder))
40
+ return false;
41
+ const segments = (text) => {
42
+ const out = text.split("/").filter((name) => name !== "" && name !== ".");
43
+ return out.includes("..") ? null : out;
44
+ };
45
+ let names = segments(folder);
46
+ if (!names)
47
+ return false;
48
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
49
+ const ownedOk = (stat) => uid === undefined || stat.uid === uid;
50
+ const looseBits = (stat) => uid !== undefined && (stat.mode & 0o022) !== 0;
51
+ const ancestorOk = (stat) => uid === undefined || ((stat.uid === 0 || stat.uid === uid) && (!looseBits(stat) || (stat.uid === 0 && (stat.mode & 0o1000) !== 0)));
52
+ const rootOnly = (stat) => stat.uid === 0 && (stat.mode & 0o022) === 0;
53
+ let followed = 0;
54
+ try {
55
+ walk: for (;;) {
56
+ const top = fs.statSync("/");
57
+ if (names.length === 0)
58
+ return top.isDirectory() && ownedOk(top) && !looseBits(top) && ledgerFileOk("/");
59
+ let system = rootOnly(top);
60
+ let prefix = "";
61
+ for (let index = 0; index < names.length; index += 1) {
62
+ prefix = `${prefix}/${names[index]}`;
63
+ let stat;
64
+ try {
65
+ stat = fs.lstatSync(prefix);
66
+ }
67
+ catch (error) {
68
+ // Missing from here down: the store creates it (mode 0700).
69
+ if (error.code === "ENOENT")
70
+ return true;
71
+ return false;
72
+ }
73
+ if (stat.isSymbolicLink()) {
74
+ if (stat.uid !== 0 || !system || followed >= SYSTEM_LINKS)
75
+ return false;
76
+ const resolved = segments(fs.realpathSync(prefix));
77
+ if (!resolved)
78
+ return false;
79
+ names = [...resolved, ...names.slice(index + 1)];
80
+ followed += 1;
81
+ continue walk;
82
+ }
83
+ if (!stat.isDirectory())
84
+ return false;
85
+ // The store opens every folder on the path for reading.
86
+ fs.accessSync(prefix, fs.constants.R_OK | fs.constants.X_OK);
87
+ if (index === names.length - 1) {
88
+ if (!ownedOk(stat) || looseBits(stat))
89
+ return false;
90
+ }
91
+ else if (!ancestorOk(stat)) {
92
+ return false;
93
+ }
94
+ system = system && rootOnly(stat);
95
+ }
96
+ return ledgerFileOk(prefix);
97
+ }
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ function ledgerFileOk(dir) {
103
+ let stat;
104
+ try {
105
+ stat = fs.lstatSync(path.posix.join(dir, NATIVE_NOTICE_LEDGER_FILE));
106
+ }
107
+ catch (error) {
108
+ return error.code === "ENOENT";
109
+ }
110
+ return stat.isFile() && stat.nlink === 1 && ownedOk(stat) && !looseBits(stat);
111
+ }
112
+ }
113
+ //# sourceMappingURL=native-notice-ledger.js.map
@@ -9,6 +9,8 @@ import { type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPla
9
9
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
10
10
  import { type LegacyUnit, type WindowsTaskOwner } from "./legacy.js";
11
11
  import { type DaemonLockResult } from "./lock.js";
12
+ import { removeMeshUnitFromOtherHome, type LaunchctlRunner } from "../mesh/live/daemon/unit-home.js";
13
+ import { type MeshUnitRepairResult } from "../mesh/live/daemon/install.js";
12
14
  import { type MachineType } from "./machine-type.js";
13
15
  import { type PickedHqCloud } from "./hq-cloud.js";
14
16
  import { type WatchRunnerOwnerStatus } from "./sync-runner.js";
@@ -46,6 +48,8 @@ export declare function refreshHqdRuntimeDecision(readDecision: () => Promise<bo
46
48
  /** Route an updater request through the daemon's existing graceful handoff. */
47
49
  export declare function handoffForPackageUpdateRequest(requested: boolean, restartDaemon: () => void): void;
48
50
  export interface RunDaemonOptions {
51
+ removeMeshUnitFromOtherHome?: typeof removeMeshUnitFromOtherHome;
52
+ isLoginHome?: (home: string) => boolean;
49
53
  foreground?: boolean;
50
54
  /** Started by the OS unit, which relaunches the daemon whenever it exits. */
51
55
  managed?: boolean;
@@ -172,6 +176,17 @@ export declare function withUserRuntimeDir(env: NodeJS.ProcessEnv, host: {
172
176
  uid: number;
173
177
  exists: (dir: string) => boolean;
174
178
  }): NodeJS.ProcessEnv;
179
+ export declare function checkMeshUnitHome(opts: {
180
+ platform: NodeJS.Platform;
181
+ home: string;
182
+ uid: number | undefined;
183
+ isLoginHome: (home: string) => boolean;
184
+ remove: typeof removeMeshUnitFromOtherHome;
185
+ run: LaunchctlRunner;
186
+ log: (level: "warn" | "error", message: string) => void;
187
+ takesOverMesh: boolean;
188
+ repair: () => MeshUnitRepairResult;
189
+ }): boolean;
175
190
  export declare function runDaemon(opts: RunDaemonOptions): Promise<number>;
176
191
  export {};
177
192
  //# sourceMappingURL=run.d.ts.map