@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
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import * as path from "node:path";
13
13
  import { syncCoreUnitId } from "../sync-core/engine-home.js";
14
+ import { engineSettingsEnv } from "../sync-core/vault-settings.js";
14
15
  import { engineOwnedManifestScopes } from "../sync-core/manifest-scopes.js";
15
16
  import { SYNC_RUNNER_OWNER, syncRunnerUnleasedBlockReason } from "./sync-runner.js";
16
17
  import { vaultSkipEnv } from "../vault-sync-switches.js";
@@ -268,6 +269,7 @@ function planService(service, ctx) {
268
269
  HQ_SYNC_MODE: full ? "full" : "readonly",
269
270
  ...(full ? { HQ_SYNC_FULL_VAULT: "1", HQ_SYNC_PROTOCOL: "1" } : {}),
270
271
  HQ_SYNC_CORE_RELEASE: vault.release,
272
+ ...engineSettingsEnv(vault.settings),
271
273
  },
272
274
  ...(full ? { heartbeatTimeoutMs: 180_000 } : {}),
273
275
  blocked: firstBlock([
@@ -68,6 +68,7 @@ export interface DaemonHost {
68
68
  systemUnitDir: string;
69
69
  /** Extra environment baked into the unit (PATH of the installing shell, HQ_DAEMON_DIR). */
70
70
  env?: Record<string, string>;
71
+ loginHome?: string;
71
72
  }
72
73
  export interface InstallOptions {
73
74
  scope: InstallScope;
@@ -198,7 +199,7 @@ export interface RefreshDaemonPlistResult {
198
199
  * finds the old plist (see daemonPlistNeedsRefresh). It must not run inside
199
200
  * the daemon's own job: the bootout would end the caller before the bootstrap.
200
201
  */
201
- export declare function refreshDaemonPlist(host: Pick<DaemonHost, "home" | "uid">, deps: {
202
+ export declare function refreshDaemonPlist(host: Pick<DaemonHost, "home" | "uid" | "loginHome">, deps: {
202
203
  run: RunCommand;
203
204
  sleep?: SleepFn;
204
205
  }): RefreshDaemonPlistResult;
@@ -26,6 +26,7 @@ import { readPidLock } from "../mesh/live/daemon/pid-lock.js";
26
26
  import { userToolDirs } from "./tools.js";
27
27
  import { liveDaemonLock, verifyDaemonForKill } from "./lock.js";
28
28
  import { daemonPaths } from "./paths.js";
29
+ import { assertLoginHome, homeIsLoginSafe } from "../mesh/live/daemon/unit-home.js";
29
30
  export const DAEMON_LAUNCHD_LABEL = "ai.getindigo.hq-daemon";
30
31
  export const DAEMON_SYSTEMD_UNIT = "hq-daemon.service";
31
32
  /**
@@ -427,6 +428,8 @@ function activate(plan, host, run, sleep, previous = null) {
427
428
  }
428
429
  }
429
430
  export function installDaemonUnit(host, options, deps) {
431
+ if (host.platform === "darwin")
432
+ assertLoginHome("install", host.home, host.loginHome, DAEMON_LAUNCHD_LABEL);
430
433
  const plan = planDaemonUnit(host, options);
431
434
  if (plan.kind === "manual") {
432
435
  return { kind: plan.kind, unitPath: "", installed: false, running: false, manualCommand: plan.manualCommand };
@@ -584,6 +587,8 @@ export function retryLaunchdBootstrap(plistPath, run, uid, sleep = blockingSleep
584
587
  */
585
588
  export function refreshDaemonPlist(host, deps) {
586
589
  const plistPath = launchdPlistPath(host.home, { label: DAEMON_LAUNCHD_LABEL });
590
+ if (!homeIsLoginSafe(host.home, host.loginHome))
591
+ return { action: "none", plistPath };
587
592
  if (!fs.existsSync(plistPath))
588
593
  return { action: "none", plistPath };
589
594
  const source = fs.readFileSync(plistPath, "utf8");
@@ -751,6 +756,8 @@ export function daemonServiceStatus(host, run, daemonPid) {
751
756
  */
752
757
  export function startDaemonUnit(host, deps) {
753
758
  const sleep = deps.sleep ?? blockingSleep;
759
+ if (host.platform === "darwin")
760
+ assertLoginHome("start", host.home, host.loginHome, DAEMON_LAUNCHD_LABEL);
754
761
  // An older install's plist runs through HQ.app and is skipped at login:
755
762
  // rewrite it first, so the unit this loads or starts is the fixed one.
756
763
  const previousPid = deps.daemonPid();
@@ -954,6 +961,8 @@ export function windowsInteractiveSession(run, user) {
954
961
  });
955
962
  }
956
963
  export function uninstallDaemonUnit(host, options, deps) {
964
+ if (host.platform === "darwin")
965
+ assertLoginHome("remove", host.home, host.loginHome, DAEMON_LAUNCHD_LABEL);
957
966
  // A system uninstall does not need the login user; only the unit path matters.
958
967
  const plan = host.platform === "linux" && options.scope === "system"
959
968
  ? { kind: "systemd-system", unitPath: path.join(host.systemUnitDir, DAEMON_SYSTEMD_UNIT), rendered: "" }
@@ -30,6 +30,7 @@ export interface LegacyProbeDeps {
30
30
  listDir: (dir: string) => string[];
31
31
  /** True when launchctl can print the GUI-domain job despite a missing plist. */
32
32
  launchdJobLoaded: (label: string) => boolean;
33
+ homeIsLogin?: boolean;
33
34
  /** Whether the task exists and runs as the current user. Another user's task is never taken over. */
34
35
  windowsTaskOwner: (taskName: string) => WindowsTaskOwner;
35
36
  /**
@@ -55,8 +55,11 @@ function darwinUnits(deps) {
55
55
  const at = (label) => path.join(dir, `${label}.plist`);
56
56
  const add = (unitId, service, label, migratable = true) => units.push({ unitId, service, kind: "launchd", name: label, path: at(label), migratable });
57
57
  const meshLabel = "ai.getindigo.hq-mesh-daemon";
58
- if (deps.existsSync(at(meshLabel)) || deps.launchdJobLoaded(meshLabel))
59
- add("mesh", "mesh", meshLabel);
58
+ if (deps.existsSync(at(meshLabel)) || deps.launchdJobLoaded(meshLabel)) {
59
+ add("mesh", "mesh", meshLabel, deps.homeIsLogin !== false);
60
+ if (deps.homeIsLogin === false)
61
+ units[units.length - 1].notMineReason = "HOME is not this account's home folder, and macOS has one Work Mesh service per login";
62
+ }
60
63
  for (const file of safeList(deps, dir).sort()) {
61
64
  const m = /^ai\.getindigo\.hq-bot\.(.+)\.plist$/.exec(file);
62
65
  if (m)
@@ -1,9 +1,11 @@
1
+ import { NATIVE_NOTICE_LEDGER_FILE, NATIVE_NOTICE_LEDGER_REFUSED, nativeNoticeLedgerUsable } from "./native-notice-ledger.js";
1
2
  /**
2
3
  * How old the daemon's machine-check results file may be and still count as
3
4
  * proof the schedule is running: two hourly intervals plus the first delay,
4
5
  * so one late or skipped batch does not flip the owner.
5
6
  */
6
7
  export declare const MACHINE_CHECK_RESULTS_FRESH_MS: number;
8
+ export { NATIVE_NOTICE_LEDGER_FILE, NATIVE_NOTICE_LEDGER_REFUSED, nativeNoticeLedgerUsable };
7
9
  /** Internal, offline protocol shared with the legacy dispatcher. */
8
10
  export declare function machineCheckOwner(env?: NodeJS.ProcessEnv, home?: string, options?: {
9
11
  now?: Date;
@@ -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. */
@@ -58,6 +58,20 @@ export type MachineCheckResult = DaemonStateMachineCheck;
58
58
  export interface RunMachineChecksOptions {
59
59
  hqRoot: string;
60
60
  env?: NodeJS.ProcessEnv;
61
+ /**
62
+ * Run every script in collect-only mode (HQ_MACHINE_CHECK_COLLECT_ONLY=1):
63
+ * it reports its finding but writes no delivery stamp. Set only for a core
64
+ * that advertises the mode (machineCheckCollectOnlySupported). Default off,
65
+ * and the variable is then removed from the script's environment.
66
+ */
67
+ collectOnly?: boolean;
68
+ /**
69
+ * With collectOnly: checks that run once in normal mode anyway, because the
70
+ * native notice has delivered their last finding. Normal mode writes the
71
+ * script's own show-once record and prints the same text, so the finding
72
+ * keeps its fingerprint and is not shown again.
73
+ */
74
+ commitIds?: ReadonlySet<string>;
61
75
  now?: () => Date;
62
76
  /** Write the results here (through the store rules) after the batch. */
63
77
  resultsFile?: string;
@@ -97,6 +111,19 @@ type ScriptCheck = {
97
111
  };
98
112
  /** The script's absolute path when it may be run; else why not. */
99
113
  export declare function checkMachineCheckScript(hqRoot: string, relative: string, platform?: NodeJS.Platform): ScriptCheck;
114
+ /** The core.yaml key that advertises collect-only support. */
115
+ export declare const MACHINE_CHECK_COLLECT_ONLY_KEY = "machineCheckCollectOnly";
116
+ /**
117
+ * Whether the installed core's scripts support collect-only mode: a
118
+ * top-level `machineCheckCollectOnly: 1` line in `<root>/core/core.yaml`
119
+ * (hq-core-staging, Q47). In that mode a script reports its finding but
120
+ * leaves its delivery stamp (the setup nag's .last file, the welcome-brief
121
+ * marker, client-health's and ensure-hq-desktop's show-once records) to the
122
+ * session that shows the finding. Operational caches and throttles are kept.
123
+ * An older core, or a core.yaml that cannot be read, answers false and the
124
+ * batch runs as before.
125
+ */
126
+ export declare function machineCheckCollectOnlySupported(hqRoot: string): boolean;
100
127
  /**
101
128
  * Run every machine check once, one at a time. A call while a batch is
102
129
  * running returns that batch. Inside a machine check
@@ -147,7 +174,20 @@ export interface MachineCheckScheduleOptions {
147
174
  /** Test seam: the gate, read at each tick. Default machineChecksScheduleOn. */
148
175
  enabled?: (env: NodeJS.ProcessEnv, home: string) => boolean;
149
176
  registered?: (root: string, home: string, env: NodeJS.ProcessEnv) => boolean;
177
+ /** Test seam: whether the native notice can use its ledger. Default nativeNoticeLedgerUsable. */
178
+ ledgerUsable?: (env: NodeJS.ProcessEnv, home: string) => boolean;
179
+ /** Test seam: whether the core supports collect-only. Default machineCheckCollectOnlySupported. */
180
+ collectOnlySupported?: (hqRoot: string) => boolean;
181
+ /** Test seam: the fingerprints the native notice delivered. Default nativeNoticeShownFingerprints. */
182
+ shownFingerprints?: (env: NodeJS.ProcessEnv, home: string) => ReadonlySet<string>;
150
183
  }
184
+ /**
185
+ * The checks to commit in this batch: each whose last result (the results
186
+ * file the native notice reads) carries a fingerprint the native notice has
187
+ * recorded as delivered, unless this schedule already committed that same
188
+ * fingerprint.
189
+ */
190
+ export declare function machineChecksToCommit(previous: readonly MachineCheckResult[], shown: ReadonlySet<string>, committed: ReadonlyMap<string, string>): Map<string, string>;
151
191
  export interface MachineCheckSchedule {
152
192
  /** One scheduled tick (tests). Resolves when the tick is done; never rejects. */
153
193
  tick(): Promise<void>;
@@ -157,8 +197,19 @@ export interface MachineCheckSchedule {
157
197
  * The daemon's machine-check timer. Each tick runs a batch only when the new
158
198
  * hook core (`core.next`) is on for this machine and no kill switch is set;
159
199
  * 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
200
+ * without a daemon restart. It also runs none when the native notice cannot
201
+ * use its ledger (nativeNoticeLedgerUsable, the rule the machine-check owner
202
+ * applies): the owner then hands the checks to the legacy hooks, and a batch
203
+ * here would run them a second time and leave cooldown stamps that silence
204
+ * the legacy run, so neither path would show the finding. A batch already running finishes. A failed batch
161
205
  * logs one line with the error's name only.
206
+ *
207
+ * When the installed core advertises collect-only support
208
+ * (machineCheckCollectOnlySupported), the batch runs its scripts in that mode
209
+ * and they write no delivery stamp. That also covers the split-HOME edge the
210
+ * ledger rule cannot see: the daemon's HOME passes the rule while the
211
+ * session's is refused, both run, and the session's legacy run still shows
212
+ * the finding. With an older core nothing changes.
162
213
  */
163
214
  export declare function startMachineCheckSchedule(options: MachineCheckScheduleOptions): MachineCheckSchedule;
164
215
  export {};
@@ -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, nativeNoticeShownFingerprints } 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";
@@ -184,6 +185,31 @@ export function checkMachineCheckScript(hqRoot, relative, platform = process.pla
184
185
  store.close();
185
186
  }
186
187
  }
188
+ /** The core.yaml key that advertises collect-only support. */
189
+ export const MACHINE_CHECK_COLLECT_ONLY_KEY = "machineCheckCollectOnly";
190
+ const COLLECT_ONLY_LINE = /^machineCheckCollectOnly:[ \t]*1[ \t]*(?:#.*)?$/m;
191
+ /**
192
+ * Whether the installed core's scripts support collect-only mode: a
193
+ * top-level `machineCheckCollectOnly: 1` line in `<root>/core/core.yaml`
194
+ * (hq-core-staging, Q47). In that mode a script reports its finding but
195
+ * leaves its delivery stamp (the setup nag's .last file, the welcome-brief
196
+ * marker, client-health's and ensure-hq-desktop's show-once records) to the
197
+ * session that shows the finding. Operational caches and throttles are kept.
198
+ * An older core, or a core.yaml that cannot be read, answers false and the
199
+ * batch runs as before.
200
+ */
201
+ export function machineCheckCollectOnlySupported(hqRoot) {
202
+ try {
203
+ const file = path.join(path.resolve(hqRoot), "core", "core.yaml");
204
+ const stat = fs.statSync(file);
205
+ if (!stat.isFile() || stat.size > 256 * 1024)
206
+ return false;
207
+ return COLLECT_ONLY_LINE.test(fs.readFileSync(file, "utf8"));
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ }
187
213
  function payload(event, hqRoot) {
188
214
  return event === "SessionStart"
189
215
  ? JSON.stringify({ hook_event_name: "SessionStart", source: "startup", session_id: SESSION_ID, cwd: hqRoot })
@@ -198,21 +224,26 @@ function payload(event, hqRoot) {
198
224
  * TerminateProcess for either signal (there are no POSIX process groups), so
199
225
  * the first kill already ends it and the second is a no-op.
200
226
  */
201
- function runScript(shell, file, spec, hqRoot, env, killGraceMs, drainMs) {
227
+ function runScript(shell, file, spec, hqRoot, env, killGraceMs, drainMs, collectOnly) {
202
228
  return new Promise((resolve) => {
203
229
  const chunks = [];
204
230
  let kept = 0;
205
231
  let child;
232
+ const scriptEnv = {
233
+ ...env,
234
+ CLAUDE_PROJECT_DIR: hqRoot,
235
+ HQ_ROOT: hqRoot,
236
+ HQ_MACHINE_CHECK: "1",
237
+ HQ_MACHINE_CHECKS_RUNNING: "1",
238
+ };
239
+ if (collectOnly)
240
+ scriptEnv.HQ_MACHINE_CHECK_COLLECT_ONLY = "1";
241
+ else
242
+ delete scriptEnv.HQ_MACHINE_CHECK_COLLECT_ONLY;
206
243
  try {
207
244
  child = spawn(shell, [file], {
208
245
  cwd: hqRoot,
209
- env: {
210
- ...env,
211
- CLAUDE_PROJECT_DIR: hqRoot,
212
- HQ_ROOT: hqRoot,
213
- HQ_MACHINE_CHECK: "1",
214
- HQ_MACHINE_CHECKS_RUNNING: "1",
215
- },
246
+ env: scriptEnv,
216
247
  stdio: ["pipe", "pipe", "ignore"],
217
248
  shell: false,
218
249
  windowsHide: true,
@@ -268,7 +299,7 @@ async function runOne(spec, options, env, disabled, shell) {
268
299
  const checked = checkMachineCheckScript(options.hqRoot, spec.path, options.platform ?? process.platform);
269
300
  if (!checked.ok)
270
301
  return { id: spec.id, status: "unknown", checked_at: at(), summary: checked.summary };
271
- const run = await runScript(shell, checked.file, spec, path.resolve(options.hqRoot), env, options.killGraceMs ?? MACHINE_CHECK_KILL_GRACE_MS, options.drainMs ?? MACHINE_CHECK_DRAIN_MS);
302
+ const run = await runScript(shell, checked.file, spec, path.resolve(options.hqRoot), env, options.killGraceMs ?? MACHINE_CHECK_KILL_GRACE_MS, options.drainMs ?? MACHINE_CHECK_DRAIN_MS, options.collectOnly === true && !(options.commitIds?.has(spec.id) ?? false));
272
303
  if (run.outcome === "timed-out") {
273
304
  return { id: spec.id, status: "unknown", checked_at: at(), summary: `timed out after ${Math.round(spec.timeoutMs / 1000)}s` };
274
305
  }
@@ -398,12 +429,39 @@ export function machineChecksKillSwitchSet(env, home) {
398
429
  export function machineChecksScheduleOn(env, home) {
399
430
  return !machineChecksKillSwitchSet(env, home) && machineChecksCoreNextOn(env);
400
431
  }
432
+ /**
433
+ * The checks to commit in this batch: each whose last result (the results
434
+ * file the native notice reads) carries a fingerprint the native notice has
435
+ * recorded as delivered, unless this schedule already committed that same
436
+ * fingerprint.
437
+ */
438
+ export function machineChecksToCommit(previous, shown, committed) {
439
+ const out = new Map();
440
+ for (const result of previous) {
441
+ const print = result.fingerprint;
442
+ if (!print || !shown.has(print) || committed.get(result.id) === print)
443
+ continue;
444
+ out.set(result.id, print);
445
+ }
446
+ return out;
447
+ }
401
448
  /**
402
449
  * The daemon's machine-check timer. Each tick runs a batch only when the new
403
450
  * hook core (`core.next`) is on for this machine and no kill switch is set;
404
451
  * 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
452
+ * without a daemon restart. It also runs none when the native notice cannot
453
+ * use its ledger (nativeNoticeLedgerUsable, the rule the machine-check owner
454
+ * applies): the owner then hands the checks to the legacy hooks, and a batch
455
+ * here would run them a second time and leave cooldown stamps that silence
456
+ * the legacy run, so neither path would show the finding. A batch already running finishes. A failed batch
406
457
  * logs one line with the error's name only.
458
+ *
459
+ * When the installed core advertises collect-only support
460
+ * (machineCheckCollectOnlySupported), the batch runs its scripts in that mode
461
+ * and they write no delivery stamp. That also covers the split-HOME edge the
462
+ * ledger rule cannot see: the daemon's HOME passes the rule while the
463
+ * session's is refused, both run, and the session's legacy run still shows
464
+ * the finding. With an older core nothing changes.
407
465
  */
408
466
  export function startMachineCheckSchedule(options) {
409
467
  const now = options.now ?? (() => Date.now());
@@ -412,6 +470,8 @@ export function startMachineCheckSchedule(options) {
412
470
  const enabled = options.enabled ?? machineChecksScheduleOn;
413
471
  let lastStart;
414
472
  let closed = false;
473
+ /** Check id to the fingerprint last committed for it (in memory; a restart may commit once more, which is harmless). */
474
+ const committed = new Map();
415
475
  const tick = async () => {
416
476
  try {
417
477
  if (closed)
@@ -427,8 +487,41 @@ export function startMachineCheckSchedule(options) {
427
487
  options.log("info", "machine checks skipped: no native SessionStart");
428
488
  return;
429
489
  }
490
+ if (!(options.ledgerUsable ?? nativeNoticeLedgerUsable)(options.env, options.home)) {
491
+ options.log("info", "machine checks skipped: the native notice cannot use its ledger");
492
+ return;
493
+ }
430
494
  lastStart = now();
431
- await run({ hqRoot, env: options.env, resultsFile: options.resultsFile });
495
+ // Q47: the batch only collects. A core that supports it leaves every
496
+ // delivery stamp to the session that shows the finding, so a batch can
497
+ // never silence a session that would otherwise have shown it.
498
+ //
499
+ // While the daemon owns the checks the native notice shows the finding
500
+ // and records only its fingerprint, never the script's own record
501
+ // (the setup nag's stamp, the desktop result claim, client-health's
502
+ // pending files). So a check whose last finding the notice has
503
+ // delivered runs once in normal mode, which writes that record. In the
504
+ // split-HOME edge the session's notice refused its ledger and recorded
505
+ // nothing, so the check stays collect-only and the legacy run shows it.
506
+ // If the owner flips from daemon to legacy between the notice's show
507
+ // and this commit, the legacy run finds the record unwritten and shows
508
+ // the finding once more, then writes the record itself: one repeat at
509
+ // most, inside one batch interval.
510
+ const collectOnly = (options.collectOnlySupported ?? machineCheckCollectOnlySupported)(hqRoot);
511
+ let commit = new Map();
512
+ if (collectOnly) {
513
+ const shown = (options.shownFingerprints ?? nativeNoticeShownFingerprints)(options.env, options.home);
514
+ if (shown.size > 0)
515
+ commit = machineChecksToCommit(readMachineCheckResults(options.resultsFile), shown, committed);
516
+ }
517
+ const results = await run({ hqRoot, env: options.env, resultsFile: options.resultsFile, collectOnly, commitIds: new Set(commit.keys()) });
518
+ // A commit run that timed out, crashed or exited non-zero may not have
519
+ // written the script's record. It is not marked committed, so the next
520
+ // batch that collects the same finding commits it again.
521
+ for (const [id, print] of commit) {
522
+ if (results.some((each) => each.id === id && each.status !== "unknown"))
523
+ committed.set(id, print);
524
+ }
432
525
  }
433
526
  catch (error) {
434
527
  options.log("warn", `machine checks failed (${error instanceof Error ? error.name : "UnknownError"})`);
@@ -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,36 @@
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
+ /**
28
+ * The fingerprints (lowercase hex) the native SessionStart notice recorded as
29
+ * delivered, read from this environment's ledger (`HQ_HOOK_STATE_DIR`, or
30
+ * `<home>/.hq/state/hq-hook`). Read-only and without the notice's lock: a
31
+ * read that races a write can miss an entry, which only delays the commit to
32
+ * the next batch. Empty when the ledger is unusable (nativeNoticeLedgerUsable),
33
+ * missing, not a single-link regular file, or not the expected size and magic.
34
+ */
35
+ export declare function nativeNoticeShownFingerprints(env: NodeJS.ProcessEnv, home: string): Set<string>;
36
+ //# sourceMappingURL=native-notice-ledger.d.ts.map