@indigoai-us/hq-cli 5.345.221 → 5.345.223

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 (87) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/dist/command-catalog.generated.d.ts +31 -0
  3. package/dist/command-catalog.generated.js +38 -0
  4. package/dist/commands/auth.js +2 -1
  5. package/dist/commands/bot.d.ts +1 -1
  6. package/dist/commands/bot.js +34 -33
  7. package/dist/commands/core-delegate-w1b.js +216 -190
  8. package/dist/commands/daemon.d.ts +1 -0
  9. package/dist/commands/daemon.js +15 -1
  10. package/dist/commands/link.d.ts +2 -0
  11. package/dist/commands/link.js +14 -2
  12. package/dist/commands/mesh.js +23 -3
  13. package/dist/commands/packs.js +13 -2
  14. package/dist/commands/sync-core.d.ts +6 -0
  15. package/dist/commands/sync-core.js +75 -1
  16. package/dist/data/command-states.json +3 -0
  17. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  18. package/dist/lib/bot/fleet-cron.js +44 -4
  19. package/dist/lib/bot/run.d.ts +4 -4
  20. package/dist/lib/bot/run.js +5 -3
  21. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  22. package/dist/lib/bot/signals-engine-flag.js +202 -9
  23. package/dist/lib/daemon/catalog.js +2 -0
  24. package/dist/lib/daemon/install.d.ts +2 -1
  25. package/dist/lib/daemon/install.js +9 -0
  26. package/dist/lib/daemon/legacy.d.ts +1 -0
  27. package/dist/lib/daemon/legacy.js +5 -2
  28. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  29. package/dist/lib/daemon/machine-check-owner.js +6 -1
  30. package/dist/lib/daemon/machine-checks.d.ts +52 -1
  31. package/dist/lib/daemon/machine-checks.js +104 -11
  32. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  33. package/dist/lib/daemon/mesh-owner.js +166 -0
  34. package/dist/lib/daemon/native-notice-ledger.d.ts +36 -0
  35. package/dist/lib/daemon/native-notice-ledger.js +156 -0
  36. package/dist/lib/daemon/run.d.ts +15 -0
  37. package/dist/lib/daemon/run.js +72 -3
  38. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  39. package/dist/lib/daemon/selfcheck.js +118 -9
  40. package/dist/lib/daemon/supervisor.d.ts +10 -0
  41. package/dist/lib/daemon/supervisor.js +86 -0
  42. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  43. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  44. package/dist/lib/flag-registry-worker.js +33 -3
  45. package/dist/lib/flag-registry.js +13 -0
  46. package/dist/lib/hook-engine/coverage.d.ts +9 -0
  47. package/dist/lib/hook-engine/coverage.js +56 -0
  48. package/dist/lib/hook-engine/native-stop-compatibility.json +56 -5
  49. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  50. package/dist/lib/mesh/live/daemon/config.js +16 -0
  51. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  52. package/dist/lib/mesh/live/daemon/install.js +142 -1
  53. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  54. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  55. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  56. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  57. package/dist/lib/registry/registry.d.ts +35 -7
  58. package/dist/lib/registry/registry.js +88 -13
  59. package/dist/lib/scan-packages/index.js +23 -2
  60. package/dist/lib/search-index/max-doc-bytes.js +2 -1
  61. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  62. package/dist/lib/service-manager/startup-migration.js +3 -0
  63. package/dist/lib/signals/engine.d.ts +8 -0
  64. package/dist/lib/signals/engine.js +15 -5
  65. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  66. package/dist/lib/sync-core/engine-holds.js +60 -0
  67. package/dist/lib/sync-core/engine-home.d.ts +2 -0
  68. package/dist/lib/sync-core/flag.d.ts +18 -0
  69. package/dist/lib/sync-core/flag.js +66 -0
  70. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  71. package/dist/lib/sync-core/reconcile.js +23 -0
  72. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  73. package/dist/lib/sync-core/rollout-state.js +7 -0
  74. package/dist/lib/sync-core/vault-settings.d.ts +32 -0
  75. package/dist/lib/sync-core/vault-settings.js +147 -0
  76. package/dist/lib/windows/install-followup.d.ts +2 -0
  77. package/dist/lib/windows/install-followup.js +4 -1
  78. package/dist/utils/host-registration.js +3 -1
  79. package/dist/utils/pack-contributions.d.ts +16 -1
  80. package/dist/utils/pack-contributions.js +139 -26
  81. package/dist/utils/self-update.d.ts +3 -1
  82. package/dist/utils/self-update.js +56 -11
  83. package/dist/utils/update-lock.d.ts +151 -14
  84. package/dist/utils/update-lock.js +782 -46
  85. package/dist/utils/version-gate.js +12 -2
  86. package/package.json +7 -7
  87. package/scripts/bench-core.mjs +34 -3
@@ -2,6 +2,7 @@
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
3
  import { loadCachedTokens } from "@indigoai-us/hq-cloud";
4
4
  import { createFlagClient } from "@indigoai-us/hq-flags-client";
5
+ import { decodeJwtClaims } from "./daemon/machine-token-identity.js";
5
6
  const data = workerData;
6
7
  const endpoint = data.endpoint;
7
8
  const COMPANY_UID_RE = /^cmp_[A-Za-z0-9]{3,128}$/;
@@ -10,6 +11,8 @@ async function refresh() {
10
11
  if (!parentPort || typeof endpoint !== "string" || endpoint.trim() === "")
11
12
  return;
12
13
  try {
14
+ const idToken = typeof data.idToken === "string" && data.idToken.length > 0
15
+ ? data.idToken : loadCachedTokens()?.idToken ?? "";
13
16
  const companyUid = typeof data.companyUid === "string" && COMPANY_UID_RE.test(data.companyUid)
14
17
  ? data.companyUid
15
18
  : undefined;
@@ -20,14 +23,41 @@ async function refresh() {
20
23
  endpoint,
21
24
  ...(companyUid ? { companyUid } : {}),
22
25
  ...(companyIdentifiers.length ? { companyIdentifiers } : {}),
23
- getToken: () => typeof data.idToken === "string" && data.idToken.length > 0
24
- ? data.idToken
25
- : loadCachedTokens()?.idToken ?? "",
26
+ getToken: () => idToken,
26
27
  refreshIntervalMs: 0,
27
28
  onError: () => { },
28
29
  });
29
30
  await client.ready();
30
31
  const snapshot = client.snapshot();
32
+ // These are the claims of the token used for the request, not environment
33
+ // identity hints. The service authenticates it again on the scoped resolve.
34
+ const claims = decodeJwtClaims(idToken);
35
+ if ((companyUid || companyIdentifiers.length) && claims?.["custom:entityType"] === "agent" &&
36
+ typeof claims["custom:entityUid"] === "string" && /^agt_[A-Za-z0-9]+$/.test(claims["custom:entityUid"])) {
37
+ // Resolve without company selectors: the service maps this authenticated
38
+ // caller to personUid=agentUid. Never relabel company-scoped decisions.
39
+ const personClient = createFlagClient({
40
+ endpoint,
41
+ getToken: () => idToken,
42
+ refreshIntervalMs: 0,
43
+ onError: () => { },
44
+ });
45
+ try {
46
+ await personClient.ready();
47
+ const personSnapshot = personClient.snapshot();
48
+ if (personSnapshot)
49
+ parentPort.postMessage({ personSnapshot });
50
+ }
51
+ catch {
52
+ // Preserve the independent company refresh when person scope is offline.
53
+ }
54
+ finally {
55
+ try {
56
+ personClient.close();
57
+ }
58
+ catch { /* Same isolated failure boundary. */ }
59
+ }
60
+ }
31
61
  if (snapshot)
32
62
  parentPort.postMessage(snapshot);
33
63
  else
@@ -238,6 +238,19 @@ export function kickFlagRegistryReadiness(dependencies = {}) {
238
238
  worker.unref();
239
239
  };
240
240
  worker.on("message", (value) => {
241
+ if (value && typeof value === "object" && "personSnapshot" in value &&
242
+ isFlagSnapshot(value.personSnapshot)) {
243
+ try {
244
+ writePersonFlagSnapshotFile(value.personSnapshot.flags);
245
+ }
246
+ catch (error) {
247
+ captureFlagRegistryException(error instanceof Error ? error : new Error(String(error)), {
248
+ component: "flag-snapshot-cache-write", company_uid_present: "false",
249
+ ...flagSnapshotWriteFailureTags(error),
250
+ }, sentry);
251
+ }
252
+ return;
253
+ }
241
254
  if (isFlagSnapshot(value)) {
242
255
  heldSnapshot = value;
243
256
  heldSnapshotFetchedAt = Date.now();
@@ -129,6 +129,15 @@ export declare function joinRaw(base: string, rest: string, platform?: NodeJS.Pl
129
129
  * sticky are not x bits. Both sides check it on the `modeBits` table in the shared cases.json.
130
130
  */
131
131
  export declare function modeBitsExecutable(mode: number, root: boolean, owner: boolean, member: boolean): boolean;
132
+ /**
133
+ * As `stop::compat::generation`: the Stop files (and master-hook.sh, which only votes) of hq-core
134
+ * v16.0.48-beta.104 and later are one side, every earlier release the other (`generations` in the
135
+ * shared policy). A file present at a released version of one side votes for it; another version,
136
+ * or a missing or unreadable file, casts no vote. Votes for both sides hold: no released core ships
137
+ * that mix, so the Stop master-hook would run cannot be told. On the later side, a master-hook.sh
138
+ * that is present and not a released later version holds too. Exported for tests.
139
+ */
140
+ export declare function generationHold(root: string): string | null;
132
141
  /** The hooks the old dispatcher runs for `event` on `host` in this HQ root; null when they cannot be read exactly. */
133
142
  export declare function shellHooks(root: string, host: CoreNextHost, event: string): string[] | null;
134
143
  /**
@@ -404,6 +404,9 @@ export function stopCompatibilityHold(root, env = process.env, fixed = (p) => p)
404
404
  const script = unreleasedScript(root, (id) => listed !== null && runs(id));
405
405
  if (script)
406
406
  return script;
407
+ const mixed = generationHold(root);
408
+ if (mixed)
409
+ return mixed;
407
410
  // Any GIT_* name outside the allowlist counts when present, even empty: git dies on an empty GIT_DIR,
408
411
  // GIT_WORK_TREE, GIT_COMMON_DIR or GIT_OBJECT_DIRECTORY, where the native readers ignore the
409
412
  // environment (#2790 r4 C1), and on many others (review r17 C3, C5).
@@ -1416,6 +1419,59 @@ function unreleasedScript(root, runs) {
1416
1419
  }
1417
1420
  return missing;
1418
1421
  }
1422
+ /**
1423
+ * As `stop::compat::generation`: the Stop files (and master-hook.sh, which only votes) of hq-core
1424
+ * v16.0.48-beta.104 and later are one side, every earlier release the other (`generations` in the
1425
+ * shared policy). A file present at a released version of one side votes for it; another version,
1426
+ * or a missing or unreadable file, casts no vote. Votes for both sides hold: no released core ships
1427
+ * that mix, so the Stop master-hook would run cannot be told. On the later side, a master-hook.sh
1428
+ * that is present and not a released later version holds too. Exported for tests.
1429
+ */
1430
+ export function generationHold(root) {
1431
+ const sides = stopCompatibility.generations ?? {};
1432
+ const files = [];
1433
+ for (const side of ['before104', 'from104'])
1434
+ for (const file of Object.keys(sides[side] ?? {}))
1435
+ if (!files.includes(file))
1436
+ files.push(file);
1437
+ const before = [];
1438
+ const from = [];
1439
+ for (const file of files) {
1440
+ let bytes;
1441
+ try {
1442
+ const full = path.join(root, file);
1443
+ if (!fs.statSync(full).isFile())
1444
+ continue;
1445
+ bytes = fs.readFileSync(full);
1446
+ }
1447
+ catch {
1448
+ continue;
1449
+ }
1450
+ const hex = createHash('sha256').update(bytes).digest('hex');
1451
+ if ((sides.from104?.[file] ?? []).includes(hex))
1452
+ from.push(file);
1453
+ else if ((sides.before104?.[file] ?? []).includes(hex))
1454
+ before.push(file);
1455
+ }
1456
+ if (before.length && from.length)
1457
+ return `mixed hq-core Stop files from both sides of v16.0.48-beta.104 (${from.join(', ')} from beta.104 or later; ${before.join(', ')} from before)`;
1458
+ // Review rv-2836: on the later side, a master-hook.sh that is present and not a released beta.104-or-later
1459
+ // version may be an earlier release that is not listed (beta.82 to beta.84 shipped edbac513), which runs the
1460
+ // Claude-only Stop gates on a Cursor payload: held, as Rust does.
1461
+ const master = '.claude/hooks/master-hook.sh';
1462
+ if (from.length && !from.includes(master) && !before.includes(master)) {
1463
+ let present = true;
1464
+ try {
1465
+ fs.lstatSync(path.join(root, master));
1466
+ }
1467
+ catch {
1468
+ present = false;
1469
+ }
1470
+ if (present)
1471
+ return `hq-core Stop files from v16.0.48-beta.104 or later (${from.join(', ')}) with a ${master} that is not a released beta.104 or later version`;
1472
+ }
1473
+ return null;
1474
+ }
1419
1475
  /** Folder hook that master-hook.sh never dispatches (retired; `hq rescue` can leave it on disk). */
1420
1476
  const RETIRED = new Set(['Stop/70-work-mesh-done.sh']);
1421
1477
  function listDir(dir) {
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "dispatcher": [
3
- "HQ_MASTER_CHILD_TIMEOUT"
3
+ "HQ_MASTER_CHILD_TIMEOUT",
4
+ "HQ_MASTER_STOP_BUDGET",
5
+ "HQ_MASTER_STOP_CHILD_TIMEOUT"
4
6
  ],
5
7
  "gitEnvironmentAllowlist": [
6
8
  "GIT_EDITOR",
@@ -92,7 +94,8 @@
92
94
  "e9398ea6abc5ed2c8ad010f5135ea3e37d7f244f9d506d8e0f426d29358c6773"
93
95
  ],
94
96
  "core/hooks/Stop/70-work-mesh-turn-end.sh": [
95
- "1b37183a94a46152c9592d6821f323203438e09ed59956d6239880bb73f896db"
97
+ "1b37183a94a46152c9592d6821f323203438e09ed59956d6239880bb73f896db",
98
+ "b373b582a906b0993a3ce56aa43c1ef0aec6668a6b7e150d59ef3214b7d65b70"
96
99
  ],
97
100
  ".claude/hooks/hq-autocommit-bash-flag.cjs": [
98
101
  "419c65157c0167473ace808bacc7cb5902afa4336f8281f7e7f9c228d74a77a4"
@@ -129,7 +132,8 @@
129
132
  "be7ca74b2524afba56fefd530bf46cbd1dd39a4c181b6a64c87e124b29bdebe7",
130
133
  "b971dae4a2b82bfa5b31782e54717115abaf052457fb1a546893d04cae43adbb",
131
134
  "df3d8ddc15a0c179227c9ba7f855c040973fcee249673156d08b2e2ff2c850b8",
132
- "49c337ceccf0a2d7c2a64f6b1de8c3c4d1da507bc5d7afcd01ed292e1f25abf7"
135
+ "49c337ceccf0a2d7c2a64f6b1de8c3c4d1da507bc5d7afcd01ed292e1f25abf7",
136
+ "9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f"
133
137
  ],
134
138
  "core/scripts/hook-stop-async-drain.sh": [
135
139
  "d7be9aa17c42bd96ba6f9d929240e06d9c057471347374de40ea4be3560da4f5"
@@ -175,7 +179,8 @@
175
179
  "89c0273ad7bac4bda2b114ca5f02c38229343a5418bad92f641e400c2883b4e0"
176
180
  ],
177
181
  "core/scripts/lib/session-id.sh": [
178
- "5178dfed9387cf5924bb71d5cdded37f445fd7b496e6037e81c43af0e7831d5b"
182
+ "5178dfed9387cf5924bb71d5cdded37f445fd7b496e6037e81c43af0e7831d5b",
183
+ "2ebbc50893c7c601a111b9e8f9945afeac88f552d7caeec09c4096f4c27a833d"
179
184
  ],
180
185
  "core/scripts/lib/session-scope-capability.sh": [
181
186
  "388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead"
@@ -188,7 +193,8 @@
188
193
  "db440318b8933b7c436c7b7172adffc9e8fd00c92f0e1745ed5da76871accbe7"
189
194
  ],
190
195
  "core/scripts/lib/work-mesh-live-hook.sh": [
191
- "25dc6d35877366ae91532a28a64d380aee054a8c571df88ed0b741aef29cf34e"
196
+ "25dc6d35877366ae91532a28a64d380aee054a8c571df88ed0b741aef29cf34e",
197
+ "2962e17569d62f5953d41cd516bd7d1b3db9849c3c4fbbd750ae13d7d181bcbe"
192
198
  ],
193
199
  "core/scripts/lib/work-mesh-live-rebind.sh": [
194
200
  "d351bf68103b7f8514d96a945bdeb6c371d9d7ba289347c368a34fea36fd4ad9"
@@ -244,6 +250,7 @@
244
250
  ],
245
251
  "core/hooks/Stop/70-work-mesh-turn-end.sh": [
246
252
  "core/scripts/lib/hook-stop-async.sh",
253
+ "core/scripts/lib/session-id.sh",
247
254
  "core/scripts/lib/work-mesh-enqueue.sh"
248
255
  ],
249
256
  ".claude/hooks/hq-autocommit.sh": [
@@ -307,5 +314,49 @@
307
314
  "core/scripts/board-project-id.sh",
308
315
  "core/scripts/hq-session.sh"
309
316
  ]
317
+ },
318
+ "generations": {
319
+ "before104": {
320
+ "core/hooks/Stop/70-work-mesh-turn-end.sh": [
321
+ "1b37183a94a46152c9592d6821f323203438e09ed59956d6239880bb73f896db"
322
+ ],
323
+ "core/scripts/hook-lib.sh": [
324
+ "89899ae7720f0bdde5cd8e014c614a6aa1796f4b79f23194e397d33b9c7e0bf2",
325
+ "4c98cd6f07d4090c062d980b0d85b0084635efdcd4a09afc05cf77287a74b28d",
326
+ "be7ca74b2524afba56fefd530bf46cbd1dd39a4c181b6a64c87e124b29bdebe7",
327
+ "b971dae4a2b82bfa5b31782e54717115abaf052457fb1a546893d04cae43adbb",
328
+ "df3d8ddc15a0c179227c9ba7f855c040973fcee249673156d08b2e2ff2c850b8",
329
+ "49c337ceccf0a2d7c2a64f6b1de8c3c4d1da507bc5d7afcd01ed292e1f25abf7"
330
+ ],
331
+ "core/scripts/lib/session-id.sh": [
332
+ "5178dfed9387cf5924bb71d5cdded37f445fd7b496e6037e81c43af0e7831d5b"
333
+ ],
334
+ "core/scripts/lib/work-mesh-live-hook.sh": [
335
+ "25dc6d35877366ae91532a28a64d380aee054a8c571df88ed0b741aef29cf34e"
336
+ ],
337
+ ".claude/hooks/master-hook.sh": [
338
+ "fe01ffc7d0380d3c9c391bc4d12f445ed4e82662d92111de442f795f210765ec",
339
+ "7c4ecd88d8790fe152e2cbcff9b452e2d91f391f24c1ba2dce46815a52ced021",
340
+ "f25c7720f24cc160fc149e56a5695aed52515a7425e3cdca87b7b021a0d0573b",
341
+ "e16b0ff06978f85feaa3cb45056c4355a5b8c094e94b36a9cdca2af214ee86b5"
342
+ ]
343
+ },
344
+ "from104": {
345
+ "core/hooks/Stop/70-work-mesh-turn-end.sh": [
346
+ "b373b582a906b0993a3ce56aa43c1ef0aec6668a6b7e150d59ef3214b7d65b70"
347
+ ],
348
+ "core/scripts/hook-lib.sh": [
349
+ "9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f"
350
+ ],
351
+ "core/scripts/lib/session-id.sh": [
352
+ "2ebbc50893c7c601a111b9e8f9945afeac88f552d7caeec09c4096f4c27a833d"
353
+ ],
354
+ "core/scripts/lib/work-mesh-live-hook.sh": [
355
+ "2962e17569d62f5953d41cd516bd7d1b3db9849c3c4fbbd750ae13d7d181bcbe"
356
+ ],
357
+ ".claude/hooks/master-hook.sh": [
358
+ "1a2439aee50652c5143ccd18561a0aa84a1e94848d02c1aa1c99157f70023f29"
359
+ ]
360
+ }
310
361
  }
311
362
  }
@@ -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