@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
@@ -0,0 +1,156 @@
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
+ /** Ledger layout (`MAGIC`, `HEADER_BYTES`, `SLOT`, `SLOTS` in crates/hq-hook/src/session_start.rs). */
114
+ const LEDGER_MAGIC = Buffer.from("HQMCSN1\n", "latin1");
115
+ const LEDGER_HEADER_BYTES = 16;
116
+ const LEDGER_SLOT = 32;
117
+ const LEDGER_SLOTS = 256;
118
+ const LEDGER_SIZE = LEDGER_HEADER_BYTES + LEDGER_SLOT * LEDGER_SLOTS;
119
+ /**
120
+ * The fingerprints (lowercase hex) the native SessionStart notice recorded as
121
+ * delivered, read from this environment's ledger (`HQ_HOOK_STATE_DIR`, or
122
+ * `<home>/.hq/state/hq-hook`). Read-only and without the notice's lock: a
123
+ * read that races a write can miss an entry, which only delays the commit to
124
+ * the next batch. Empty when the ledger is unusable (nativeNoticeLedgerUsable),
125
+ * missing, not a single-link regular file, or not the expected size and magic.
126
+ */
127
+ export function nativeNoticeShownFingerprints(env, home) {
128
+ const shown = new Set();
129
+ if (!nativeNoticeLedgerUsable(env, home))
130
+ return shown;
131
+ const override = env.HQ_HOOK_STATE_DIR;
132
+ const folder = override ? override : `${home}/.hq/state/hq-hook`;
133
+ const file = path.posix.join(folder, NATIVE_NOTICE_LEDGER_FILE);
134
+ let bytes;
135
+ try {
136
+ const stat = fs.lstatSync(file);
137
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size !== LEDGER_SIZE)
138
+ return shown;
139
+ bytes = fs.readFileSync(file);
140
+ }
141
+ catch {
142
+ return shown;
143
+ }
144
+ if (bytes.length !== LEDGER_SIZE || !bytes.subarray(0, LEDGER_MAGIC.length).equals(LEDGER_MAGIC))
145
+ return shown;
146
+ for (let index = 0; index < LEDGER_SLOTS; index += 1) {
147
+ const start = LEDGER_HEADER_BYTES + index * LEDGER_SLOT;
148
+ const slot = bytes.subarray(start, start + LEDGER_SLOT);
149
+ // An all-zero slot is empty (the notice never records an all-zero print).
150
+ if (slot.every((byte) => byte === 0))
151
+ continue;
152
+ shown.add(slot.toString("hex"));
153
+ }
154
+ return shown;
155
+ }
156
+ //# 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 { effectiveEngineSettings, 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,7 +84,9 @@ 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) => {
89
+ const effective = effectiveEngineSettings(settings.get(vault.uid), vault.downloadStreams);
84
90
  const plan = inspectEngineHome(home, hqRoot, {
85
91
  uid: vault.uid,
86
92
  kind: vault.kind,
@@ -90,6 +96,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
90
96
  binaryPath: state.binaryPath,
91
97
  release: state.release,
92
98
  ...(vault.legacyOffSince ? { legacyOffSince: vault.legacyOffSince } : {}),
99
+ ...(effective ? { settings: effective } : {}),
93
100
  }, platform);
94
101
  const releaseHold = vault.phase === "full" ? fullModeHold(vault, state.release, platform) : undefined;
95
102
  return releaseHold ? { ...plan, blockedReason: releaseHold } : plan;
@@ -410,6 +417,7 @@ export function probeLegacyUnits(platform, home) {
410
417
  return findLegacyUnits({
411
418
  platform,
412
419
  home,
420
+ homeIsLogin: platform === "darwin" ? homeIsLoginSafe(home) : true,
413
421
  existsSync: fs.existsSync,
414
422
  listDir: (dir) => fs.readdirSync(dir),
415
423
  launchdJobLoaded: (label) => {
@@ -421,7 +429,7 @@ export function probeLegacyUnits(platform, home) {
421
429
  windowsHide: true,
422
430
  timeout: 15_000,
423
431
  });
424
- return result.status === 0;
432
+ return meshJobLoadedForHome({ status: result.status, stdout: result.stdout ?? "" }, home);
425
433
  },
426
434
  windowsTaskOwner,
427
435
  });
@@ -657,6 +665,43 @@ export function withUserRuntimeDir(env, host) {
657
665
  const dir = `/run/user/${host.uid}`;
658
666
  return host.exists(dir) ? { ...env, XDG_RUNTIME_DIR: dir } : env;
659
667
  }
668
+ export function checkMeshUnitHome(opts) {
669
+ if (opts.platform !== "darwin")
670
+ return true;
671
+ let homeIsLogin;
672
+ try {
673
+ homeIsLogin = opts.isLoginHome(opts.home);
674
+ }
675
+ catch (err) {
676
+ opts.log("warn", `could not check where the Work Mesh service was loaded from: ${err.message}`);
677
+ opts.log("warn", `HOME ${opts.home} could not be confirmed as this account's home folder; leaving the Work Mesh LaunchAgent alone`);
678
+ return false;
679
+ }
680
+ if (!homeIsLogin) {
681
+ opts.log("warn", `HOME ${opts.home} is not this account's home folder; leaving the Work Mesh LaunchAgent alone`);
682
+ return false;
683
+ }
684
+ try {
685
+ if (!opts.takesOverMesh) {
686
+ const repaired = opts.repair();
687
+ if (repaired.from)
688
+ opts.log(repaired.repaired ? "warn" : "error", repaired.message ?? `Work Mesh service loaded from ${repaired.from}`);
689
+ }
690
+ else if (typeof opts.uid === "number") {
691
+ const other = opts.remove({ home: opts.home, uid: opts.uid, run: opts.run });
692
+ if (other.removed) {
693
+ opts.log("warn", `stopped a Work Mesh service that was loaded from ${other.from}, outside this account's home folder`);
694
+ }
695
+ else if (other.from) {
696
+ 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}`);
697
+ }
698
+ }
699
+ }
700
+ catch (err) {
701
+ opts.log("error", `could not repair the Work Mesh service: ${err.message}`);
702
+ }
703
+ return true;
704
+ }
660
705
  export async function runDaemon(opts) {
661
706
  // Before anything reads the environment: hqd and every service inherit it.
662
707
  const started = daemonStartEnv(opts.env);
@@ -825,11 +870,35 @@ export async function runDaemon(opts) {
825
870
  }
826
871
  return legacyCache.units;
827
872
  };
828
- const legacyMesh = legacyMeshUnitsToRetire(legacyUnits(), {
873
+ const meshEnabled = enabledServices(machineType, initial).includes("mesh");
874
+ const launchctl = (command, args) => {
875
+ const r = spawnSync(command, args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
876
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
877
+ };
878
+ const homeIsLogin = checkMeshUnitHome({
879
+ platform,
880
+ home,
881
+ uid: process.getuid?.(),
882
+ isLoginHome: opts.isLoginHome ?? isLoginHome,
883
+ remove: opts.removeMeshUnitFromOtherHome ?? removeMeshUnitFromOtherHome,
884
+ run: launchctl,
885
+ log: (level, message) => log(level, message),
886
+ takesOverMesh: (opts.managed === true || opts.host !== undefined) && meshEnabled,
887
+ repair: () => repairMeshUnitFromOtherHome({
888
+ platform: "darwin",
889
+ home,
890
+ uid: process.getuid?.(),
891
+ env,
892
+ hqRoot: initial.hqRoot ?? (env.HQ_ROOT?.trim() || undefined),
893
+ run: launchctl,
894
+ meshOwner: () => (meshEnabled ? meshOwnerHere(home, env) : "hq-daemon-mesh-off"),
895
+ }),
896
+ });
897
+ const legacyMesh = !homeIsLogin ? [] : legacyMeshUnitsToRetire(legacyUnits(), {
829
898
  platform,
830
899
  managed: opts.managed === true,
831
900
  hosted: opts.host !== undefined,
832
- meshEnabled: enabledServices(machineType, initial).includes("mesh"),
901
+ meshEnabled,
833
902
  });
834
903
  if (legacyMesh.length > 0) {
835
904
  try {
@@ -25,6 +25,34 @@ export interface EngineUnitProblem {
25
25
  export declare function engineUnitsNeedingAttention(state: DaemonState | null, holds: PersistedHolds, now: number,
26
26
  /** False for a vault that is skipped on this machine or not on the rollout. */
27
27
  wanted?: (vaultUid: string) => boolean): EngineUnitProblem[];
28
+ export declare const WAKE_LIVE_WITHIN_MS = 60000;
29
+ export interface WakeMarker {
30
+ connected: boolean;
31
+ heartbeatAtMs: number;
32
+ }
33
+ export declare function readWakeMarker(file: string): WakeMarker | null;
34
+ export interface WakeProblem {
35
+ since: number;
36
+ what: string;
37
+ }
38
+ export interface WakeWatch {
39
+ notLiveSince: number;
40
+ checkedAt: number;
41
+ }
42
+ export declare const WAKE_WATCH_GAP_MS: number;
43
+ export declare function readWakeWatch(file: string): WakeWatch | null;
44
+ export declare function engineIsRunning(state: DaemonState | null, wanted?: (vaultUid: string) => boolean): boolean;
45
+ export interface WakeAssessment {
46
+ live: boolean;
47
+ notLiveSince?: number;
48
+ problem: WakeProblem | null;
49
+ }
50
+ export declare function assessWake(input: {
51
+ engineRunning: boolean;
52
+ marker: WakeMarker | null;
53
+ watch: WakeWatch | null;
54
+ now: number;
55
+ }): WakeAssessment;
28
56
  export interface SelfCheckRecord {
29
57
  lastSentAt: number;
30
58
  /** Sorted unit ids last reported (for the log; the rate limit ignores them). */
@@ -56,11 +84,11 @@ export declare function writeSelfCheckResult(file: string, result: SelfCheckResu
56
84
  * in the last day. Which units are affected does not matter, so units that
57
85
  * take turns failing cannot send a DM on every change.
58
86
  */
59
- export declare function shouldReport(problems: EngineUnitProblem[], last: SelfCheckRecord | null, now: number): boolean;
87
+ export declare function shouldReport(problems: EngineUnitProblem[], last: SelfCheckRecord | null, now: number, wake?: WakeProblem | null): boolean;
60
88
  /** The DM text for the owner. Plain, with the commands that fix each case. */
61
89
  export declare function selfCheckMessage(problems: EngineUnitProblem[], machine: string,
62
90
  /** A name for a vault (company slug, "personal"), when known. */
63
- vaultName?: (vaultUid: string) => string | undefined): {
91
+ vaultName?: (vaultUid: string) => string | undefined, wake?: WakeProblem | null): {
64
92
  body: string;
65
93
  details: string;
66
94
  };
@@ -87,6 +115,11 @@ export interface SelfCheckDeps {
87
115
  details: string;
88
116
  }) => Promise<string | null>;
89
117
  log: (line: string) => void;
118
+ wake?: {
119
+ markerPath: string;
120
+ watchPath: string;
121
+ meshWanted: () => boolean;
122
+ };
90
123
  }
91
124
  export type SelfCheckOutcome = "healthy" | "reported" | "already-reported" | "no-owner";
92
125
  export declare function runSelfCheck(deps: SelfCheckDeps): Promise<SelfCheckOutcome>;
@@ -76,6 +76,80 @@ function unitProblem(unit, hold, state, now) {
76
76
  what: `${unit.status === "running" ? "restarting" : "failing"} with no heartbeat since ${iso(since)}, restarted ${unit.restarts} times${exit}`,
77
77
  };
78
78
  }
79
+ export const WAKE_LIVE_WITHIN_MS = 60_000;
80
+ export function readWakeMarker(file) {
81
+ let text;
82
+ try {
83
+ text = fs.readFileSync(file, "utf8");
84
+ }
85
+ catch (error) {
86
+ if (error.code === "ENOENT")
87
+ return null;
88
+ throw error;
89
+ }
90
+ let parsed;
91
+ try {
92
+ parsed = JSON.parse(text);
93
+ }
94
+ catch (error) {
95
+ if (error instanceof SyntaxError)
96
+ return null;
97
+ throw error;
98
+ }
99
+ if (!parsed || typeof parsed !== "object")
100
+ return null;
101
+ if (typeof parsed.heartbeatAtMs !== "number" || !Number.isFinite(parsed.heartbeatAtMs))
102
+ return null;
103
+ return { connected: parsed.connected === true, heartbeatAtMs: parsed.heartbeatAtMs };
104
+ }
105
+ export const WAKE_WATCH_GAP_MS = 150 * 60_000;
106
+ export function readWakeWatch(file) {
107
+ let text;
108
+ try {
109
+ text = fs.readFileSync(file, "utf8");
110
+ }
111
+ catch (error) {
112
+ if (error.code === "ENOENT")
113
+ return null;
114
+ throw error;
115
+ }
116
+ try {
117
+ const parsed = JSON.parse(text);
118
+ const ok = (v) => typeof v === "number" && Number.isFinite(v);
119
+ return ok(parsed?.notLiveSince) && ok(parsed.checkedAt)
120
+ ? { notLiveSince: parsed.notLiveSince, checkedAt: parsed.checkedAt }
121
+ : null;
122
+ }
123
+ catch (error) {
124
+ if (error instanceof SyntaxError)
125
+ return null;
126
+ throw error;
127
+ }
128
+ }
129
+ export function engineIsRunning(state, wanted = () => true) {
130
+ return (state?.units ?? []).some((unit) => unit.id.startsWith(ENGINE_UNIT_PREFIX) &&
131
+ unit.status === "running" &&
132
+ wanted(unit.id.slice(ENGINE_UNIT_PREFIX.length)));
133
+ }
134
+ export function assessWake(input) {
135
+ const { marker, now } = input;
136
+ const fresh = marker !== null && now - marker.heartbeatAtMs <= WAKE_LIVE_WITHIN_MS;
137
+ if (!input.engineRunning || (fresh && marker.connected))
138
+ return { live: true, problem: null };
139
+ const watch = input.watch && now - input.watch.checkedAt <= WAKE_WATCH_GAP_MS ? input.watch : null;
140
+ const firstSeen = watch?.notLiveSince ?? now;
141
+ const since = firstSeen;
142
+ const what = marker === null
143
+ ? `Work Mesh has written no change-notification marker since at least ${iso(since)}`
144
+ : fresh
145
+ ? `Work Mesh has not been connected for change notifications since at least ${iso(since)}`
146
+ : `Work Mesh last updated its change-notification marker at ${iso(marker.heartbeatAtMs)}, and it was still stale at every check since ${iso(since)}`;
147
+ return {
148
+ live: false,
149
+ notLiveSince: firstSeen,
150
+ problem: now - since > ATTENTION_AFTER_MS ? { since, what } : null,
151
+ };
152
+ }
79
153
  function iso(ms) {
80
154
  return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
81
155
  }
@@ -91,6 +165,9 @@ export function readSelfCheckRecord(file) {
91
165
  }
92
166
  }
93
167
  export function writeSelfCheckRecord(file, record) {
168
+ writeSelfCheckRecordFile(file, record);
169
+ }
170
+ function writeSelfCheckRecordFile(file, record) {
94
171
  ensurePrivateDir(path.dirname(file));
95
172
  const tmp = `${file}.${process.pid}.tmp`;
96
173
  fs.writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
@@ -132,32 +209,62 @@ export function writeSelfCheckResult(file, result, options = {}) {
132
209
  * in the last day. Which units are affected does not matter, so units that
133
210
  * take turns failing cannot send a DM on every change.
134
211
  */
135
- export function shouldReport(problems, last, now) {
136
- if (problems.length === 0)
212
+ export function shouldReport(problems, last, now, wake = null) {
213
+ if (problems.length === 0 && !wake)
137
214
  return false;
138
215
  if (!last)
139
216
  return true;
217
+ if (problems.length > 0 && last.units.length === 0)
218
+ return true;
140
219
  return now - last.lastSentAt >= REPORT_INTERVAL_MS;
141
220
  }
142
221
  /** The DM text for the owner. Plain, with the commands that fix each case. */
143
222
  export function selfCheckMessage(problems, machine,
144
223
  /** A name for a vault (company slug, "personal"), when known. */
145
- vaultName = () => undefined) {
224
+ vaultName = () => undefined, wake = null) {
146
225
  const named = (p) => {
147
226
  const uid = p.unitId.slice(ENGINE_UNIT_PREFIX.length);
148
227
  const name = vaultName(uid);
149
228
  return name ? `${name} (${uid})` : uid;
150
229
  };
151
230
  const names = problems.map(named).join(", ");
152
- const body = `HQ sync on ${machine}: the sync engine for ${names} has not synced for over ${ATTENTION_AFTER_MS / 60_000} minutes. ` +
153
- "Run `hq daemon status` on that machine.";
231
+ const body = problems.length > 0
232
+ ? `HQ sync on ${machine}: the sync engine for ${names} has not synced for over ${ATTENTION_AFTER_MS / 60_000} minutes. ` +
233
+ "Run `hq daemon status` on that machine."
234
+ : `HQ sync on ${machine}: the sync engine is running without change notifications, so it only polls and other machines' changes can arrive up to 30 minutes late. ` +
235
+ "Run `hq mesh daemon status` and `hq daemon status` on that machine.";
154
236
  const lines = problems.map((p) => `- ${named(p)}: ${p.what}. Retry with: hq daemon restart ${p.unitId}`);
237
+ if (wake)
238
+ lines.push(`- change notifications: ${wake.what}. Check with: hq mesh daemon status and hq daemon status`);
155
239
  lines.push("", "Logs: hq daemon logs <unit>. This check runs in hq daemon and sends at most one DM a day from this machine.");
156
240
  return { body, details: lines.join("\n") };
157
241
  }
242
+ function checkWake(deps, state, now) {
243
+ if (!deps.wake)
244
+ return null;
245
+ try {
246
+ const assessment = assessWake({
247
+ engineRunning: deps.wake.meshWanted() && engineIsRunning(state, deps.wanted),
248
+ marker: readWakeMarker(deps.wake.markerPath),
249
+ watch: readWakeWatch(deps.wake.watchPath),
250
+ now,
251
+ });
252
+ if (assessment.live)
253
+ fs.rmSync(deps.wake.watchPath, { force: true });
254
+ else
255
+ writeSelfCheckRecordFile(deps.wake.watchPath, { notLiveSince: assessment.notLiveSince ?? now, checkedAt: now });
256
+ return assessment.problem;
257
+ }
258
+ catch (error) {
259
+ deps.log(`sync engine self-check: could not check change notifications (${error.code ?? error.message})`);
260
+ return null;
261
+ }
262
+ }
158
263
  export async function runSelfCheck(deps) {
159
264
  const now = deps.now();
160
- const problems = engineUnitsNeedingAttention(deps.readState(), deps.readHolds(), now, deps.wanted);
265
+ const state = deps.readState();
266
+ const problems = engineUnitsNeedingAttention(state, deps.readHolds(), now, deps.wanted);
267
+ const wake = checkWake(deps, state, now);
161
268
  if (deps.resultPath) {
162
269
  try {
163
270
  writeSelfCheckResult(deps.resultPath, { checkedAt: now, problems: problems.length });
@@ -166,18 +273,20 @@ export async function runSelfCheck(deps) {
166
273
  deps.log(`sync engine self-check: could not record this run's result (${error.code ?? "error"})`);
167
274
  }
168
275
  }
169
- if (problems.length === 0) {
276
+ if (problems.length === 0 && !wake) {
170
277
  deps.log("sync engine self-check: every engine unit is healthy");
171
278
  return "healthy";
172
279
  }
173
280
  for (const p of problems)
174
281
  deps.log(`sync engine self-check: ${p.unitId} ${p.what}`);
282
+ if (wake)
283
+ deps.log(`sync engine self-check: ${wake.what} while a sync engine is running`);
175
284
  const last = readSelfCheckRecord(deps.recordPath);
176
- if (!shouldReport(problems, last, now)) {
285
+ if (!shouldReport(problems, last, now, wake)) {
177
286
  deps.log(`sync engine self-check: already reported at ${iso(last.lastSentAt)}; next report after ${iso(last.lastSentAt + REPORT_INTERVAL_MS)}`);
178
287
  return "already-reported";
179
288
  }
180
- const to = await deps.sendToOwner(selfCheckMessage(problems, deps.machine, deps.vaultName));
289
+ const to = await deps.sendToOwner(selfCheckMessage(problems, deps.machine, deps.vaultName, wake));
181
290
  if (to === null) {
182
291
  deps.log("sync engine self-check: this machine is signed in as an agent, so there is no owner to DM; nothing was sent");
183
292
  return "no-owner";
@@ -41,6 +41,16 @@ export declare const EPISODE_MAX_FAILURES = 6;
41
41
  export declare const EPISODE_HEALTHY_RESET_MS: number;
42
42
  export declare const STOP_ESCALATION_MS = 10000;
43
43
  export declare const SYNC_RUNNER_PERSIST_GRACE_MS = 60000;
44
+ /**
45
+ * Longest wait for a sync-core engine's cycle to end before a parallel-download
46
+ * settings change restarts it anyway. A first-sync cycle can run about 14 minutes.
47
+ */
48
+ export declare const SYNC_CORE_SETTINGS_IDLE_MAX_MS: number;
49
+ /**
50
+ * True when two sync-core plans differ only in the parallel-download env keys,
51
+ * so the change can wait for the engine to finish its cycle.
52
+ */
53
+ export declare function onlySyncCoreSettingsChanged(before: UnitPlan, after: UnitPlan): boolean;
44
54
  export declare const CLI_UPDATE_SYNC_IDLE_KILL_GRACE_MS = 60000;
45
55
  /** After a handoff, how long a replaced unit must stay up before the next one is replaced. */
46
56
  export declare const HANDOFF_STAGGER_MS = 15000;