@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
@@ -3,38 +3,85 @@ import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { RESOURCE_STOP_WAIT_MS, WorkerResourceSampler, resourceSampleIntervalMs, } from "./resource-usage.js";
6
7
  export const LANE_WORKER_EXIT_PATH_ENV = "HQ_LANE_WORKER_EXIT_PATH";
8
+ /**
9
+ * The longest the wrapper waits for resource figures after the worker exits.
10
+ * The sampler gives up on a running sample at RESOURCE_STOP_WAIT_MS; this is
11
+ * the backstop for a sampler that does not return at all.
12
+ */
13
+ export const WORKER_USAGE_WAIT_MS = RESOURCE_STOP_WAIT_MS + 250;
7
14
  function exitCodeFor(code, signal) {
8
15
  if (code !== null)
9
16
  return code;
10
17
  return signal ? 128 + (os.constants.signals[signal] ?? 0) : 1;
11
18
  }
12
- function recordExit(pathname, code, signal) {
19
+ function recordExit(pathname, code, signal, endedAt, usage) {
13
20
  const tempPath = `${pathname}.${process.pid}.tmp`;
14
21
  fs.writeFileSync(tempPath, `${JSON.stringify({
15
22
  exit_code: exitCodeFor(code, signal),
16
23
  ...(signal ? { signal } : {}),
17
- ended_at: new Date().toISOString(),
24
+ ended_at: endedAt.toISOString(),
25
+ // PS-011: what this run used. resource-usage.ts documents each field's accuracy.
26
+ ...(usage ? { resource_usage: usage } : {}),
18
27
  })}\n`, { mode: 0o600 });
19
28
  fs.renameSync(tempPath, pathname);
20
29
  }
21
- /** Runs one lane worker process and persists its terminal process status. */
22
- export function runLaneWorkerProcess(command, args, env = process.env, cwd = process.cwd()) {
30
+ /** The sampler's usage, or null when it fails or does not answer within waitMs. */
31
+ async function boundedUsage(sampler, endedAt, waitMs) {
32
+ let timer;
33
+ try {
34
+ return await Promise.race([
35
+ sampler.stop(endedAt),
36
+ new Promise((resolve) => {
37
+ timer = setTimeout(() => {
38
+ process.stderr.write("hq lanes: worker resource use was not ready in time; the exit record has none\n");
39
+ resolve(null);
40
+ }, waitMs);
41
+ // Not unref'd: this timer is what keeps the wrapper alive until the
42
+ // exit record is written when a sampler never answers.
43
+ }),
44
+ ]);
45
+ }
46
+ catch (error) {
47
+ process.stderr.write(`hq lanes: could not measure worker resource use: ${error instanceof Error ? error.message : String(error)}\n`);
48
+ return null;
49
+ }
50
+ finally {
51
+ if (timer)
52
+ clearTimeout(timer);
53
+ }
54
+ }
55
+ /** Runs one lane worker process and persists its terminal process status and resource use. */
56
+ export function runLaneWorkerProcess(command, args, env = process.env, cwd = process.cwd(), options = {}) {
57
+ const now = options.now ?? (() => new Date());
23
58
  const exitPath = env[LANE_WORKER_EXIT_PATH_ENV];
24
59
  const childEnv = { ...env };
25
60
  delete childEnv[LANE_WORKER_EXIT_PATH_ENV];
61
+ const intervalMs = options.sampleIntervalMs ?? resourceSampleIntervalMs(env);
62
+ const sampler = exitPath
63
+ ? (options.createSampler ?? ((pid, at, ms) => new WorkerResourceSampler(pid, at, ms, options.samplerDeps)))(process.pid, now(), intervalMs)
64
+ : null;
26
65
  const child = childProcess.spawn(command, args, { cwd, env: childEnv, stdio: "inherit" });
66
+ sampler?.setWorkerPid(child.pid);
67
+ sampler?.start();
27
68
  let settled = false;
28
- const finish = (code, signal) => {
29
- if (!settled && exitPath) {
69
+ // The worker's exit code is recorded before anything else can end the
70
+ // wrapper. The signal forwarders stay installed until the exit record is in
71
+ // place, so a SIGTERM that arrives after the worker exited (the reaper
72
+ // signals the wrapper pid) cannot kill the wrapper before it writes it.
73
+ const finish = async (code, signal) => {
74
+ settled = true;
75
+ const endedAt = now();
76
+ const usage = sampler ? await boundedUsage(sampler, endedAt, options.usageWaitMs ?? WORKER_USAGE_WAIT_MS) : null;
77
+ if (exitPath) {
30
78
  try {
31
- recordExit(exitPath, code, signal);
79
+ recordExit(exitPath, code, signal, endedAt, usage);
32
80
  }
33
81
  catch (error) {
34
82
  process.stderr.write(`hq lanes: could not persist worker exit status: ${error instanceof Error ? error.message : String(error)}\n`);
35
83
  }
36
84
  }
37
- settled = true;
38
85
  return exitCodeFor(code, signal);
39
86
  };
40
87
  return new Promise((resolve) => {
@@ -45,23 +92,28 @@ export function runLaneWorkerProcess(command, args, env = process.env, cwd = pro
45
92
  process.removeListener(signal, handler);
46
93
  };
47
94
  for (const signal of signals) {
48
- const handler = () => child.kill(signal);
95
+ // Once the worker has exited there is nothing to forward to; the
96
+ // handler then only keeps the wrapper alive until the record is written.
97
+ const handler = () => {
98
+ if (!settled)
99
+ child.kill(signal);
100
+ };
49
101
  handlers.set(signal, handler);
50
102
  process.on(signal, handler);
51
103
  }
104
+ const end = (code, signal) => {
105
+ if (settled)
106
+ return;
107
+ void finish(code, signal).then((exitCode) => {
108
+ cleanup();
109
+ resolve(exitCode);
110
+ });
111
+ };
52
112
  child.once("error", (error) => {
53
113
  process.stderr.write(`hq lanes: worker process could not start: ${error.message}\n`);
54
- if (!settled) {
55
- cleanup();
56
- resolve(finish(127, null));
57
- }
58
- });
59
- child.once("exit", (code, signal) => {
60
- if (!settled) {
61
- cleanup();
62
- resolve(finish(code, signal));
63
- }
114
+ end(127, null);
64
115
  });
116
+ child.once("exit", (code, signal) => end(code, signal));
65
117
  });
66
118
  }
67
119
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
@@ -15,7 +15,7 @@ export declare function isInstallableHqRoot(dir: string): boolean;
15
15
  export declare function findAncestorHqRoot(startDir: string): string | null;
16
16
  export interface InstallHqRootResolution {
17
17
  root: string;
18
- source: "flag" | "env" | "ancestor";
18
+ source: "flag" | "env" | "ancestor" | "trusted";
19
19
  }
20
20
  /**
21
21
  * Resolve the HQ root `hq mesh daemon install` records and passes to the
@@ -33,4 +33,11 @@ export declare function resolveInstallHqRoot(opts?: {
33
33
  export declare function readDaemonConfig(daemonDirectory: string): DaemonConfig;
34
34
  /** Record a verified local HQ checkout without trusting a caller-supplied path at runtime. */
35
35
  export declare function registerTrustedHqRoot(daemonDirectory: string, candidate: string | undefined): DaemonConfig;
36
+ export declare function resolveIfStaleHqRoot(opts: {
37
+ explicit?: string;
38
+ env?: NodeJS.ProcessEnv;
39
+ cwd?: string;
40
+ daemonDirectory: string;
41
+ installedUnitRoot?: string | null;
42
+ }): InstallHqRootResolution;
36
43
  //# sourceMappingURL=config.d.ts.map
@@ -117,4 +117,20 @@ export function registerTrustedHqRoot(daemonDirectory, candidate) {
117
117
  fs.writeFileSync(daemonConfigPath(daemonDirectory), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
118
118
  return next;
119
119
  }
120
+ export function resolveIfStaleHqRoot(opts) {
121
+ try {
122
+ return resolveInstallHqRoot(opts);
123
+ }
124
+ catch (error) {
125
+ if (opts.explicit?.trim() || (opts.env ?? process.env).HQ_ROOT?.trim())
126
+ throw error;
127
+ const fromUnit = verifyHqRoot(opts.installedUnitRoot ?? undefined);
128
+ if (fromUnit)
129
+ return { root: fromUnit, source: "trusted" };
130
+ const trusted = readDaemonConfig(opts.daemonDirectory).trustedHqRoots.at(-1);
131
+ if (!trusted)
132
+ throw error;
133
+ return { root: trusted, source: "trusted" };
134
+ }
135
+ }
120
136
  //# sourceMappingURL=config.js.map
@@ -67,7 +67,7 @@ export interface InstallPaths {
67
67
  /** Verified HQ root to persist and pass to the installed service. */
68
68
  hqRoot?: string;
69
69
  /** How hqRoot was chosen (shown in the Windows install confirmation). */
70
- hqRootSource?: "flag" | "env" | "ancestor";
70
+ hqRootSource?: "flag" | "env" | "ancestor" | "trusted";
71
71
  }
72
72
  export interface InstallResult {
73
73
  platform: DaemonInstallPlatform;
@@ -94,6 +94,7 @@ export interface InstallResult {
94
94
  /** Windows status: whether recordedHqRoot still passes isInstallableHqRoot. */
95
95
  rootValid?: boolean;
96
96
  }
97
+ export declare function installedUnitHqRoot(home: string, platform?: DaemonInstallPlatform, env?: NodeJS.ProcessEnv): string | null;
97
98
  /** Best-effort restart result used after an in-place CLI upgrade. */
98
99
  export interface RestartDaemonResult {
99
100
  attempted: boolean;
@@ -117,7 +118,32 @@ export declare function restartDaemonServiceIfInstalled(opts?: {
117
118
  sleep?: SleepFn;
118
119
  /** Windows: terminate the recorded daemon pid after `schtasks /End` (tests inject). */
119
120
  kill?: (pid: number) => void;
121
+ loginHome?: string;
122
+ meshOwner?: () => MeshOwner;
120
123
  }): RestartDaemonResult;
124
+ export type MeshOwner = "hq-daemon" | "hq-daemon-mesh-off" | null;
125
+ export interface MeshUnitRepairResult {
126
+ repaired: boolean;
127
+ action?: "replaced" | "removed";
128
+ from?: string;
129
+ message?: string;
130
+ }
131
+ export declare function repairMeshUnitFromOtherHome(opts?: {
132
+ platform?: DaemonInstallPlatform;
133
+ home?: string;
134
+ loginHome?: string;
135
+ uid?: number;
136
+ hqRoot?: string;
137
+ env?: NodeJS.ProcessEnv;
138
+ existsSync?: typeof fs.existsSync;
139
+ run?: (command: string, args: string[]) => {
140
+ status: number | null;
141
+ stdout?: string;
142
+ stderr?: string;
143
+ };
144
+ sleep?: SleepFn;
145
+ meshOwner?: () => MeshOwner;
146
+ }): MeshUnitRepairResult;
121
147
  export declare function detectPlatform(platform?: NodeJS.Platform): DaemonInstallPlatform;
122
148
  /**
123
149
  * HQ updates moved the CLI from toolchain/node/bin/hq to
@@ -187,6 +213,7 @@ export declare function installDaemonIfStale(opts: {
187
213
  readUnit?: (file: string) => string | null;
188
214
  /** Checks the installed unit's node path (tests); defaults to the real filesystem. */
189
215
  nodeProblem?: (nodePath: string) => "missing" | "versioned" | null;
216
+ loginHome?: string;
190
217
  }): InstallIfStaleResult;
191
218
  /**
192
219
  * The node binary baked into the installed daemon unit (darwin plist or linux
@@ -205,7 +232,7 @@ export declare function buildInstallPaths(opts: {
205
232
  argv?: string[];
206
233
  execPath?: string;
207
234
  hqRoot?: string;
208
- hqRootSource?: "flag" | "env" | "ancestor";
235
+ hqRootSource?: "flag" | "env" | "ancestor" | "trusted";
209
236
  /** Windows account (`DOMAIN\user`) the task runs as; defaults to the current user. */
210
237
  windowsUser?: string;
211
238
  /** Windows headless launcher override (tests); defaults to %SystemRoot%\System32\conhost.exe when present. */
@@ -337,6 +364,7 @@ export declare function installDaemonService(opts: {
337
364
  run?: RunCommand;
338
365
  uid?: number;
339
366
  sleep?: SleepFn;
367
+ loginHome?: string;
340
368
  }): InstallResult;
341
369
  export declare function uninstallDaemonService(opts: {
342
370
  platform?: DaemonInstallPlatform;
@@ -351,6 +379,7 @@ export declare function uninstallDaemonService(opts: {
351
379
  schtasks?: SchtasksRunner;
352
380
  /** Windows: terminate the recorded daemon pid after `schtasks /End` (tests inject). */
353
381
  kill?: (pid: number) => void;
382
+ loginHome?: string;
354
383
  }): InstallResult;
355
384
  /**
356
385
  * Live service-manager probe for `daemonServiceStatus`: `launchctl print
@@ -23,6 +23,7 @@ import { isInstallableHqRoot, readDaemonConfig, registerTrustedHqRoot, verifyHqR
23
23
  import { defaultPidLockDeps, pidLockStatus, readPidLock } from "./pid-lock.js";
24
24
  import { retireLegacyListen } from "./legacy-listen.js";
25
25
  import { readDaemonState } from "./state.js";
26
+ import { HQ_DAEMON_LAUNCHD_LABEL, assertLoginHome, isLoginHome, meshPlistPath, meshUnitFromOtherHome, removeMeshUnitFromOtherHome, } from "./unit-home.js";
26
27
  import { activateLaunchd, defaultRunCommand, discoverLaunchdIdentity, installLaunchdPlist, launchdProgramArguments, launchdIsLoaded, launchdServiceTarget, launchdPlistProgramArguments, parseLaunchdCommand, launchdProgramArgumentsDiffer, parseLaunchctlPrintArguments, } from "../../../service-manager/launchd.js";
27
28
  import { activateSystemd, systemdIsActive } from "../../../service-manager/systemd.js";
28
29
  import { nodeBinaryProblem, preferStableNodeBinary } from "../../../node-binary.js";
@@ -66,6 +67,23 @@ function readServiceText(file, existsSync, readFileSync) {
66
67
  }
67
68
  return buf.toString("utf8");
68
69
  }
70
+ export function installedUnitHqRoot(home, platform = detectPlatform(), env) {
71
+ if (platform !== "darwin" && platform !== "linux" && platform !== "win32")
72
+ return null;
73
+ const unitPath = platform === "darwin"
74
+ ? path.join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`)
75
+ : platform === "linux"
76
+ ? path.join(home, ".config", "systemd", "user", SYSTEMD_UNIT_NAME)
77
+ : path.join(daemonDir(undefined, home, env), `${WINDOWS_TASK_NAME}.xml`);
78
+ try {
79
+ if (!fs.existsSync(unitPath))
80
+ return null;
81
+ return hqRootFromUnitText(platform, readServiceText(unitPath, fs.existsSync, fs.readFileSync));
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
69
87
  function hqRootFromUnitText(platform, text) {
70
88
  if (platform === "win32")
71
89
  return parseWindowsTaskHqRoot(text);
@@ -178,6 +196,23 @@ export function restartDaemonServiceIfInstalled(opts = {}) {
178
196
  };
179
197
  });
180
198
  try {
199
+ if (platform === "darwin" && !isLoginHome(home, opts.loginHome))
200
+ return { attempted: false, restarted: false };
201
+ const repair = repairMeshUnitFromOtherHome({
202
+ platform,
203
+ home,
204
+ loginHome: opts.loginHome,
205
+ uid: opts.uid,
206
+ hqRoot: opts.hqRoot,
207
+ env: opts.env,
208
+ existsSync,
209
+ run,
210
+ sleep: opts.sleep,
211
+ meshOwner: opts.meshOwner,
212
+ });
213
+ if (repair.from) {
214
+ return { attempted: true, restarted: repair.action === "replaced", message: repair.message };
215
+ }
181
216
  migrateLegacyDaemonUnit({
182
217
  platform,
183
218
  home,
@@ -248,6 +283,101 @@ export function restartDaemonServiceIfInstalled(opts = {}) {
248
283
  }
249
284
  return { attempted: false, restarted: false };
250
285
  }
286
+ function defaultMeshOwner(home) {
287
+ return fs.existsSync(path.join(home, "Library", "LaunchAgents", `${HQ_DAEMON_LAUNCHD_LABEL}.plist`)) ? "hq-daemon" : null;
288
+ }
289
+ export function repairMeshUnitFromOtherHome(opts = {}) {
290
+ const platform = opts.platform ?? detectPlatform();
291
+ if (platform !== "darwin")
292
+ return { repaired: false };
293
+ const home = opts.home ?? os.homedir();
294
+ const uid = opts.uid ?? process.getuid?.();
295
+ if (typeof uid !== "number")
296
+ return { repaired: false };
297
+ const run = asRunCommand(opts.run ?? defaultRunCommand);
298
+ const existsSync = opts.existsSync ?? fs.existsSync;
299
+ const foreign = meshUnitFromOtherHome({ home, loginHome: opts.loginHome, uid, run });
300
+ if (!foreign)
301
+ return { repaired: false };
302
+ const foundAt = (from) => `The Work Mesh service was loaded from ${from}, which is not in this account's home folder.`;
303
+ const ownerOf = opts.meshOwner ?? (() => defaultMeshOwner(home));
304
+ let owner;
305
+ try {
306
+ owner = ownerOf();
307
+ }
308
+ catch (error) {
309
+ return {
310
+ repaired: false,
311
+ from: foreign,
312
+ message: `${foundAt(foreign)} Left it running: could not tell whether hq daemon runs Work Mesh (${error instanceof Error ? error.message : String(error)}). Run: hq daemon status`,
313
+ };
314
+ }
315
+ const other = removeMeshUnitFromOtherHome({ home, loginHome: opts.loginHome, uid, run, sleep: opts.sleep });
316
+ if (!other.from)
317
+ return { repaired: false };
318
+ const found = foundAt(other.from);
319
+ if (!other.removed) {
320
+ return { repaired: false, from: other.from, message: `${found} Stopping it failed: ${other.error}` };
321
+ }
322
+ try {
323
+ owner = ownerOf();
324
+ }
325
+ catch {
326
+ // keep the owner read before the bootout
327
+ }
328
+ const plist = meshPlistPath(home);
329
+ try {
330
+ if (owner === "hq-daemon") {
331
+ return { repaired: true, action: "removed", from: other.from, message: `${found} Stopped it; hq daemon runs Work Mesh for this account.` };
332
+ }
333
+ if (existsSync(plist)) {
334
+ activateLaunchd(plist, run, uid, { sleep: opts.sleep });
335
+ return { repaired: true, action: "replaced", from: other.from, message: `${found} Loaded ${plist} in its place.` };
336
+ }
337
+ if (owner === "hq-daemon-mesh-off") {
338
+ return {
339
+ repaired: true,
340
+ action: "removed",
341
+ from: other.from,
342
+ message: `${found} Stopped it. Work Mesh is turned off in hq daemon; turn it on with: hq daemon enable mesh`,
343
+ };
344
+ }
345
+ const root = verifyHqRoot(opts.hqRoot) ??
346
+ verifyHqRoot(opts.env?.HQ_ROOT) ??
347
+ readDaemonConfig(daemonDir(undefined, home, opts.env)).trustedHqRoots.at(-1);
348
+ if (!root) {
349
+ return {
350
+ repaired: true,
351
+ action: "removed",
352
+ from: other.from,
353
+ message: `${found} Stopped it. Start the real one with: hq mesh daemon install`,
354
+ };
355
+ }
356
+ const env = opts.env ?? process.env;
357
+ const paths = buildInstallPaths({
358
+ home,
359
+ env: opts.env,
360
+ hqRoot: root,
361
+ hqBinary: resolveHqBinary(process.argv, env),
362
+ nodeBinary: resolveNodeBinary(process.execPath, env),
363
+ });
364
+ installDaemonService({ platform, paths, run, uid, sleep: opts.sleep, loginHome: opts.loginHome });
365
+ return {
366
+ repaired: true,
367
+ action: "replaced",
368
+ from: other.from,
369
+ message: `${found} Installed ${paths.plistPath} in its place.`,
370
+ };
371
+ }
372
+ catch (error) {
373
+ return {
374
+ repaired: false,
375
+ action: "removed",
376
+ from: other.from,
377
+ message: `${found} Stopped it, but starting the real one failed: ${error instanceof Error ? error.message : String(error)}. Run: hq mesh daemon install`,
378
+ };
379
+ }
380
+ }
251
381
  export function detectPlatform(platform = process.platform) {
252
382
  if (platform === "darwin")
253
383
  return "darwin";
@@ -397,8 +527,14 @@ export function isNewerCliVersion(current, recorded) {
397
527
  * `run` is the launchctl/systemctl seam — tests pass a stub.
398
528
  */
399
529
  export function installDaemonIfStale(opts) {
400
- const recorded = readDaemonState(opts.paths.daemonDir)?.cliVersion;
401
530
  const platformForUnit = opts.platform ?? detectPlatform();
531
+ if (platformForUnit === "darwin" && !isLoginHome(opts.paths.home, opts.loginHome)) {
532
+ return {
533
+ reinstalled: false,
534
+ message: `HOME is ${opts.paths.home}, not this account's home folder; leaving the Work Mesh service alone`,
535
+ };
536
+ }
537
+ const recorded = readDaemonState(opts.paths.daemonDir)?.cliVersion;
402
538
  const installedNode = installedDaemonNodeBinary(opts.paths, platformForUnit, opts.readUnit);
403
539
  // Only a rewrite that changes the node path helps: a unit whose node is gone
404
540
  // or versioned, while this install resolves a different (stable) one.
@@ -433,6 +569,7 @@ export function installDaemonIfStale(opts) {
433
569
  run,
434
570
  uid: opts.uid,
435
571
  sleep: opts.sleep,
572
+ loginHome: opts.loginHome,
436
573
  });
437
574
  return {
438
575
  reinstalled: true,
@@ -977,6 +1114,8 @@ export function installDaemonService(opts) {
977
1114
  const platform = opts.platform ?? detectPlatform();
978
1115
  const paths = opts.paths ??
979
1116
  buildInstallPaths({ systemUser: opts.systemUser });
1117
+ if (platform === "darwin")
1118
+ assertLoginHome("install", paths.home, opts.loginHome);
980
1119
  const mkdirSync = opts.mkdirSync ?? fs.mkdirSync;
981
1120
  mkdirSync(paths.daemonDir, { recursive: true, mode: 0o700 });
982
1121
  registerTrustedHqRoot(paths.daemonDir, paths.hqRoot);
@@ -1140,6 +1279,8 @@ export function installDaemonService(opts) {
1140
1279
  export function uninstallDaemonService(opts) {
1141
1280
  const platform = opts.platform ?? detectPlatform();
1142
1281
  const paths = opts.paths ?? buildInstallPaths({});
1282
+ if (platform === "darwin")
1283
+ assertLoginHome("remove", paths.home, opts.loginHome);
1143
1284
  const unlinkSync = opts.unlinkSync ?? fs.unlinkSync;
1144
1285
  const existsSync = opts.existsSync ?? fs.existsSync;
1145
1286
  if (platform === "win32") {
@@ -0,0 +1,5 @@
1
+ export declare function canonicalDir(dir: string): string;
2
+ export declare function loginUserHome(): string;
3
+ export declare function isLoginHome(home: string, loginHome?: string): boolean;
4
+ export declare function homeIsLoginSafe(home: string, loginHome?: string): boolean;
5
+ //# sourceMappingURL=login-home.d.ts.map
@@ -0,0 +1,27 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ export function canonicalDir(dir) {
5
+ const resolved = path.resolve(dir);
6
+ try {
7
+ return fs.realpathSync.native(resolved);
8
+ }
9
+ catch {
10
+ return resolved;
11
+ }
12
+ }
13
+ export function loginUserHome() {
14
+ return os.userInfo().homedir;
15
+ }
16
+ export function isLoginHome(home, loginHome = loginUserHome()) {
17
+ return canonicalDir(home) === canonicalDir(loginHome);
18
+ }
19
+ export function homeIsLoginSafe(home, loginHome) {
20
+ try {
21
+ return isLoginHome(home, loginHome);
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ //# sourceMappingURL=login-home.js.map
@@ -0,0 +1,49 @@
1
+ import { homeIsLoginSafe, isLoginHome, loginUserHome } from "./login-home.js";
2
+ import { type SleepFn } from "../../../service-manager/launchd.js";
3
+ export { homeIsLoginSafe, isLoginHome, loginUserHome };
4
+ export declare class MeshUnitHomeError extends Error {
5
+ readonly home: string;
6
+ readonly loginHome: string;
7
+ constructor(action: "install" | "remove" | "start", home: string, loginHome: string, label?: string);
8
+ }
9
+ export declare function assertLoginHome(action: "install" | "remove" | "start", home: string, loginHome?: string, label?: string): void;
10
+ export declare function loadedLaunchdPlistPath(printed: string): string | null;
11
+ export declare function meshPlistPath(home: string): string;
12
+ export declare function jobLoadedFromHome(printed: string, home: string): boolean;
13
+ export declare function meshUnitLoadedFromElsewhere(printed: string, home: string): string | null;
14
+ export declare function meshJobLoadedForHome(printed: {
15
+ status: number | null;
16
+ stdout?: string;
17
+ }, home: string): boolean;
18
+ export declare const HQ_DAEMON_LAUNCHD_LABEL = "ai.getindigo.hq-daemon";
19
+ export type LaunchctlRunner = (command: string, args: string[]) => {
20
+ status: number | null;
21
+ stdout?: string;
22
+ stderr?: string;
23
+ };
24
+ export interface OtherHomeMeshUnit {
25
+ removed: boolean;
26
+ from?: string;
27
+ error?: string;
28
+ }
29
+ export declare function meshUnitFromOtherHome(opts: {
30
+ home: string;
31
+ loginHome?: string;
32
+ uid: number;
33
+ run: LaunchctlRunner;
34
+ label?: string;
35
+ }): string | null;
36
+ export declare function removeMeshUnitFromOtherHome(opts: {
37
+ home: string;
38
+ loginHome?: string;
39
+ uid: number;
40
+ run: LaunchctlRunner;
41
+ label?: string;
42
+ sleep?: SleepFn;
43
+ markPending?: boolean;
44
+ }): OtherHomeMeshUnit;
45
+ export declare const FOREIGN_UNLOAD_DEADLINE_MS = 30000;
46
+ export declare function markHealPending(home: string, label: string): void;
47
+ export declare function clearHealPending(home: string, label: string): void;
48
+ export declare function healPending(home: string, label: string): boolean;
49
+ //# sourceMappingURL=unit-home.d.ts.map
@@ -0,0 +1,134 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { LAUNCHD_LABEL } from "./paths.js";
4
+ import { canonicalDir, homeIsLoginSafe, isLoginHome, loginUserHome } from "./login-home.js";
5
+ import { waitForLaunchdUnload } from "../../../service-manager/launchd.js";
6
+ export { homeIsLoginSafe, isLoginHome, loginUserHome };
7
+ export class MeshUnitHomeError extends Error {
8
+ home;
9
+ loginHome;
10
+ constructor(action, home, loginHome, label = LAUNCHD_LABEL) {
11
+ const service = label === LAUNCHD_LABEL ? "the Work Mesh service" : "hq daemon";
12
+ const verb = action === "install" ? "installing" : action === "remove" ? "removing" : "starting";
13
+ super(`Not ${verb} ${service}: HOME is ${home}, ` +
14
+ `but this account's home folder is ${loginHome}. macOS keeps one ${label} service per login, ` +
15
+ `so doing this from another HOME would ${action === "remove" ? "stop" : "replace"} the real one. ` +
16
+ "Run the command again without overriding HOME.");
17
+ this.name = "MeshUnitHomeError";
18
+ this.home = home;
19
+ this.loginHome = loginHome;
20
+ }
21
+ }
22
+ export function assertLoginHome(action, home, loginHome = loginUserHome(), label = LAUNCHD_LABEL) {
23
+ if (!isLoginHome(home, loginHome))
24
+ throw new MeshUnitHomeError(action, home, loginHome, label);
25
+ }
26
+ export function loadedLaunchdPlistPath(printed) {
27
+ const value = /^\s*path\s*=\s*(.+?)\s*$/m.exec(printed)?.[1];
28
+ return value && path.isAbsolute(value) ? value : null;
29
+ }
30
+ export function meshPlistPath(home) {
31
+ return path.join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
32
+ }
33
+ const MACHINE_AGENT_DIRS = ["/Library/LaunchAgents/", "/System/Library/LaunchAgents/"];
34
+ export function jobLoadedFromHome(printed, home) {
35
+ const loaded = loadedLaunchdPlistPath(printed);
36
+ if (!loaded)
37
+ return false;
38
+ return canonicalDir(path.dirname(loaded)) === canonicalDir(path.join(home, "Library", "LaunchAgents"));
39
+ }
40
+ export function meshUnitLoadedFromElsewhere(printed, home) {
41
+ const loaded = loadedLaunchdPlistPath(printed);
42
+ if (!loaded)
43
+ return null;
44
+ if (MACHINE_AGENT_DIRS.some((dir) => loaded.startsWith(dir)))
45
+ return null;
46
+ const expected = meshPlistPath(home);
47
+ return canonicalDir(path.dirname(loaded)) === canonicalDir(path.dirname(expected)) ? null : loaded;
48
+ }
49
+ export function meshJobLoadedForHome(printed, home) {
50
+ if (printed.status !== 0)
51
+ return false;
52
+ return meshUnitLoadedFromElsewhere(printed.stdout ?? "", home) === null;
53
+ }
54
+ export const HQ_DAEMON_LAUNCHD_LABEL = "ai.getindigo.hq-daemon";
55
+ export function meshUnitFromOtherHome(opts) {
56
+ if (!isLoginHome(opts.home, opts.loginHome))
57
+ return null;
58
+ const printed = opts.run("launchctl", ["print", `gui/${opts.uid}/${opts.label ?? LAUNCHD_LABEL}`]);
59
+ if (printed.status !== 0)
60
+ return null;
61
+ return meshUnitLoadedFromElsewhere(printed.stdout ?? "", opts.home);
62
+ }
63
+ export function removeMeshUnitFromOtherHome(opts) {
64
+ if (!isLoginHome(opts.home, opts.loginHome))
65
+ return { removed: false };
66
+ const target = `gui/${opts.uid}/${opts.label ?? LAUNCHD_LABEL}`;
67
+ const printed = opts.run("launchctl", ["print", target]);
68
+ if (printed.status !== 0)
69
+ return { removed: false };
70
+ const from = meshUnitLoadedFromElsewhere(printed.stdout ?? "", opts.home);
71
+ if (!from)
72
+ return { removed: false };
73
+ if (opts.markPending)
74
+ markHealPending(opts.home, opts.label ?? LAUNCHD_LABEL);
75
+ const bootout = opts.run("launchctl", ["bootout", target]);
76
+ const unloaded = waitForLaunchdUnload(target, (command, args) => {
77
+ const r = opts.run(command, args);
78
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
79
+ }, { sleep: opts.sleep, deadlineMs: FOREIGN_UNLOAD_DEADLINE_MS });
80
+ if (!unloaded) {
81
+ const detail = bootout.status !== 0 ? (bootout.stderr || bootout.stdout || "").trim() || `launchctl bootout exited ${bootout.status}` : "";
82
+ return { removed: false, from, error: detail || `${target} was still loaded ${FOREIGN_UNLOAD_DEADLINE_MS / 1000} s after launchctl bootout` };
83
+ }
84
+ return { removed: true, from };
85
+ }
86
+ export const FOREIGN_UNLOAD_DEADLINE_MS = 30_000;
87
+ function healPendingPath(home) {
88
+ return path.join(home, ".hq", "launchd-heal-pending.json");
89
+ }
90
+ function readHealPending(home) {
91
+ try {
92
+ const raw = JSON.parse(fs.readFileSync(healPendingPath(home), "utf8"));
93
+ const labels = raw && typeof raw === "object" ? raw.labels : undefined;
94
+ return Array.isArray(labels) ? labels.filter((label) => typeof label === "string") : [];
95
+ }
96
+ catch {
97
+ return [];
98
+ }
99
+ }
100
+ function writeHealPending(home, labels) {
101
+ const file = healPendingPath(home);
102
+ if (labels.length === 0) {
103
+ fs.rmSync(file, { force: true });
104
+ return;
105
+ }
106
+ fs.mkdirSync(path.dirname(file), { recursive: true });
107
+ const tmp = `${file}.${process.pid}.tmp`;
108
+ fs.writeFileSync(tmp, `${JSON.stringify({ labels })}\n`);
109
+ fs.renameSync(tmp, file);
110
+ }
111
+ export function markHealPending(home, label) {
112
+ try {
113
+ const labels = readHealPending(home);
114
+ if (!labels.includes(label))
115
+ writeHealPending(home, [...labels, label]);
116
+ }
117
+ catch {
118
+ // best effort: a missing marker only loses the resume of an interrupted heal
119
+ }
120
+ }
121
+ export function clearHealPending(home, label) {
122
+ try {
123
+ const labels = readHealPending(home);
124
+ if (labels.includes(label))
125
+ writeHealPending(home, labels.filter((item) => item !== label));
126
+ }
127
+ catch {
128
+ // best effort
129
+ }
130
+ }
131
+ export function healPending(home, label) {
132
+ return readHealPending(home).includes(label);
133
+ }
134
+ //# sourceMappingURL=unit-home.js.map