@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
@@ -48,6 +48,7 @@ import * as hookEngineResolve from '../lib/hook-engine/resolve.js';
48
48
  import { launcherRoot, quotePosix, quoteWindows } from '../lib/hook-engine/registration.js';
49
49
  import { openStoreDir } from '../lib/safe-store.js';
50
50
  import { SKIP_CANARY_GATE_ENV, checkHostCanary } from '../lib/hook-engine/canary-gate.js';
51
+ import { resolvedUnder } from '../lib/hook-engine/coverage.js';
51
52
  export { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
52
53
  import { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
53
54
  export { coreNextKillReason, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE } from './core-next-kill.js';
@@ -67,7 +68,9 @@ export function targetForEvent(target, event) {
67
68
  * the old registration.
68
69
  */
69
70
  export const REQUIRED_EVALUATORS = {
70
- PreToolUse: ['credential-files', 'company-scope', 'path-search-rules', 'command-rules', 'policy-injection'],
71
+ // Merge-state has no production writer yet. Require its readiness separately
72
+ // so command-rules alone cannot remove the existing merge gate dispatcher.
73
+ PreToolUse: ['credential-files', 'company-scope', 'path-search-rules', 'command-rules', 'merge-gates-ready', 'live-command-flags-ready', 'git-identity-authority-ready', 'policy-injection'],
71
74
  PostToolUse: ['policy-injection'],
72
75
  UserPromptSubmit: ['policy-injection'],
73
76
  SessionStart: ['policy-injection'],
@@ -316,7 +319,7 @@ export function coreNextTarget(home, env = process.env, options = {}) {
316
319
  const events = capableEvents(caps);
317
320
  if (!events.length)
318
321
  return null;
319
- return { coreNext: stable, events, covers: caps.covers ?? {}, canary: hostCanaryGate(home, env, caps.version, platform, options.warn) };
322
+ return resolvedUnder({ coreNext: stable, events, covers: caps.covers ?? {}, canary: hostCanaryGate(home, env, caps.version, platform, options.warn) }, env);
320
323
  }
321
324
  const warned = new Set();
322
325
  function warnOnce(message, warn) {
@@ -115,6 +115,9 @@ export interface UnwireResult {
115
115
  * (status `live` or `broken`). Foreign links and real files are left in place
116
116
  * -- same collision philosophy as scan-packages.sh. This is what prevents an
117
117
  * uninstall from leaving dangling symlinks behind.
118
+ *
119
+ * Also removes the namespaced skill host (`<pack>:<item>`) reindex writes
120
+ * next to the unprefixed table dest.
118
121
  */
119
122
  export declare function unwirePack(hqRoot: string, packDir: string, contributes: Partial<Record<PackContributeKey, string[]>>): UnwireResult;
120
123
  /** The result of {@link unwirePackMcp}: the per-server un-registration outcomes (empty when no `mcp` keys). */
@@ -226,38 +226,125 @@ export function findDependentPacks(installed, name) {
226
226
  return installed.filter((p) => p.name !== name &&
227
227
  (p.manifest?.requires?.packs ?? []).some((d) => d.name === name));
228
228
  }
229
+ function unlinkContribution(result, link, packDir) {
230
+ const status = linkStatus(link, packDir);
231
+ if (status === 'live' || status === 'broken') {
232
+ try {
233
+ fs.unlinkSync(link.dst);
234
+ result.unlinked.push({ key: link.key, item: link.item, dst: link.dst });
235
+ }
236
+ catch {
237
+ result.skipped.push({
238
+ key: link.key,
239
+ item: link.item,
240
+ dst: link.dst,
241
+ reason: 'foreign',
242
+ });
243
+ }
244
+ return;
245
+ }
246
+ result.skipped.push({
247
+ key: link.key,
248
+ item: link.item,
249
+ dst: link.dst,
250
+ reason: status === 'missing' ? 'missing' : 'foreign',
251
+ });
252
+ }
253
+ /**
254
+ * Reindex surfaces pack skills as `.claude/skills/<pack>:<item>` (symlink or
255
+ * a directory wrapper). Uninstall's table dest is the unprefixed name, so
256
+ * those wrappers would otherwise stay behind as empty dirs.
257
+ */
258
+ function unwireNamespacedSkillHost(dst, packDir, item, result) {
259
+ let st;
260
+ try {
261
+ st = fs.lstatSync(dst);
262
+ }
263
+ catch {
264
+ return;
265
+ }
266
+ const declared = {
267
+ key: 'skills',
268
+ item,
269
+ src: path.join(packDir, 'skills', item),
270
+ dst,
271
+ };
272
+ if (st.isSymbolicLink()) {
273
+ const status = linkStatus(declared, packDir);
274
+ if (status !== 'live' && status !== 'broken')
275
+ return;
276
+ try {
277
+ fs.unlinkSync(dst);
278
+ result.unlinked.push({ key: 'skills', item, dst });
279
+ }
280
+ catch {
281
+ result.skipped.push({ key: 'skills', item, dst, reason: 'foreign' });
282
+ }
283
+ return;
284
+ }
285
+ if (!st.isDirectory())
286
+ return;
287
+ let names;
288
+ try {
289
+ names = fs.readdirSync(dst);
290
+ }
291
+ catch {
292
+ return;
293
+ }
294
+ for (const name of names) {
295
+ const child = path.join(dst, name);
296
+ let childSt;
297
+ try {
298
+ childSt = fs.lstatSync(child);
299
+ }
300
+ catch {
301
+ return;
302
+ }
303
+ if (!childSt.isSymbolicLink())
304
+ return;
305
+ let resolved;
306
+ try {
307
+ resolved = path.resolve(dst, fs.readlinkSync(child));
308
+ }
309
+ catch {
310
+ return;
311
+ }
312
+ if (!targetUnderPackDir(packDir, resolved))
313
+ return;
314
+ try {
315
+ fs.unlinkSync(child);
316
+ }
317
+ catch {
318
+ return;
319
+ }
320
+ }
321
+ try {
322
+ fs.rmdirSync(dst);
323
+ result.unlinked.push({ key: 'skills', item, dst });
324
+ }
325
+ catch {
326
+ /* still occupied */
327
+ }
328
+ }
229
329
  /**
230
330
  * Remove only the host symlinks that resolve into THIS pack's directory
231
331
  * (status `live` or `broken`). Foreign links and real files are left in place
232
332
  * -- same collision philosophy as scan-packages.sh. This is what prevents an
233
333
  * uninstall from leaving dangling symlinks behind.
334
+ *
335
+ * Also removes the namespaced skill host (`<pack>:<item>`) reindex writes
336
+ * next to the unprefixed table dest.
234
337
  */
235
338
  export function unwirePack(hqRoot, packDir, contributes) {
236
339
  const result = { unlinked: [], skipped: [] };
237
340
  for (const link of contributionLinks(hqRoot, packDir, contributes)) {
238
- const status = linkStatus(link, packDir);
239
- if (status === 'live' || status === 'broken') {
240
- try {
241
- fs.unlinkSync(link.dst);
242
- result.unlinked.push({ key: link.key, item: link.item, dst: link.dst });
243
- }
244
- catch {
245
- result.skipped.push({
246
- key: link.key,
247
- item: link.item,
248
- dst: link.dst,
249
- reason: 'foreign',
250
- });
251
- }
252
- }
253
- else {
254
- result.skipped.push({
255
- key: link.key,
256
- item: link.item,
257
- dst: link.dst,
258
- reason: status === 'missing' ? 'missing' : 'foreign',
259
- });
260
- }
341
+ unlinkContribution(result, link, packDir);
342
+ }
343
+ const packName = path.basename(packDir);
344
+ for (const item of contributes.skills ?? []) {
345
+ if (typeof item !== 'string' || item.length === 0)
346
+ continue;
347
+ unwireNamespacedSkillHost(path.join(hqRoot, '.claude', 'skills', `${packName}:${item}`), packDir, item, result);
261
348
  }
262
349
  return result;
263
350
  }
@@ -81,6 +81,7 @@ export const RESIDENT_PACKAGE_MODULES = {
81
81
  "../lib/hot-channels/adapters/index.js",
82
82
  "../lib/capacity/collect.js",
83
83
  "../lib/capacity/accounts.js",
84
+ "../lib/core-utils/hook-timeout-debug-context-flag.js",
84
85
  ],
85
86
  "daemon-logs-follow": [],
86
87
  "mesh-daemon": ["../sentry.js", "../lib/doctor/client-health-reason-codes-flag.js", "@indigoai-us/hq-flags-client", "../lib/plan-limit-nag.js", "../utils/plan-gate-error.js", "../utils/deleted-company-notice.js", "open", "../utils/cognito-session.js", "../lib/first-sync-next-step.js", "@indigoai-us/hq-cloud"],
@@ -290,6 +291,9 @@ const LOADERS = {
290
291
  // before it refuses on a stale one.
291
292
  () => import("../lib/capacity/collect.js"),
292
293
  () => import("../lib/capacity/accounts.js"),
294
+ // Native Stop timeout diagnostics report through sentry-report, whose
295
+ // hook-timeout debug-context gate loads this flag module on demand.
296
+ () => import("../lib/core-utils/hook-timeout-debug-context-flag.js"),
293
297
  ],
294
298
  "daemon-logs-follow": [],
295
299
  "mesh-daemon": [
@@ -132,7 +132,9 @@ export declare function runUpdateQuiet(cmd: string, args: string[], env?: NodeJS
132
132
  * the hq-sync Rust app), so every updater on the machine contends on ONE lock
133
133
  * instead of each tool keeping its own.
134
134
  */
135
- export declare function acquireUpdateLock(now?: number): (() => void) | null;
135
+ export declare function acquireUpdateLock(now?: number): ((() => void) & {
136
+ stillHeld?: () => boolean;
137
+ }) | null;
136
138
  /** Injectable surface so the flow is unit-testable without network or spawns. */
137
139
  export interface SelfUpdateDeps {
138
140
  env?: NodeJS.ProcessEnv;
@@ -68,11 +68,13 @@ import { CLI_NAME, CLI_VERSION } from "../cli-version.js";
68
68
  import { buildBunInstallArgv, buildPnpmInstallArgv, buildPrefixedInstallArgv, buildSpawnPlan, canWriteNpmInstall, captureNonWritableNpmPrefixNotice, claimNonWritableNpmPrefixNotice, checkUpdateConvergence, derivePnpmHome, detachUpdateSupervisor, isBunManagedPackageDir, isLocalDependencyInstall, isPnpmManagedPackageDir, normalizeRunningInstall, nonWritablePrefixNote, openInstallOutput, resolvePnpmPathInstall, pnpmUpdateEnv, pnpmInstalledVersion, performPnpmUpdate, resolveRunningInstall, runUpdateCommand, runSupervisedUpdateCommand, UPDATE_RECURSION_GUARD_ENV, } from "./version-gate.js";
69
69
  import { canStageInstall, stagedNpmInstall } from "./staged-install.js";
70
70
  import { npmGlobalInstallArgv } from "./npm-install-flags.js";
71
- import { acquireUpdateLock as acquireSharedUpdateLock } from "./update-lock.js";
71
+ import { acquireUpdateLock as acquireSharedUpdateLock, STARTUP_TAKEOVER_WAIT_MS, } from "./update-lock.js";
72
72
  import { markLatestIneffective } from "./version-check.js";
73
73
  import { fileSelfUpdateBackoff } from "./self-update-backoff.js";
74
74
  import { removeHqCliPs1Shims } from "../lib/windows/ps1-shims.js";
75
75
  import { restartDaemonServiceIfInstalled } from "../lib/mesh/live/daemon/install.js";
76
+ import { meshOwnerHere, repairHqDaemonUnitFromOtherHome } from "../lib/daemon/mesh-owner.js";
77
+ import { homedir } from "node:os";
76
78
  import { createCurrentPackageUseLeaseHandoff, PACKAGE_USE_LEASE_HANDOFF_ENV, releaseCurrentPackageUseLease, } from "./package-use-lease.js";
77
79
  /**
78
80
  * Set on the re-exec'd child so it can never self-update (and re-exec) again.
@@ -732,8 +734,13 @@ export function runUpdateQuiet(cmd, args, env, cwd) {
732
734
  * instead of each tool keeping its own.
733
735
  */
734
736
  export function acquireUpdateLock(now = Date.now()) {
735
- const handle = acquireSharedUpdateLock({ now, tool: "hq-cli-self-update" });
736
- return handle ? handle.release : null;
737
+ // Runs before the user's command, so it waits only briefly for the mutex.
738
+ const handle = acquireSharedUpdateLock({
739
+ now,
740
+ tool: "hq-cli-self-update",
741
+ takeoverWaitMs: STARTUP_TAKEOVER_WAIT_MS,
742
+ });
743
+ return handle ? Object.assign(() => handle.release(), { stillHeld: handle.stillHeld }) : null;
737
744
  }
738
745
  /**
739
746
  * Re-run `hq <argv…>` from PATH so the freshly-installed version handles the
@@ -866,10 +873,15 @@ async function updateAndReexec(argv, flavor, known, deps) {
866
873
  return { action: "skipped" };
867
874
  }
868
875
  let outcome;
876
+ const heldLock = {};
869
877
  try {
870
- outcome = await attemptUpdateAndReexec(argv, flavor, known, deps, env);
878
+ outcome = await attemptUpdateAndReexec(argv, flavor, known, deps, env, heldLock);
871
879
  }
872
880
  catch (error) {
881
+ // A throw between taking the lock and the install's own finally must not
882
+ // leave the lock held: its heartbeat would keep it fresh for as long as
883
+ // this process lives (the daemon runs for days).
884
+ heldLock.release?.();
873
885
  if (known)
874
886
  backoff.record(known);
875
887
  else
@@ -887,7 +899,17 @@ async function updateAndReexec(argv, flavor, known, deps) {
887
899
  }
888
900
  return outcome;
889
901
  }
890
- async function attemptUpdateAndReexec(argv, flavor, known, deps, env) {
902
+ /** Release at most once, keeping `stillHeld`. */
903
+ function releaseOnce(release) {
904
+ let done = false;
905
+ return Object.assign(() => {
906
+ if (done)
907
+ return;
908
+ done = true;
909
+ release();
910
+ }, release.stillHeld ? { stillHeld: release.stillHeld } : {});
911
+ }
912
+ async function attemptUpdateAndReexec(argv, flavor, known, deps, env, heldLock = {}) {
891
913
  const latest = known ?? (await (deps.fetchLatest ?? fetchLatestVersion)());
892
914
  if (!latest)
893
915
  return { action: "skipped" };
@@ -941,9 +963,11 @@ async function attemptUpdateAndReexec(argv, flavor, known, deps, env) {
941
963
  }
942
964
  install = pathTarget.install;
943
965
  }
944
- const releaseLock = flavor.lock ? (deps.acquireLock ?? acquireUpdateLock)() : () => { };
945
- if (!releaseLock)
966
+ const acquired = flavor.lock ? (deps.acquireLock ?? acquireUpdateLock)() : () => { };
967
+ if (!acquired)
946
968
  return { action: "skipped", latest };
969
+ const releaseLock = releaseOnce(acquired);
970
+ heldLock.release = releaseLock;
947
971
  if (install.manager === "npm" &&
948
972
  install.prefix &&
949
973
  install.packageRoot &&
@@ -965,6 +989,13 @@ async function attemptUpdateAndReexec(argv, flavor, known, deps, env) {
965
989
  return { action: "update-failed", latest };
966
990
  }
967
991
  const staged = canStageInstall(install) && (await readStagedSelfUpdateFlag(deps, env));
992
+ // A racing taker may have moved our lock since acquisition: another
993
+ // installer may be running, so skip before touching the install.
994
+ const lockCheck = releaseLock;
995
+ if (typeof lockCheck.stillHeld === "function" && !lockCheck.stillHeld()) {
996
+ releaseLock();
997
+ return { action: "skipped", latest };
998
+ }
968
999
  const renamePath = deps.renamePath ?? fs.renameSync;
969
1000
  // The staged install keeps the running package in place until the swap and
970
1001
  // restores it itself, so it takes no snapshot.
@@ -1162,10 +1193,24 @@ async function attemptUpdateAndReexec(argv, flavor, known, deps, env) {
1162
1193
  // A resident mesh daemon keeps the old JS loaded after a global install.
1163
1194
  // Service restart is best-effort and cannot turn a successful update red.
1164
1195
  try {
1165
- const restart = (deps.restartDaemon ?? (() => restartDaemonServiceIfInstalled({
1166
- env,
1167
- hqRoot: env.HQ_ROOT,
1168
- })))();
1196
+ const restart = (deps.restartDaemon ?? (() => {
1197
+ const uid = process.getuid?.();
1198
+ if (process.platform === "darwin" && typeof uid === "number") {
1199
+ try {
1200
+ const daemon = repairHqDaemonUnitFromOtherHome({ home: homedir(), uid, env });
1201
+ if (daemon.message)
1202
+ console.error(chalk.yellow(` ${daemon.message}`));
1203
+ }
1204
+ catch (error) {
1205
+ console.error(chalk.yellow(` Could not check the hq daemon service: ${error instanceof Error ? error.message : String(error)}`));
1206
+ }
1207
+ }
1208
+ return restartDaemonServiceIfInstalled({
1209
+ env,
1210
+ hqRoot: env.HQ_ROOT,
1211
+ meshOwner: () => meshOwnerHere(homedir(), env),
1212
+ });
1213
+ }))();
1169
1214
  if (restart?.message)
1170
1215
  console.error(chalk.yellow(` ${restart.message}`));
1171
1216
  }
@@ -151,6 +151,15 @@ const KNOWN_ERROR_NAMES = new Set([
151
151
  "QmdStoreUnopenableError",
152
152
  "QmdQueryDocumentError",
153
153
  "QmdModelDownloadError",
154
+ // A damaged SQLite index file. Still captured, so it groups on its own key
155
+ // (HQ-CLI-EJ).
156
+ "QmdStoreCorruptError",
157
+ // Thrown marked expected (the boundary prints the remedy and skips capture),
158
+ // or handled inside reconciliation. Allow-listed defensively, like
159
+ // QmdWorkdirMissingError below (HQ-CLI-EJ, HQ-CLI-GJ).
160
+ "QmdAccessDeniedError",
161
+ "QmdConfigUnwritableError",
162
+ "QmdCollectionPathTakenError",
154
163
  // Shares the `Qmd` prefix the qmd branch keys on. The boundary now SUPPRESSES
155
164
  // capture for this class, so it should never reach a capture route — allow-
156
165
  // listed defensively so a future capture path cannot mint an unbounded group
@@ -18,21 +18,59 @@
18
18
  * CLI updates. Do not change either without a coordinated hq-sync release.
19
19
  *
20
20
  * Path: $HOME/.hq/locks/cli-update.lock
21
- * Content: JSON object with exactly these fields:
21
+ * Content: JSON object with these fields:
22
22
  * {
23
23
  * "pid": <number> — owning process id,
24
- * "startedAt": <string> — ISO-8601 acquisition timestamp,
24
+ * "startedAt": <string> — ISO-8601 time of acquisition or of the
25
+ * holder's latest heartbeat,
25
26
  * "tool": <string> — which actor holds it (e.g. "hq-cli-version-gate"),
26
- * "version": <string> — the holder's own version
27
+ * "version": <string> — the holder's own version,
28
+ * "nonce": <string> — OPTIONAL, identifies one acquisition (the
29
+ * desktop app writes one too; readers that do
30
+ * not know it ignore it)
27
31
  * }
28
- * Staleness: a holder is stale when `startedAt` is older than 10 minutes OR
29
- * its `pid` is no longer alive (`kill(pid, 0)` → ESRCH). A stale lock may be
30
- * removed and re-acquired; a fresh one means "someone else is installing the
31
- * very version you want — skip".
32
+ * Staleness (same rules as hq-desktop-app's `stored_lock_is_stale`): a
33
+ * holder is stale when `startedAt` is at least 10 minutes old, or at least
34
+ * 10 minutes in the future (a skewed clock cannot pin the lock), OR its `pid`
35
+ * is no longer alive (`kill(pid, 0)` → ESRCH; Node maps the Windows
36
+ * `OpenProcess` probe the same way, and access denied counts as alive). A
37
+ * legacy lock with `startedAt` but no `pid` retires by age only. A stale
38
+ * lock may be removed and re-acquired; a fresh one means "someone else is
39
+ * installing the very version you want — skip".
40
+ * Heartbeat: while held, the holder rewrites `startedAt` every 60 seconds
41
+ * inside the takeover mutex (both sides), so an install that legitimately
42
+ * runs past 10 minutes is never judged stale. The 10-minute TTL is kept
43
+ * because it bounds how long a crashed holder blocks updates; the heartbeat
44
+ * is what keeps a long hold safe.
32
45
  * ────────────────────────────────────────────────────────────────────────────
33
46
  *
34
- * Mechanics: acquisition is a single atomic `open(…, 'wx')` (O_CREAT|O_EXCL) —
35
- * no mkdir dance, no read-then-write window. Unparseable lock content is
47
+ * Mechanics: the body is written to a temp file and hard-linked to the lock
48
+ * name (an atomic create-new), so the lock is never visible empty; 'wx' is
49
+ * the fallback where hard links are unavailable. A stale lock is renamed
50
+ * aside and deleted only if it still matches what was judged stale; release
51
+ * deletes only a file still holding this process's exact body. An
52
+ * unparseable lock younger than 30 seconds is left alone (mid-write).
53
+ * Publish, takeover and release run inside the `cli-update.lock.takeover` mkdir
54
+ * mutex shared with hq-desktop-app. Release leaves the lock in place when the
55
+ * mutex stays busy; the lock is reclaimed once its holder exits or the TTL
56
+ * passes, and rechecks the lock's content after taking the mutex, because a
57
+ * takeover can finish between the first check and the mutex. The directory is
58
+ * never moved. Each holder keeps a uniquely named file inside it, with the time
59
+ * it was taken in the name, and a crashed holder's mutex is taken by renaming
60
+ * that file to a new name: a rename either moves the file it judged stale or
61
+ * fails, so a judgment made earlier cannot touch a newer holder's mutex, and of
62
+ * several stealers exactly one wins. An acquirer holds the mutex only if its
63
+ * file is alone in the directory after it was written, so two processes that
64
+ * land in one directory cannot both proceed. A holder confirms its file is still
65
+ * there right before it moves the lock. Gaps that remain: a holder paused past
66
+ * the mutex TTL, or whose clock jumped forward past that TTL or back more than a
67
+ * day, can lose the mutex, and a theft in the moment between that check and the
68
+ * move goes unseen; mixed versions (an older CLI or desktop app without the
69
+ * mutex) can still race until both update. `stillHeld()` and the no-replace
70
+ * publish are the defenses there. A
71
+ * restore that cannot use a hard link leaves the moved file under its aside name
72
+ * (swept after the TTL), and the holder re-checks `stillHeld()` before
73
+ * installing. Unparseable lock content is
36
74
  * treated as stale (a torn write from a crashed holder must not wedge updates
37
75
  * forever). Everything is best-effort: any unexpected filesystem error reads
38
76
  * as "lock held", because the callers' shared philosophy is that updating is
@@ -42,17 +80,42 @@
42
80
  export declare const UPDATE_LOCK_STALE_MS: number;
43
81
  /** `tool` recorded when this CLI takes the lock. */
44
82
  export declare const UPDATE_LOCK_TOOL = "hq-cli-version-gate";
83
+ /**
84
+ * How often a holder rewrites `startedAt` while it holds the lock. Matches
85
+ * hq-desktop-app's `CLI_UPDATE_LOCK_HEARTBEAT` (60 s). An install may run up to
86
+ * the 30-minute update deadline, far past {@link UPDATE_LOCK_STALE_MS}. Without
87
+ * a refresh the desktop app (or another CLI) takes a live install's lock at
88
+ * 10 minutes and can start a second install on the same prefix.
89
+ */
90
+ export declare const UPDATE_LOCK_HEARTBEAT_MS: number;
91
+ /**
92
+ * Wait for the takeover mutex on the start-up update paths (the required-update
93
+ * gate and the attended self-updater). The mutex only guards a few file
94
+ * operations, so a longer wait adds start-up latency without making a
95
+ * takeover more likely to succeed when the mutex is wedged.
96
+ */
97
+ export declare const STARTUP_TAKEOVER_WAIT_MS = 1000;
98
+ /** How long release waits for the takeover mutex before deferring to exit. */
99
+ export declare const RELEASE_MUTEX_WAIT_MS = 2000;
45
100
  export interface UpdateLockInfo {
46
101
  pid: number;
47
102
  startedAt: string;
48
103
  tool: string;
49
104
  version: string;
105
+ /** Identifies this acquisition; optional in the contract. */
106
+ nonce?: string;
50
107
  }
51
108
  export interface UpdateLockHandle {
52
109
  /** Absolute path of the held lock file. */
53
110
  path: string;
54
111
  /** Delete the lock file. Idempotent, never throws. */
55
112
  release: () => void;
113
+ /**
114
+ * Whether the lock file still holds exactly this process's body. Call it
115
+ * right before installing; false means a racing taker moved the lock and
116
+ * another installer may be running.
117
+ */
118
+ stillHeld: () => boolean;
56
119
  }
57
120
  /** Injectable knobs so contention/staleness are unit-testable hermetically. */
58
121
  export interface UpdateLockOptions {
@@ -62,23 +125,97 @@ export interface UpdateLockOptions {
62
125
  isPidAlive?: (pid: number) => boolean;
63
126
  tool?: string;
64
127
  version?: string;
128
+ /** Wait for the shared takeover mutex (default 10 s). */
129
+ takeoverWaitMs?: number;
130
+ /** Stop waiting for the takeover mutex (the lock then reads as held). */
131
+ isCancelled?: () => boolean;
132
+ /** Test seam: runs between renaming a stale lock aside and checking it. */
133
+ afterTakeoverRename?: () => void;
134
+ /** Test seam: runs just before this process moves the lock file aside. */
135
+ beforeLockMove?: () => void;
136
+ /**
137
+ * Heartbeat interval while held (default {@link UPDATE_LOCK_HEARTBEAT_MS}).
138
+ * 0 disables the heartbeat.
139
+ */
140
+ heartbeatMs?: number;
141
+ /** Wait for the takeover mutex on release (default {@link RELEASE_MUTEX_WAIT_MS}). */
142
+ releaseMutexWaitMs?: number;
143
+ /**
144
+ * Called with a retry when release could not take the takeover mutex. The
145
+ * default runs the retry once when the process exits.
146
+ */
147
+ deferRelease?: (retry: () => void) => void;
65
148
  }
149
+ /**
150
+ * Env var overriding the lock DIRECTORY (not the file name). Contract — matches
151
+ * hq-desktop-app's `LOCK_DIR_ENV`, so both sides use one lock when it is set.
152
+ */
153
+ export declare const LOCK_DIR_ENV = "HQ_LOCK_DIR";
66
154
  export declare function updateLockPath(): string;
67
155
  /**
68
156
  * Whether an existing lock's recorded holder is safe to displace: its
69
- * `startedAt` is older than {@link UPDATE_LOCK_STALE_MS}, or its pid is dead.
157
+ * `startedAt` is at least {@link UPDATE_LOCK_STALE_MS} old or ahead, or its pid
158
+ * is dead.
70
159
  * Unreadable / malformed content is stale by definition — only a crashed or
71
160
  * interrupted holder leaves one behind, and treating it as fresh would block
72
161
  * every future update on this machine.
73
162
  */
74
163
  export declare function isLockStale(raw: string | null, now: number, isPidAlive: (pid: number) => boolean): boolean;
164
+ /**
165
+ * An unparseable lock younger than this may be a writer between create and
166
+ * write (older writers create the file before filling it), so it is not
167
+ * taken over yet. Matches the hq-desktop-app side.
168
+ */
169
+ export declare const UNPARSEABLE_LOCK_GRACE_MS: number;
170
+ /**
171
+ * Takeover mutex shared with hq-desktop-app: a DIRECTORY named
172
+ * `cli-update.lock.takeover` next to the lock, created with an atomic mkdir
173
+ * (the same on macOS, Linux and Windows, and the same as the Rust side).
174
+ * Publish, takeover and release run inside it. A holder file inside it older
175
+ * than {@link TAKEOVER_MUTEX_STALE_MS} was left by a crashed process and is
176
+ * stolen by renaming it. Contract — matches hq-desktop-app's
177
+ * `CLI_UPDATE_TAKEOVER_FILE`.
178
+ */
179
+ export declare const TAKEOVER_MUTEX_SUFFIX = ".takeover";
180
+ export declare const TAKEOVER_MUTEX_STALE_MS: number;
181
+ /** A holder file dated further ahead than this cannot be a clock correction. */
182
+ export declare const TAKEOVER_MUTEX_FUTURE_STALE_MS: number;
183
+ /** Default wait for the takeover mutex before reporting the lock as held. */
184
+ export declare const TAKEOVER_MUTEX_WAIT_MS: number;
185
+ /** Test seam points inside {@link acquireTakeoverMutex}. */
186
+ export type TakeoverMutexStage = "stale-judged" | "created" | "token-written";
187
+ /** Releases the takeover mutex when called. */
188
+ export type TakeoverMutexRelease = (() => void) & {
189
+ /** False once the holder file is gone, meaning another process stole the mutex. */
190
+ stillOwned: () => boolean;
191
+ };
192
+ /**
193
+ * Take the takeover mutex. Returns a release function, or null when the wait
194
+ * timed out or `isCancelled` returned true. Release removes the holder file and
195
+ * removes the directory only if that file was still there, so a holder whose
196
+ * mutex was stolen cannot remove the next holder's.
197
+ */
198
+ export declare function acquireTakeoverMutex(lockPath: string, options?: {
199
+ waitMs?: number;
200
+ staleMs?: number;
201
+ isCancelled?: () => boolean;
202
+ /** Test seam: runs at each stage so a test can interleave another process. */
203
+ onStage?: (stage: TakeoverMutexStage) => void;
204
+ }): TakeoverMutexRelease | null;
205
+ /**
206
+ * Remove a lock judged stale: rename it aside, confirm it is exactly the
207
+ * content that was judged, and only then delete it. A mismatch means another
208
+ * process replaced it; put it back (or leave it aside) and report it held.
209
+ * `afterRename` is a test seam for interleaving another process.
210
+ */
211
+ export declare function takeOverStale(lockPath: string, judged: string | null, afterRename?: () => void): boolean;
75
212
  /**
76
213
  * Take the machine-wide CLI-update lock, or return `null` when a fresh holder
77
- * has it (this process should skip its install). A stale holder is removed and
78
- * acquisition retried exactly once — two genuinely-racing processes still
79
- * serialize correctly because the retry goes back through O_EXCL.
214
+ * has it or the takeover mutex could not be taken (this process should skip
215
+ * its install). Takeover and publish both run inside the shared mutex.
80
216
  *
81
- * Callers MUST release in a `finally` around the install.
217
+ * Callers MUST call `stillHeld()` right before installing and release in a
218
+ * `finally` around the install.
82
219
  */
83
220
  export declare function acquireUpdateLock(options?: UpdateLockOptions): UpdateLockHandle | null;
84
221
  //# sourceMappingURL=update-lock.d.ts.map