@indigoai-us/hq-cli 5.345.221 → 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 (64) hide show
  1. package/CHANGELOG.md +47 -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/core-delegate-w1b.js +9 -3
  6. package/dist/commands/daemon.d.ts +1 -0
  7. package/dist/commands/daemon.js +15 -1
  8. package/dist/commands/link.d.ts +2 -0
  9. package/dist/commands/link.js +14 -2
  10. package/dist/commands/mesh.js +23 -3
  11. package/dist/commands/sync-core.d.ts +6 -0
  12. package/dist/commands/sync-core.js +55 -0
  13. package/dist/data/command-states.json +3 -0
  14. package/dist/lib/daemon/catalog.js +2 -0
  15. package/dist/lib/daemon/install.d.ts +2 -1
  16. package/dist/lib/daemon/install.js +9 -0
  17. package/dist/lib/daemon/legacy.d.ts +1 -0
  18. package/dist/lib/daemon/legacy.js +5 -2
  19. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  20. package/dist/lib/daemon/machine-check-owner.js +6 -1
  21. package/dist/lib/daemon/machine-checks.d.ts +7 -1
  22. package/dist/lib/daemon/machine-checks.js +10 -1
  23. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  24. package/dist/lib/daemon/mesh-owner.js +166 -0
  25. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  26. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  27. package/dist/lib/daemon/run.d.ts +15 -0
  28. package/dist/lib/daemon/run.js +71 -3
  29. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  30. package/dist/lib/daemon/selfcheck.js +118 -9
  31. package/dist/lib/hook-engine/coverage.d.ts +9 -0
  32. package/dist/lib/hook-engine/coverage.js +56 -0
  33. package/dist/lib/hook-engine/native-stop-compatibility.json +56 -5
  34. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  35. package/dist/lib/mesh/live/daemon/config.js +16 -0
  36. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  37. package/dist/lib/mesh/live/daemon/install.js +142 -1
  38. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  39. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  40. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  41. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  42. package/dist/lib/registry/registry.d.ts +35 -7
  43. package/dist/lib/registry/registry.js +88 -13
  44. package/dist/lib/scan-packages/index.js +24 -2
  45. package/dist/lib/search-index/max-doc-bytes.js +2 -1
  46. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  47. package/dist/lib/service-manager/startup-migration.js +3 -0
  48. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  49. package/dist/lib/sync-core/engine-holds.js +60 -0
  50. package/dist/lib/sync-core/engine-home.d.ts +2 -0
  51. package/dist/lib/sync-core/reconcile.js +8 -0
  52. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  53. package/dist/lib/sync-core/vault-settings.js +131 -0
  54. package/dist/lib/windows/install-followup.d.ts +2 -0
  55. package/dist/lib/windows/install-followup.js +4 -1
  56. package/dist/utils/host-registration.js +3 -1
  57. package/dist/utils/pack-contributions.d.ts +3 -0
  58. package/dist/utils/pack-contributions.js +110 -23
  59. package/dist/utils/self-update.d.ts +3 -1
  60. package/dist/utils/self-update.js +56 -11
  61. package/dist/utils/update-lock.d.ts +151 -14
  62. package/dist/utils/update-lock.js +782 -46
  63. package/dist/utils/version-gate.js +12 -2
  64. package/package.json +7 -7
@@ -7,6 +7,7 @@ import { readDaemonConfig } from "./config.js";
7
7
  import { sameHqRoot } from "../hook-engine/registration-identity.js";
8
8
  import { nativeSessionStartRegistered } from "./machine-check-registration.js";
9
9
  import { codexEnvEvidence, grokEnvEvidence } from "../doctor/platform.js";
10
+ import { NATIVE_NOTICE_LEDGER_FILE, NATIVE_NOTICE_LEDGER_REFUSED, nativeNoticeLedgerUsable } from "./native-notice-ledger.js";
10
11
  /**
11
12
  * How old the daemon's machine-check results file may be and still count as
12
13
  * proof the schedule is running: two hourly intervals plus the first delay,
@@ -16,6 +17,7 @@ export const MACHINE_CHECK_RESULTS_FRESH_MS = 2 * MACHINE_CHECKS_INTERVAL_MS + M
16
17
  function errorName(error) {
17
18
  return error instanceof Error ? error.code ?? error.name : "UnknownError";
18
19
  }
20
+ export { NATIVE_NOTICE_LEDGER_FILE, NATIVE_NOTICE_LEDGER_REFUSED, nativeNoticeLedgerUsable };
19
21
  /**
20
22
  * The session's harness: `HQ_HARNESS` when set, else the Codex or Grok runtime
21
23
  * variables (the same markers `lanes` uses for the orchestrator engine), else
@@ -36,7 +38,8 @@ function sessionHarness(env) {
36
38
  * when every host-local signal shows the schedule is really running here:
37
39
  * not Windows (checks start with /bin/bash), the rollout flag is on with no
38
40
  * kill switch, the daemon heartbeat file is fresh, and the schedule wrote its
39
- * results file (which needs a resolved HQ root) within the freshness window.
41
+ * results file (which needs a resolved HQ root) within the freshness window,
42
+ * and the native notice can use its ledger (nativeNoticeLedgerUsable).
40
43
  * Anything that cannot be observed answers "legacy" with the reason.
41
44
  */
42
45
  function decideOwner(env, home, now, platform) {
@@ -80,6 +83,8 @@ function decideOwner(env, home, now, platform) {
80
83
  if (!Number.isFinite(age) || age > MACHINE_CHECK_RESULTS_FRESH_MS) {
81
84
  return { owner: "legacy", reason: "machine-check results stale" };
82
85
  }
86
+ if (!nativeNoticeLedgerUsable(env, home))
87
+ return { owner: "legacy", reason: NATIVE_NOTICE_LEDGER_REFUSED };
83
88
  return { owner: "daemon", reason: "daemon live and schedule results fresh" };
84
89
  }
85
90
  /** Internal, offline protocol shared with the legacy dispatcher. */
@@ -147,6 +147,8 @@ export interface MachineCheckScheduleOptions {
147
147
  /** Test seam: the gate, read at each tick. Default machineChecksScheduleOn. */
148
148
  enabled?: (env: NodeJS.ProcessEnv, home: string) => boolean;
149
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;
150
152
  }
151
153
  export interface MachineCheckSchedule {
152
154
  /** One scheduled tick (tests). Resolves when the tick is done; never rejects. */
@@ -157,7 +159,11 @@ export interface MachineCheckSchedule {
157
159
  * The daemon's machine-check timer. Each tick runs a batch only when the new
158
160
  * hook core (`core.next`) is on for this machine and no kill switch is set;
159
161
  * both are read at every tick, so turning either off stops the next run
160
- * 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
161
167
  * logs one line with the error's name only.
162
168
  */
163
169
  export declare function startMachineCheckSchedule(options: MachineCheckScheduleOptions): MachineCheckSchedule;
@@ -40,6 +40,7 @@ import { coreNextEnabled } from "../../utils/core-next-flag.js";
40
40
  import { coreNextKillReason } from "../../utils/core-next-kill.js";
41
41
  import { isExcludedWindowsBash, resolveWindowsBash } from "../../utils/windows-bash.js";
42
42
  import { anyNativeSessionStartRegistered } from "./machine-check-registration.js";
43
+ import { nativeNoticeLedgerUsable } from "./native-notice-ledger.js";
43
44
  import { openStoreDir } from "../safe-store.js";
44
45
  import { readStoreFile, writeStoreFile } from "./paths.js";
45
46
  import { cutUtf8, MACHINE_CHECK_DETAIL_BYTES } from "./state-file.js";
@@ -402,7 +403,11 @@ export function machineChecksScheduleOn(env, home) {
402
403
  * The daemon's machine-check timer. Each tick runs a batch only when the new
403
404
  * hook core (`core.next`) is on for this machine and no kill switch is set;
404
405
  * both are read at every tick, so turning either off stops the next run
405
- * 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
406
411
  * logs one line with the error's name only.
407
412
  */
408
413
  export function startMachineCheckSchedule(options) {
@@ -427,6 +432,10 @@ export function startMachineCheckSchedule(options) {
427
432
  options.log("info", "machine checks skipped: no native SessionStart");
428
433
  return;
429
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
+ }
430
439
  lastStart = now();
431
440
  await run({ hqRoot, env: options.env, resultsFile: options.resultsFile });
432
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
@@ -27,6 +27,7 @@ import { effectiveSyncOwner, readDaemonConfig } from "./config.js";
27
27
  import { inspectEngineHome } from "../sync-core/engine-home.js";
28
28
  import { fullModeHold } from "../sync-core/reconcile.js";
29
29
  import { readSyncCoreRolloutState } from "../sync-core/rollout-state.js";
30
+ import { readSyncCoreVaultSettings } from "../sync-core/vault-settings.js";
30
31
  import { assertPersonalServiceSessionCapability, readRemoteControlPoolsConfig, remoteControlPoolSecretsEnv, } from "./remote-control-pools.js";
31
32
  import { loadLanesConfig } from "../lanes/config.js";
32
33
  import { daemonLanesReconcileHandler } from "../lanes/daemon-reconcile.js";
@@ -43,6 +44,9 @@ import { acquireDaemonLock, isProcessAlive, processCommandLine, releaseDaemonLoc
43
44
  import { retireLegacyMeshUnits } from "./migrate.js";
44
45
  import { daemonDir as meshDaemonDir, daemonPidPath as meshDaemonPidPath } from "../mesh/live/daemon/paths.js";
45
46
  import { readPidLock } from "../mesh/live/daemon/pid-lock.js";
47
+ import { homeIsLoginSafe, isLoginHome, meshJobLoadedForHome, removeMeshUnitFromOtherHome } from "../mesh/live/daemon/unit-home.js";
48
+ import { meshOwnerHere } from "./mesh-owner.js";
49
+ import { repairMeshUnitFromOtherHome } from "../mesh/live/daemon/install.js";
46
50
  import { registryDir, registryFile } from "../registry/registry.js";
47
51
  import { updateAnywhereRuntimeRevocationMarker } from "../anywhere-runtime-revocation-marker.js";
48
52
  import { classifyWindowsTask, currentWindowsIdentity, daemonRootRefusal } from "./install.js";
@@ -80,6 +84,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
80
84
  const state = readSyncCoreRolloutState(home);
81
85
  if (!state)
82
86
  return [];
87
+ const settings = readSyncCoreVaultSettings(home);
83
88
  return state.vaults.map((vault) => {
84
89
  const plan = inspectEngineHome(home, hqRoot, {
85
90
  uid: vault.uid,
@@ -90,6 +95,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
90
95
  binaryPath: state.binaryPath,
91
96
  release: state.release,
92
97
  ...(vault.legacyOffSince ? { legacyOffSince: vault.legacyOffSince } : {}),
98
+ ...(settings.has(vault.uid) ? { settings: settings.get(vault.uid) } : {}),
93
99
  }, platform);
94
100
  const releaseHold = vault.phase === "full" ? fullModeHold(vault, state.release, platform) : undefined;
95
101
  return releaseHold ? { ...plan, blockedReason: releaseHold } : plan;
@@ -410,6 +416,7 @@ export function probeLegacyUnits(platform, home) {
410
416
  return findLegacyUnits({
411
417
  platform,
412
418
  home,
419
+ homeIsLogin: platform === "darwin" ? homeIsLoginSafe(home) : true,
413
420
  existsSync: fs.existsSync,
414
421
  listDir: (dir) => fs.readdirSync(dir),
415
422
  launchdJobLoaded: (label) => {
@@ -421,7 +428,7 @@ export function probeLegacyUnits(platform, home) {
421
428
  windowsHide: true,
422
429
  timeout: 15_000,
423
430
  });
424
- return result.status === 0;
431
+ return meshJobLoadedForHome({ status: result.status, stdout: result.stdout ?? "" }, home);
425
432
  },
426
433
  windowsTaskOwner,
427
434
  });
@@ -657,6 +664,43 @@ export function withUserRuntimeDir(env, host) {
657
664
  const dir = `/run/user/${host.uid}`;
658
665
  return host.exists(dir) ? { ...env, XDG_RUNTIME_DIR: dir } : env;
659
666
  }
667
+ export function checkMeshUnitHome(opts) {
668
+ if (opts.platform !== "darwin")
669
+ return true;
670
+ let homeIsLogin;
671
+ try {
672
+ homeIsLogin = opts.isLoginHome(opts.home);
673
+ }
674
+ catch (err) {
675
+ opts.log("warn", `could not check where the Work Mesh service was loaded from: ${err.message}`);
676
+ opts.log("warn", `HOME ${opts.home} could not be confirmed as this account's home folder; leaving the Work Mesh LaunchAgent alone`);
677
+ return false;
678
+ }
679
+ if (!homeIsLogin) {
680
+ opts.log("warn", `HOME ${opts.home} is not this account's home folder; leaving the Work Mesh LaunchAgent alone`);
681
+ return false;
682
+ }
683
+ try {
684
+ if (!opts.takesOverMesh) {
685
+ const repaired = opts.repair();
686
+ if (repaired.from)
687
+ opts.log(repaired.repaired ? "warn" : "error", repaired.message ?? `Work Mesh service loaded from ${repaired.from}`);
688
+ }
689
+ else if (typeof opts.uid === "number") {
690
+ const other = opts.remove({ home: opts.home, uid: opts.uid, run: opts.run });
691
+ if (other.removed) {
692
+ opts.log("warn", `stopped a Work Mesh service that was loaded from ${other.from}, outside this account's home folder`);
693
+ }
694
+ else if (other.from) {
695
+ opts.log("error", `a Work Mesh service is loaded from ${other.from}, outside this account's home folder, and could not be stopped: ${other.error}`);
696
+ }
697
+ }
698
+ }
699
+ catch (err) {
700
+ opts.log("error", `could not repair the Work Mesh service: ${err.message}`);
701
+ }
702
+ return true;
703
+ }
660
704
  export async function runDaemon(opts) {
661
705
  // Before anything reads the environment: hqd and every service inherit it.
662
706
  const started = daemonStartEnv(opts.env);
@@ -825,11 +869,35 @@ export async function runDaemon(opts) {
825
869
  }
826
870
  return legacyCache.units;
827
871
  };
828
- const legacyMesh = legacyMeshUnitsToRetire(legacyUnits(), {
872
+ const meshEnabled = enabledServices(machineType, initial).includes("mesh");
873
+ const launchctl = (command, args) => {
874
+ const r = spawnSync(command, args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
875
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
876
+ };
877
+ const homeIsLogin = checkMeshUnitHome({
878
+ platform,
879
+ home,
880
+ uid: process.getuid?.(),
881
+ isLoginHome: opts.isLoginHome ?? isLoginHome,
882
+ remove: opts.removeMeshUnitFromOtherHome ?? removeMeshUnitFromOtherHome,
883
+ run: launchctl,
884
+ log: (level, message) => log(level, message),
885
+ takesOverMesh: (opts.managed === true || opts.host !== undefined) && meshEnabled,
886
+ repair: () => repairMeshUnitFromOtherHome({
887
+ platform: "darwin",
888
+ home,
889
+ uid: process.getuid?.(),
890
+ env,
891
+ hqRoot: initial.hqRoot ?? (env.HQ_ROOT?.trim() || undefined),
892
+ run: launchctl,
893
+ meshOwner: () => (meshEnabled ? meshOwnerHere(home, env) : "hq-daemon-mesh-off"),
894
+ }),
895
+ });
896
+ const legacyMesh = !homeIsLogin ? [] : legacyMeshUnitsToRetire(legacyUnits(), {
829
897
  platform,
830
898
  managed: opts.managed === true,
831
899
  hosted: opts.host !== undefined,
832
- meshEnabled: enabledServices(machineType, initial).includes("mesh"),
900
+ meshEnabled,
833
901
  });
834
902
  if (legacyMesh.length > 0) {
835
903
  try {