@indigoai-us/hq-cli 5.345.220 → 5.345.222

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/dist/command-catalog.generated.d.ts +175 -2
  3. package/dist/command-catalog.generated.js +213 -2
  4. package/dist/commands/auth.js +6 -2
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-delegate-w1b.js +9 -3
  10. package/dist/commands/core-stop-autosave.d.ts +21 -0
  11. package/dist/commands/core-stop-autosave.js +300 -0
  12. package/dist/commands/core.js +2 -0
  13. package/dist/commands/daemon.d.ts +6 -0
  14. package/dist/commands/daemon.js +46 -8
  15. package/dist/commands/doctor-usage.d.ts +5 -0
  16. package/dist/commands/doctor-usage.js +25 -0
  17. package/dist/commands/env.d.ts +49 -4
  18. package/dist/commands/env.js +355 -5
  19. package/dist/commands/lanes-shared.d.ts +3 -0
  20. package/dist/commands/lanes.d.ts +3 -0
  21. package/dist/commands/lanes.js +87 -3
  22. package/dist/commands/link.d.ts +2 -0
  23. package/dist/commands/link.js +14 -2
  24. package/dist/commands/mesh.js +23 -3
  25. package/dist/commands/sources.js +3 -3
  26. package/dist/commands/sync-core.d.ts +7 -0
  27. package/dist/commands/sync-core.js +132 -3
  28. package/dist/commands/whoami.js +96 -80
  29. package/dist/data/command-states.json +3 -0
  30. package/dist/lib/bot/config.d.ts +17 -0
  31. package/dist/lib/bot/config.js +13 -0
  32. package/dist/lib/bot/fleet-cron.js +24 -2
  33. package/dist/lib/bot/fleet-local.d.ts +30 -2
  34. package/dist/lib/bot/fleet-local.js +60 -1
  35. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  36. package/dist/lib/bot/grok-login-scope.js +93 -0
  37. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  38. package/dist/lib/bot/legacy-provider-login.js +28 -22
  39. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  40. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  41. package/dist/lib/core-utils/sentry-report.js +2 -0
  42. package/dist/lib/daemon/catalog.js +2 -0
  43. package/dist/lib/daemon/install.d.ts +2 -1
  44. package/dist/lib/daemon/install.js +9 -0
  45. package/dist/lib/daemon/legacy.d.ts +1 -0
  46. package/dist/lib/daemon/legacy.js +5 -2
  47. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  48. package/dist/lib/daemon/machine-check-owner.js +6 -1
  49. package/dist/lib/daemon/machine-checks.d.ts +29 -2
  50. package/dist/lib/daemon/machine-checks.js +64 -13
  51. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  52. package/dist/lib/daemon/mesh-owner.js +166 -0
  53. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  54. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  55. package/dist/lib/daemon/run.d.ts +15 -0
  56. package/dist/lib/daemon/run.js +137 -11
  57. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  58. package/dist/lib/daemon/selfcheck.js +118 -9
  59. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  60. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  61. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  62. package/dist/lib/daemon/stop-autosave.js +111 -0
  63. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  64. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  65. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  66. package/dist/lib/daemon/stop-job-executor.js +126 -0
  67. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  68. package/dist/lib/daemon/stop-jobs.js +599 -0
  69. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  70. package/dist/lib/doctor/checks/host-core.js +1 -1
  71. package/dist/lib/environment/access-probes.d.ts +234 -0
  72. package/dist/lib/environment/access-probes.js +918 -0
  73. package/dist/lib/environment/profile.d.ts +15 -2
  74. package/dist/lib/environment/profile.js +55 -20
  75. package/dist/lib/environment/rfc3339.d.ts +8 -0
  76. package/dist/lib/environment/rfc3339.js +26 -0
  77. package/dist/lib/environment/work-requirements.d.ts +169 -0
  78. package/dist/lib/environment/work-requirements.js +389 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +146 -7
  80. package/dist/lib/hook-engine/coverage.js +1480 -4
  81. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  82. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  83. package/dist/lib/hook-engine/native-stop-compatibility.json +362 -0
  84. package/dist/lib/hook-engine/reconcile.js +2 -2
  85. package/dist/lib/hot-channels/alert.d.ts +2 -2
  86. package/dist/lib/hot-channels/alert.js +8 -5
  87. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  88. package/dist/lib/hot-channels/signals-pass.js +296 -17
  89. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  90. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  91. package/dist/lib/install/hook-target.js +1 -1
  92. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  93. package/dist/lib/lanes/host-capacity.js +17 -2
  94. package/dist/lib/lanes/host-compute.d.ts +90 -0
  95. package/dist/lib/lanes/host-compute.js +185 -0
  96. package/dist/lib/lanes/index.d.ts +2 -0
  97. package/dist/lib/lanes/index.js +1 -0
  98. package/dist/lib/lanes/reconcile.js +22 -1
  99. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  100. package/dist/lib/lanes/resource-usage.js +589 -0
  101. package/dist/lib/lanes/run-size.d.ts +46 -0
  102. package/dist/lib/lanes/run-size.js +197 -0
  103. package/dist/lib/lanes/store.js +27 -0
  104. package/dist/lib/lanes/throttle.d.ts +36 -1
  105. package/dist/lib/lanes/throttle.js +47 -10
  106. package/dist/lib/lanes/types.d.ts +40 -0
  107. package/dist/lib/lanes/types.js +2 -2
  108. package/dist/lib/lanes/watcher.js +13 -4
  109. package/dist/lib/lanes/worker-process.d.ts +25 -2
  110. package/dist/lib/lanes/worker-process.js +71 -19
  111. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  112. package/dist/lib/mesh/live/daemon/config.js +16 -0
  113. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  114. package/dist/lib/mesh/live/daemon/install.js +142 -1
  115. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  116. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  117. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  118. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  119. package/dist/lib/placement/match.d.ts +192 -0
  120. package/dist/lib/placement/match.js +667 -0
  121. package/dist/lib/registry/registry.d.ts +35 -7
  122. package/dist/lib/registry/registry.js +88 -13
  123. package/dist/lib/safe-store.d.ts +14 -0
  124. package/dist/lib/safe-store.js +77 -4
  125. package/dist/lib/scan-packages/index.js +24 -2
  126. package/dist/lib/search-index/index.d.ts +88 -4
  127. package/dist/lib/search-index/index.js +288 -24
  128. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  129. package/dist/lib/search-index/max-doc-bytes.js +49 -23
  130. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  131. package/dist/lib/service-manager/startup-migration.js +3 -0
  132. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  133. package/dist/lib/signals/codex-lockdown.js +271 -0
  134. package/dist/lib/signals/codex-login.d.ts +37 -0
  135. package/dist/lib/signals/codex-login.js +83 -0
  136. package/dist/lib/signals/engine.d.ts +27 -0
  137. package/dist/lib/signals/engine.js +70 -0
  138. package/dist/lib/signals/reply.js +22 -1
  139. package/dist/lib/signals/run-record.js +6 -1
  140. package/dist/lib/signals/settings.d.ts +5 -0
  141. package/dist/lib/signals/settings.js +2 -0
  142. package/dist/lib/signals/steps/extract.d.ts +85 -9
  143. package/dist/lib/signals/steps/extract.js +317 -68
  144. package/dist/lib/signals/steps/types.d.ts +2 -0
  145. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  146. package/dist/lib/sync-core/engine-holds.js +60 -0
  147. package/dist/lib/sync-core/engine-home.d.ts +37 -1
  148. package/dist/lib/sync-core/engine-home.js +119 -16
  149. package/dist/lib/sync-core/reconcile.js +8 -0
  150. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  151. package/dist/lib/sync-core/rollout-state.js +5 -2
  152. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  153. package/dist/lib/sync-core/vault-settings.js +131 -0
  154. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  155. package/dist/lib/sync-core/vault-uid.js +4 -0
  156. package/dist/lib/windows/install-followup.d.ts +2 -0
  157. package/dist/lib/windows/install-followup.js +4 -1
  158. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  159. package/dist/utils/auth-session-check.d.ts +16 -0
  160. package/dist/utils/auth-session-check.js +16 -0
  161. package/dist/utils/client-health-contract.d.ts +6 -0
  162. package/dist/utils/client-health-contract.js +13 -0
  163. package/dist/utils/client-health.d.ts +7 -0
  164. package/dist/utils/client-health.js +22 -1
  165. package/dist/utils/command-usage.d.ts +40 -0
  166. package/dist/utils/command-usage.js +61 -0
  167. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  168. package/dist/utils/duplicate-command-usage.js +125 -0
  169. package/dist/utils/host-registration.js +5 -2
  170. package/dist/utils/pack-contributions.d.ts +3 -0
  171. package/dist/utils/pack-contributions.js +110 -23
  172. package/dist/utils/resident-package-preload.js +4 -0
  173. package/dist/utils/self-update.d.ts +3 -1
  174. package/dist/utils/self-update.js +56 -11
  175. package/dist/utils/sentry-fingerprint.js +9 -0
  176. package/dist/utils/update-lock.d.ts +151 -14
  177. package/dist/utils/update-lock.js +782 -46
  178. package/dist/utils/version-gate.js +12 -2
  179. package/dist/utils/windows-bash.d.ts +2 -0
  180. package/dist/utils/windows-bash.js +2 -1
  181. package/package.json +9 -8
  182. package/scripts/bench-core-compare.mjs +313 -0
  183. package/scripts/bench-core.mjs +399 -12
  184. package/scripts/check-function-manifest.mjs +116 -3
@@ -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";
@@ -68,6 +72,9 @@ import { userToolDirs } from "./tools.js";
68
72
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
69
73
  import { createTccEpermGuard, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
70
74
  import { daemonRunGuard } from "./lanes-reconcile-guard.js";
75
+ import { startStopJobDrainer } from "./stop-jobs.js";
76
+ import { executeStopJob, pruneStopJobResults, stopJobCompleted } from "./stop-job-executor.js";
77
+ import { closeStopDiagnosticCursor, drainStopDiagnostics } from "./stop-diagnostics.js";
71
78
  export const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
72
79
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
73
80
  export const RESTART_EXIT_CODE = 75;
@@ -77,6 +84,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
77
84
  const state = readSyncCoreRolloutState(home);
78
85
  if (!state)
79
86
  return [];
87
+ const settings = readSyncCoreVaultSettings(home);
80
88
  return state.vaults.map((vault) => {
81
89
  const plan = inspectEngineHome(home, hqRoot, {
82
90
  uid: vault.uid,
@@ -87,6 +95,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
87
95
  binaryPath: state.binaryPath,
88
96
  release: state.release,
89
97
  ...(vault.legacyOffSince ? { legacyOffSince: vault.legacyOffSince } : {}),
98
+ ...(settings.has(vault.uid) ? { settings: settings.get(vault.uid) } : {}),
90
99
  }, platform);
91
100
  const releaseHold = vault.phase === "full" ? fullModeHold(vault, state.release, platform) : undefined;
92
101
  return releaseHold ? { ...plan, blockedReason: releaseHold } : plan;
@@ -407,6 +416,7 @@ export function probeLegacyUnits(platform, home) {
407
416
  return findLegacyUnits({
408
417
  platform,
409
418
  home,
419
+ homeIsLogin: platform === "darwin" ? homeIsLoginSafe(home) : true,
410
420
  existsSync: fs.existsSync,
411
421
  listDir: (dir) => fs.readdirSync(dir),
412
422
  launchdJobLoaded: (label) => {
@@ -418,7 +428,7 @@ export function probeLegacyUnits(platform, home) {
418
428
  windowsHide: true,
419
429
  timeout: 15_000,
420
430
  });
421
- return result.status === 0;
431
+ return meshJobLoadedForHome({ status: result.status, stdout: result.stdout ?? "" }, home);
422
432
  },
423
433
  windowsTaskOwner,
424
434
  });
@@ -654,6 +664,43 @@ export function withUserRuntimeDir(env, host) {
654
664
  const dir = `/run/user/${host.uid}`;
655
665
  return host.exists(dir) ? { ...env, XDG_RUNTIME_DIR: dir } : env;
656
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
+ }
657
704
  export async function runDaemon(opts) {
658
705
  // Before anything reads the environment: hqd and every service inherit it.
659
706
  const started = daemonStartEnv(opts.env);
@@ -822,11 +869,35 @@ export async function runDaemon(opts) {
822
869
  }
823
870
  return legacyCache.units;
824
871
  };
825
- 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(), {
826
897
  platform,
827
898
  managed: opts.managed === true,
828
899
  hosted: opts.host !== undefined,
829
- meshEnabled: enabledServices(machineType, initial).includes("mesh"),
900
+ meshEnabled,
830
901
  });
831
902
  if (legacyMesh.length > 0) {
832
903
  try {
@@ -977,7 +1048,53 @@ export async function runDaemon(opts) {
977
1048
  laneReconcileHandlerLoadInFlight = false;
978
1049
  });
979
1050
  };
1051
+ const stopJobAbort = new AbortController();
1052
+ const ownsStopQueue = () => path.resolve(paths.root) === path.resolve(home, ".hq/daemon")
1053
+ && readPidLock(paths.lockPath)?.pid === process.pid;
1054
+ let stopDiagnosticsRunning = false;
1055
+ let stopDiagnosticRoot;
1056
+ const stopDiagnosticTimer = setInterval(() => {
1057
+ const root = readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT;
1058
+ if (stopDiagnosticRoot && (root !== stopDiagnosticRoot || !ownsStopQueue())) {
1059
+ closeStopDiagnosticCursor(stopDiagnosticRoot);
1060
+ stopDiagnosticRoot = undefined;
1061
+ }
1062
+ if (!root || stopDiagnosticsRunning || !ownsStopQueue())
1063
+ return;
1064
+ stopDiagnosticRoot = root;
1065
+ stopDiagnosticsRunning = true;
1066
+ void drainStopDiagnostics({ root, ownsQueue: ownsStopQueue, log: message => log("warn", message) })
1067
+ .catch(error => log("warn", `Stop diagnostic drain failed: ${String(error)}`))
1068
+ .finally(() => { stopDiagnosticsRunning = false; });
1069
+ }, 5000);
1070
+ stopDiagnosticTimer.unref();
1071
+ const stopJobDrainer = startStopJobDrainer({
1072
+ home,
1073
+ ownsQueue: ownsStopQueue,
1074
+ completed: job => {
1075
+ const root = readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT;
1076
+ return root !== undefined && stopJobCompleted(job, root);
1077
+ },
1078
+ pruneResults: olderThan => {
1079
+ const root = readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT;
1080
+ if (root)
1081
+ pruneStopJobResults(root, olderThan);
1082
+ },
1083
+ execute: job => executeStopJob(job, {
1084
+ nodeBinary: opts.nodeBinary,
1085
+ hqBinary: opts.hqBinary,
1086
+ allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1087
+ signal: stopJobAbort.signal,
1088
+ }),
1089
+ log: message => log("warn", message),
1090
+ });
1091
+ /** Closes the watchers; the promise settles once the Stop job in progress (if any) has written its receipt. */
980
1092
  const closeRuntimeWatchers = () => {
1093
+ if (stopDiagnosticRoot)
1094
+ closeStopDiagnosticCursor(stopDiagnosticRoot);
1095
+ clearInterval(stopDiagnosticTimer);
1096
+ stopJobAbort.abort();
1097
+ const stopJobsClosed = stopJobDrainer.close().catch((err) => log("warn", `Stop job drainer did not close cleanly: ${String(err)}`));
981
1098
  laneReconcileWatcher?.close();
982
1099
  laneReconcileWatcher = null;
983
1100
  laneReconcileWatcherRoot = null;
@@ -985,6 +1102,7 @@ export async function runDaemon(opts) {
985
1102
  machineChecks.close();
986
1103
  flagSnapshots.close();
987
1104
  stateWriter.close();
1105
+ return stopJobsClosed;
988
1106
  };
989
1107
  const plan = () => {
990
1108
  const config = readDaemonConfig(paths.configPath);
@@ -1554,14 +1672,15 @@ export async function runDaemon(opts) {
1554
1672
  tccEpermGuard.dispose();
1555
1673
  log("info", `${why}; stopping services`);
1556
1674
  closeHqd();
1557
- closeRuntimeWatchers();
1675
+ // The aborted Stop job's receipt is written before the lease is released.
1676
+ const stopJobsClosed = closeRuntimeWatchers();
1558
1677
  // Keep shutdown bounded, but let a stopping sync runner reach its persist deadline.
1559
1678
  const cap = createShutdownCap();
1560
1679
  extendSyncShutdownCap = cap.extendForSyncRunnerPersist;
1561
1680
  if (supervisor.hasStoppingSyncRunner())
1562
1681
  cap.extendForSyncRunnerPersist();
1563
1682
  const servicesStopped = supervisor.stop();
1564
- void Promise.race([servicesStopped, cap.promise]).then((result) => {
1683
+ void Promise.race([Promise.all([servicesStopped, stopJobsClosed]).then(([result]) => result), cap.promise]).then((result) => {
1565
1684
  cap.clear();
1566
1685
  extendSyncShutdownCap = undefined;
1567
1686
  if (result === "timeout")
@@ -1584,7 +1703,7 @@ export async function runDaemon(opts) {
1584
1703
  daemonStopping = true;
1585
1704
  tccEpermGuard.dispose();
1586
1705
  closeHqd();
1587
- closeRuntimeWatchers();
1706
+ const stopJobsClosed = closeRuntimeWatchers();
1588
1707
  const released = supervisor.release();
1589
1708
  // What these readers have not read stays in the FIFO for the next daemon.
1590
1709
  for (const tail of protocolTails)
@@ -1616,10 +1735,17 @@ export async function runDaemon(opts) {
1616
1735
  // The released processes must not keep this one alive.
1617
1736
  for (const child of spawned)
1618
1737
  child.unref();
1619
- releaseDaemonLock(paths.lockPath);
1620
- resolve(RESTART_EXIT_CODE);
1621
- // Anything else still holding the event loop open must not delay the restart.
1622
- setTimeout(() => process.exit(RESTART_EXIT_CODE), 5_000).unref();
1738
+ // The aborted Stop job's receipt is written before the lease is released
1739
+ // (bounded: the job's child is already signalled).
1740
+ let handOverTimer;
1741
+ void Promise.race([stopJobsClosed, new Promise((done) => { handOverTimer = setTimeout(done, 3_000); handOverTimer.unref(); })]).then(() => {
1742
+ if (handOverTimer)
1743
+ clearTimeout(handOverTimer);
1744
+ releaseDaemonLock(paths.lockPath);
1745
+ resolve(RESTART_EXIT_CODE);
1746
+ // Anything else still holding the event loop open must not delay the restart.
1747
+ setTimeout(() => process.exit(RESTART_EXIT_CODE), 5_000).unref();
1748
+ });
1623
1749
  };
1624
1750
  restartDaemon = () => {
1625
1751
  if (!restartsForParent(opts)) {
@@ -1654,7 +1780,7 @@ export async function runDaemon(opts) {
1654
1780
  catch (err) {
1655
1781
  log("error", `supervisor failed to start: ${err.message}`);
1656
1782
  closeHqd();
1657
- closeRuntimeWatchers();
1783
+ void closeRuntimeWatchers();
1658
1784
  releaseDaemonLock(paths.lockPath);
1659
1785
  resolve(1);
1660
1786
  }
@@ -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";
@@ -0,0 +1,19 @@
1
+ /** Why the folder that holds lock `directory` cannot hold it, or undefined.
2
+ * The folder is resolved first (macOS /tmp is a link to /private/tmp) and must
3
+ * be owned by this user or root and closed to group and other writes, unless
4
+ * it is a root-owned sticky folder such as /tmp: there another user cannot
5
+ * remove or rename this user's lock, and the lock folder itself is checked as
6
+ * a private store before it is used. A store check of the parent itself would
7
+ * refuse /tmp (owned by root, world-writable), which made autosave skip every
8
+ * file on Linux without TMPDIR.
9
+ */
10
+ export declare function lockParentRefusal(directory: string): string | undefined;
11
+ /** Recover only an old, private autosave lock whose owner is definitely gone.
12
+ * Live or unreadable process identity stays held. The renamed directory is
13
+ * checked against the original inode before anything inside it is removed.
14
+ */
15
+ export declare function acquireAutosaveLock(directory: string, now: number, staleMinutes: number, alive?: (pid: number) => boolean | undefined, birth?: (pid: number) => string | undefined): {
16
+ recovered: boolean;
17
+ release(): void;
18
+ } | undefined;
19
+ //# sourceMappingURL=stop-autosave-lock.d.ts.map