@indigoai-us/hq-cli 5.345.221 → 5.345.222

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/dist/command-catalog.generated.d.ts +31 -0
  3. package/dist/command-catalog.generated.js +38 -0
  4. package/dist/commands/auth.js +2 -1
  5. package/dist/commands/core-delegate-w1b.js +9 -3
  6. package/dist/commands/daemon.d.ts +1 -0
  7. package/dist/commands/daemon.js +15 -1
  8. package/dist/commands/link.d.ts +2 -0
  9. package/dist/commands/link.js +14 -2
  10. package/dist/commands/mesh.js +23 -3
  11. package/dist/commands/sync-core.d.ts +6 -0
  12. package/dist/commands/sync-core.js +55 -0
  13. package/dist/data/command-states.json +3 -0
  14. package/dist/lib/daemon/catalog.js +2 -0
  15. package/dist/lib/daemon/install.d.ts +2 -1
  16. package/dist/lib/daemon/install.js +9 -0
  17. package/dist/lib/daemon/legacy.d.ts +1 -0
  18. package/dist/lib/daemon/legacy.js +5 -2
  19. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  20. package/dist/lib/daemon/machine-check-owner.js +6 -1
  21. package/dist/lib/daemon/machine-checks.d.ts +7 -1
  22. package/dist/lib/daemon/machine-checks.js +10 -1
  23. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  24. package/dist/lib/daemon/mesh-owner.js +166 -0
  25. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  26. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  27. package/dist/lib/daemon/run.d.ts +15 -0
  28. package/dist/lib/daemon/run.js +71 -3
  29. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  30. package/dist/lib/daemon/selfcheck.js +118 -9
  31. package/dist/lib/hook-engine/coverage.d.ts +9 -0
  32. package/dist/lib/hook-engine/coverage.js +56 -0
  33. package/dist/lib/hook-engine/native-stop-compatibility.json +56 -5
  34. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  35. package/dist/lib/mesh/live/daemon/config.js +16 -0
  36. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  37. package/dist/lib/mesh/live/daemon/install.js +142 -1
  38. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  39. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  40. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  41. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  42. package/dist/lib/registry/registry.d.ts +35 -7
  43. package/dist/lib/registry/registry.js +88 -13
  44. package/dist/lib/scan-packages/index.js +24 -2
  45. package/dist/lib/search-index/max-doc-bytes.js +2 -1
  46. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  47. package/dist/lib/service-manager/startup-migration.js +3 -0
  48. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  49. package/dist/lib/sync-core/engine-holds.js +60 -0
  50. package/dist/lib/sync-core/engine-home.d.ts +2 -0
  51. package/dist/lib/sync-core/reconcile.js +8 -0
  52. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  53. package/dist/lib/sync-core/vault-settings.js +131 -0
  54. package/dist/lib/windows/install-followup.d.ts +2 -0
  55. package/dist/lib/windows/install-followup.js +4 -1
  56. package/dist/utils/host-registration.js +3 -1
  57. package/dist/utils/pack-contributions.d.ts +3 -0
  58. package/dist/utils/pack-contributions.js +110 -23
  59. package/dist/utils/self-update.d.ts +3 -1
  60. package/dist/utils/self-update.js +56 -11
  61. package/dist/utils/update-lock.d.ts +151 -14
  62. package/dist/utils/update-lock.js +782 -46
  63. package/dist/utils/version-gate.js +12 -2
  64. package/package.json +7 -7
@@ -18,51 +18,136 @@
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
39
77
  * optional and the CLI keeps working either way.
40
78
  */
79
+ import { randomUUID } from "node:crypto";
41
80
  import * as fs from "node:fs";
42
81
  import * as os from "node:os";
43
82
  import * as path from "node:path";
83
+ import { Worker } from "node:worker_threads";
44
84
  import { CLI_VERSION } from "../cli-version.js";
45
85
  /** A held lock older than this is treated as abandoned (crashed owner). */
46
86
  export const UPDATE_LOCK_STALE_MS = 10 * 60 * 1000;
47
87
  /** `tool` recorded when this CLI takes the lock. */
48
88
  export const UPDATE_LOCK_TOOL = "hq-cli-version-gate";
89
+ /**
90
+ * How often a holder rewrites `startedAt` while it holds the lock. Matches
91
+ * hq-desktop-app's `CLI_UPDATE_LOCK_HEARTBEAT` (60 s). An install may run up to
92
+ * the 30-minute update deadline, far past {@link UPDATE_LOCK_STALE_MS}. Without
93
+ * a refresh the desktop app (or another CLI) takes a live install's lock at
94
+ * 10 minutes and can start a second install on the same prefix.
95
+ */
96
+ export const UPDATE_LOCK_HEARTBEAT_MS = 60 * 1000;
97
+ /**
98
+ * Wait for the takeover mutex on the start-up update paths (the required-update
99
+ * gate and the attended self-updater). The mutex only guards a few file
100
+ * operations, so a longer wait adds start-up latency without making a
101
+ * takeover more likely to succeed when the mutex is wedged.
102
+ */
103
+ export const STARTUP_TAKEOVER_WAIT_MS = 1000;
104
+ /** How long release waits for the takeover mutex before deferring to exit. */
105
+ export const RELEASE_MUTEX_WAIT_MS = 2000;
106
+ /**
107
+ * Env var overriding the lock DIRECTORY (not the file name). Contract — matches
108
+ * hq-desktop-app's `LOCK_DIR_ENV`, so both sides use one lock when it is set.
109
+ */
110
+ export const LOCK_DIR_ENV = "HQ_LOCK_DIR";
49
111
  export function updateLockPath() {
112
+ const dir = process.env[LOCK_DIR_ENV];
113
+ if (dir)
114
+ return path.join(dir, "cli-update.lock");
50
115
  return path.join(os.homedir(), ".hq", "locks", "cli-update.lock");
51
116
  }
117
+ /** A pid the desktop app can read: absent, null, or an unsigned 32-bit integer. */
118
+ function pidFieldIsReadable(pid) {
119
+ return pid === undefined || pid === null || (Number.isInteger(pid) && pid >= 0 && pid <= 0xffffffff);
120
+ }
121
+ /**
122
+ * Whether the lock parses the way the desktop app parses it (a `startedAt`
123
+ * string and a readable pid). A lock that does not gets the
124
+ * {@link UNPARSEABLE_LOCK_GRACE_MS} grace on both sides.
125
+ */
126
+ function isParseableLock(raw) {
127
+ try {
128
+ const info = JSON.parse(raw);
129
+ return info != null && typeof info.startedAt === "string" && pidFieldIsReadable(info.pid);
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ }
52
135
  function defaultIsPidAlive(pid) {
53
136
  try {
54
137
  process.kill(pid, 0);
55
138
  return true;
56
139
  }
57
140
  catch (err) {
58
- // ESRCH — no such process. EPERM means it exists but is not ours; that
59
- // still counts as alive (we must not steal a root-owned updater's lock).
60
- return err.code === "EPERM";
141
+ // Only ESRCH (no such process) means dead, as on the desktop side. EPERM
142
+ // means it exists under another user, and a pid this probe cannot handle
143
+ // (e.g. one above 2^31, which Node rejects) is not proof of anything.
144
+ return err.code !== "ESRCH";
61
145
  }
62
146
  }
63
147
  /**
64
148
  * Whether an existing lock's recorded holder is safe to displace: its
65
- * `startedAt` is older than {@link UPDATE_LOCK_STALE_MS}, or its pid is dead.
149
+ * `startedAt` is at least {@link UPDATE_LOCK_STALE_MS} old or ahead, or its pid
150
+ * is dead.
66
151
  * Unreadable / malformed content is stale by definition — only a crashed or
67
152
  * interrupted holder leaves one behind, and treating it as fresh would block
68
153
  * every future update on this machine.
@@ -77,60 +162,676 @@ export function isLockStale(raw, now, isPidAlive) {
77
162
  catch {
78
163
  return true;
79
164
  }
80
- if (typeof info.pid !== "number" || typeof info.startedAt !== "string") {
165
+ if (info == null || typeof info.startedAt !== "string")
81
166
  return true;
82
- }
83
167
  const startedAt = Date.parse(info.startedAt);
84
168
  if (Number.isNaN(startedAt))
85
169
  return true;
86
- if (now - startedAt > UPDATE_LOCK_STALE_MS)
170
+ // Same boundaries as hq-desktop-app: at least the TTL old, or at least the
171
+ // TTL in the future.
172
+ if (now - startedAt >= UPDATE_LOCK_STALE_MS)
173
+ return true;
174
+ if (startedAt - now >= UPDATE_LOCK_STALE_MS)
175
+ return true;
176
+ // A legacy lock with no pid has nothing to probe. The desktop app retires it
177
+ // by age only, so this side does too and never takes a lock it still honors.
178
+ if (info.pid === undefined || info.pid === null)
179
+ return false;
180
+ // Not a pid the desktop app can read: stale, but acquireUpdateLock still
181
+ // gives it the unparseable-lock grace, as the desktop app does.
182
+ if (!pidFieldIsReadable(info.pid))
87
183
  return true;
88
184
  if (!isPidAlive(info.pid))
89
185
  return true;
90
186
  return false;
91
187
  }
92
- function tryCreate(lockPath, body) {
93
- let fd;
188
+ /**
189
+ * An unparseable lock younger than this may be a writer between create and
190
+ * write (older writers create the file before filling it), so it is not
191
+ * taken over yet. Matches the hq-desktop-app side.
192
+ */
193
+ export const UNPARSEABLE_LOCK_GRACE_MS = 30 * 1000;
194
+ /**
195
+ * Takeover mutex shared with hq-desktop-app: a DIRECTORY named
196
+ * `cli-update.lock.takeover` next to the lock, created with an atomic mkdir
197
+ * (the same on macOS, Linux and Windows, and the same as the Rust side).
198
+ * Publish, takeover and release run inside it. A holder file inside it older
199
+ * than {@link TAKEOVER_MUTEX_STALE_MS} was left by a crashed process and is
200
+ * stolen by renaming it. Contract — matches hq-desktop-app's
201
+ * `CLI_UPDATE_TAKEOVER_FILE`.
202
+ */
203
+ export const TAKEOVER_MUTEX_SUFFIX = ".takeover";
204
+ export const TAKEOVER_MUTEX_STALE_MS = 30 * 1000;
205
+ /** A holder file dated further ahead than this cannot be a clock correction. */
206
+ export const TAKEOVER_MUTEX_FUTURE_STALE_MS = 24 * 60 * 60 * 1000;
207
+ /** Default wait for the takeover mutex before reporting the lock as held. */
208
+ export const TAKEOVER_MUTEX_WAIT_MS = 10 * 1000;
209
+ function siblingTemp(lockPath, tag) {
210
+ return `${lockPath}.${tag}-${process.pid}-${Math.random().toString(36).slice(2)}`;
211
+ }
212
+ function sleepSync(ms) {
213
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
214
+ }
215
+ function ageMs(p, now) {
94
216
  try {
95
- // 'wx' — O_CREAT|O_EXCL|O_WRONLY: fails atomically if the file exists.
96
- fd = fs.openSync(lockPath, "wx");
217
+ return now - fs.statSync(p).mtimeMs;
218
+ }
219
+ catch {
220
+ return null;
221
+ }
222
+ }
223
+ /**
224
+ * A holder file's name carries the time it was taken, because a rename keeps the
225
+ * file's mtime. Contract — matches hq-desktop-app's `mutex_token_name`.
226
+ */
227
+ function newMutexToken(mutex) {
228
+ return path.join(mutex, `owner-${process.pid}-${Math.random().toString(36).slice(2)}-t${Date.now()}`);
229
+ }
230
+ /** Age from the time in the name, or the file's mtime for any other name. */
231
+ function mutexTokenAgeMs(mutex, name, now) {
232
+ const stamped = /-t(\d{1,15})$/.exec(name);
233
+ if (stamped)
234
+ return now - Number(stamped[1]);
235
+ return ageMs(path.join(mutex, name), now);
236
+ }
237
+ /**
238
+ * A holder file dated ahead is normal after the clock is corrected backward, and
239
+ * that holder may still be running. Only a time further ahead than any such
240
+ * correction counts as stale. A crashed holder's file dated less than this ahead
241
+ * clears once its time plus the stale limit has passed. Matches hq-desktop-app's
242
+ * `mutex_age_is_stale`.
243
+ */
244
+ function mutexAgeIsStale(age, staleMs) {
245
+ return age !== null && (age >= staleMs || age <= -TAKEOVER_MUTEX_FUTURE_STALE_MS);
246
+ }
247
+ function removeMutexDirBestEffort(mutex) {
248
+ try {
249
+ fs.rmdirSync(mutex);
97
250
  }
98
251
  catch {
252
+ // Not empty: someone else's file is inside. Otherwise removed after its TTL.
253
+ }
254
+ }
255
+ /**
256
+ * Handle a mutex that already exists. When every holder file in it is stale,
257
+ * rename one to a new name of ours and return that path. A rename either moves
258
+ * the file judged stale or fails, so of several stealers one wins, and one acting
259
+ * on an out-of-date judgment changes nothing. An empty directory (a holder that
260
+ * crashed before writing its file) is removed, which fails if a file has landed
261
+ * in it. Returns null when the caller should keep waiting.
262
+ */
263
+ function stealOrClearMutex(mutex, staleMs, onStage) {
264
+ let names;
265
+ try {
266
+ names = fs.readdirSync(mutex);
267
+ }
268
+ catch (err) {
269
+ // A plain file of this name came from an unreleased build.
270
+ if (err.code === "ENOTDIR" &&
271
+ mutexAgeIsStale(ageMs(mutex, Date.now()), staleMs)) {
272
+ try {
273
+ fs.rmSync(mutex);
274
+ }
275
+ catch {
276
+ // best-effort; keep waiting
277
+ }
278
+ }
99
279
  return null;
100
280
  }
281
+ const now = Date.now();
282
+ if (names.length === 0) {
283
+ if (mutexAgeIsStale(ageMs(mutex, now), staleMs)) {
284
+ onStage?.("stale-judged");
285
+ removeMutexDirBestEffort(mutex);
286
+ }
287
+ return null;
288
+ }
289
+ // Any name counts as a holder, so nothing left in here can wedge the mutex.
290
+ if (!names.every((name) => mutexAgeIsStale(mutexTokenAgeMs(mutex, name, now), staleMs))) {
291
+ return null;
292
+ }
293
+ onStage?.("stale-judged");
294
+ const mine = newMutexToken(mutex);
101
295
  try {
102
- fs.writeSync(fd, body);
296
+ fs.renameSync(path.join(mutex, names[0]), mine);
297
+ return mine;
103
298
  }
104
299
  catch {
105
- // A lock we created but could not stamp is still OURS — keep it.
300
+ return null;
106
301
  }
107
- finally {
302
+ }
303
+ function createMutexToken(mutex) {
304
+ const token = newMutexToken(mutex);
305
+ try {
306
+ fs.closeSync(fs.openSync(token, "wx"));
307
+ return token;
308
+ }
309
+ catch {
310
+ // The directory was removed by a stealer acting on an empty old mutex, or
311
+ // cannot be written. The caller retries under its deadline.
312
+ removeMutexDirBestEffort(mutex);
313
+ return null;
314
+ }
315
+ }
316
+ function mutexTokenIsAlone(mutex, token) {
317
+ try {
318
+ const names = fs.readdirSync(mutex);
319
+ return names.length === 1 && names[0] === path.basename(token);
320
+ }
321
+ catch {
322
+ return false;
323
+ }
324
+ }
325
+ /**
326
+ * Take the takeover mutex. Returns a release function, or null when the wait
327
+ * timed out or `isCancelled` returned true. Release removes the holder file and
328
+ * removes the directory only if that file was still there, so a holder whose
329
+ * mutex was stolen cannot remove the next holder's.
330
+ */
331
+ export function acquireTakeoverMutex(lockPath, options = {}) {
332
+ const mutex = lockPath + TAKEOVER_MUTEX_SUFFIX;
333
+ const waitMs = options.waitMs ?? TAKEOVER_MUTEX_WAIT_MS;
334
+ const staleMs = options.staleMs ?? TAKEOVER_MUTEX_STALE_MS;
335
+ // Monotonic, so a clock change cannot stretch or end the wait.
336
+ const started = performance.now();
337
+ for (;;) {
338
+ if (options.isCancelled?.())
339
+ return null;
340
+ let created = false;
108
341
  try {
109
- fs.closeSync(fd);
342
+ fs.mkdirSync(mutex);
343
+ created = true;
344
+ }
345
+ catch (err) {
346
+ if (err.code !== "EEXIST")
347
+ return null;
348
+ }
349
+ let token;
350
+ if (created) {
351
+ options.onStage?.("created");
352
+ token = createMutexToken(mutex);
353
+ }
354
+ else {
355
+ token = stealOrClearMutex(mutex, staleMs, options.onStage);
356
+ }
357
+ if (token) {
358
+ options.onStage?.("token-written");
359
+ // Hold only when alone. If two files are here, the process that wrote
360
+ // second sees both and backs off.
361
+ if (mutexTokenIsAlone(mutex, token))
362
+ return releaseMutex(mutex, token);
363
+ try {
364
+ fs.rmSync(token);
365
+ }
366
+ catch {
367
+ // already gone
368
+ }
369
+ removeMutexDirBestEffort(mutex);
370
+ }
371
+ if (performance.now() - started >= waitMs)
372
+ return null;
373
+ sleepSync(20);
374
+ }
375
+ }
376
+ function releaseMutex(mutex, token) {
377
+ const release = () => {
378
+ try {
379
+ fs.rmSync(token);
110
380
  }
111
381
  catch {
112
- // already closed
382
+ return;
383
+ }
384
+ removeMutexDirBestEffort(mutex);
385
+ };
386
+ return Object.assign(release, { stillOwned: () => fs.existsSync(token) });
387
+ }
388
+ /** Remove aside/temp files older than the lock TTL. Runs under the mutex. */
389
+ function sweepOldAsides(lockPath, now) {
390
+ const dir = path.dirname(lockPath);
391
+ const base = path.basename(lockPath) + ".";
392
+ let names;
393
+ try {
394
+ names = fs.readdirSync(dir);
395
+ }
396
+ catch {
397
+ return;
398
+ }
399
+ for (const name of names) {
400
+ if (!name.startsWith(base))
401
+ continue;
402
+ const rest = name.slice(base.length);
403
+ if (!/^(stale-|release-|tmp-|takeover\.stale-)/.test(rest))
404
+ continue;
405
+ const p = path.join(dir, name);
406
+ const age = ageMs(p, now);
407
+ if (age === null || age < UPDATE_LOCK_STALE_MS)
408
+ continue;
409
+ try {
410
+ fs.rmSync(p, { recursive: true, force: true });
411
+ }
412
+ catch {
413
+ // best-effort
113
414
  }
114
415
  }
115
- return {
116
- path: lockPath,
117
- release: () => {
416
+ }
417
+ function readOrNull(p) {
418
+ try {
419
+ return fs.readFileSync(p, "utf-8");
420
+ }
421
+ catch {
422
+ return null;
423
+ }
424
+ }
425
+ /**
426
+ * Whether `raw` is the lock this acquisition published. The heartbeat rewrites
427
+ * `startedAt`, so ownership is the pid, tool and nonce, as on the desktop side
428
+ * (`lock_owned_by`). A lock that cannot be parsed is never ours.
429
+ */
430
+ function lockIsOurs(raw, identity) {
431
+ if (raw === null)
432
+ return false;
433
+ try {
434
+ const info = JSON.parse(raw);
435
+ return (info != null &&
436
+ info.pid === identity.pid &&
437
+ info.tool === identity.tool &&
438
+ info.nonce === identity.nonce);
439
+ }
440
+ catch {
441
+ return false;
442
+ }
443
+ }
444
+ /**
445
+ * Heartbeat worker. The install runs under `spawnSync`, which blocks this
446
+ * thread for as long as the install takes, so a timer here could not fire. A
447
+ * worker thread keeps its own event loop. Every `intervalMs` it takes the
448
+ * takeover mutex (same directory, holder-file and stale rules as
449
+ * {@link acquireTakeoverMutex}), checks the lock is still ours, and rewrites
450
+ * `startedAt` through a temp file and a rename. It stops for good once the lock
451
+ * is gone or parses as someone else's; a read error or a busy mutex skips one
452
+ * beat. `control[0]` is the stop flag and `control[1]` is set while a beat runs.
453
+ */
454
+ const HEARTBEAT_SOURCE = `
455
+ const { workerData } = require("node:worker_threads");
456
+ const fs = require("node:fs");
457
+ const path = require("node:path");
458
+ const { lockPath, pid, tool, nonce, intervalMs, mutexWaitMs, mutexStaleMs, mutexFutureStaleMs } = workerData;
459
+ const control = new Int32Array(workerData.control);
460
+ const mutex = lockPath + ${JSON.stringify(TAKEOVER_MUTEX_SUFFIX)};
461
+ const stopped = () => Atomics.load(control, 0) !== 0;
462
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
463
+ const rand = () => Math.random().toString(36).slice(2);
464
+ const newHolderFile = () => path.join(mutex, "owner-" + process.pid + "-" + rand() + "-t" + Date.now());
465
+ const isStale = (age) => age !== null && (age >= mutexStaleMs || age <= -mutexFutureStaleMs);
466
+ const rmdirQuiet = () => { try { fs.rmdirSync(mutex); } catch {} };
467
+ function tokenAge(name, now) {
468
+ const stamped = /-t(\\d{1,15})$/.exec(name);
469
+ if (stamped) return now - Number(stamped[1]);
470
+ try { return now - fs.statSync(path.join(mutex, name)).mtimeMs; } catch { return null; }
471
+ }
472
+ function acquireMutex() {
473
+ const started = performance.now();
474
+ for (;;) {
475
+ if (stopped()) return null;
476
+ let created = false;
477
+ try { fs.mkdirSync(mutex); created = true; } catch (e) { if (e.code !== "EEXIST") return null; }
478
+ let mine = null;
479
+ if (created) {
480
+ const holderFile = newHolderFile();
481
+ try { fs.closeSync(fs.openSync(holderFile, "wx")); mine = holderFile; } catch { rmdirQuiet(); }
482
+ } else {
483
+ let names = null;
484
+ try { names = fs.readdirSync(mutex); } catch {}
485
+ if (names !== null) {
486
+ const now = Date.now();
487
+ if (names.length === 0) {
488
+ try { if (isStale(now - fs.statSync(mutex).mtimeMs)) rmdirQuiet(); } catch {}
489
+ } else if (names.every((name) => isStale(tokenAge(name, now)))) {
490
+ const holderFile = newHolderFile();
491
+ try { fs.renameSync(path.join(mutex, names[0]), holderFile); mine = holderFile; } catch {}
492
+ }
493
+ }
494
+ }
495
+ if (mine !== null) {
496
+ try {
497
+ const names = fs.readdirSync(mutex);
498
+ if (names.length === 1 && names[0] === path.basename(mine)) return mine;
499
+ } catch {}
500
+ try { fs.rmSync(mine); } catch {}
501
+ rmdirQuiet();
502
+ }
503
+ if (performance.now() - started >= mutexWaitMs) return null;
504
+ sleep(20);
505
+ }
506
+ }
507
+ function releaseMutex(holderFile) {
508
+ try { fs.rmSync(holderFile); } catch { return; }
509
+ rmdirQuiet();
510
+ }
511
+ // "ours" | "lost" (gone, or someone else's) | "unknown" (unreadable or torn).
512
+ function ownership() {
513
+ let raw;
514
+ try { raw = fs.readFileSync(lockPath, "utf8"); } catch (e) { return e.code === "ENOENT" ? "lost" : "unknown"; }
515
+ let info;
516
+ try { info = JSON.parse(raw); } catch { return "unknown"; }
517
+ if (info === null || typeof info !== "object") return "unknown";
518
+ return info.pid === pid && info.tool === tool && info.nonce === nonce ? "ours" : "lost";
519
+ }
520
+ function beat() {
521
+ const before = ownership();
522
+ if (before !== "ours") return before;
523
+ const holderFile = acquireMutex();
524
+ if (holderFile === null) return "unknown";
525
+ try {
526
+ if (stopped()) return "lost";
527
+ const now = ownership();
528
+ if (now !== "ours") return now;
529
+ if (!fs.existsSync(holderFile)) return "unknown";
530
+ const info = JSON.parse(fs.readFileSync(lockPath, "utf8"));
531
+ info.startedAt = new Date().toISOString();
532
+ const tmp = lockPath + ".tmp-" + process.pid + "-" + rand();
533
+ try {
534
+ fs.writeFileSync(tmp, JSON.stringify(info), { flag: "wx" });
535
+ fs.renameSync(tmp, lockPath);
536
+ } catch {
537
+ try { fs.rmSync(tmp, { force: true }); } catch {}
538
+ return "unknown";
539
+ }
540
+ return "ours";
541
+ } finally {
542
+ releaseMutex(holderFile);
543
+ }
544
+ }
545
+ for (;;) {
546
+ Atomics.wait(control, 0, 0, intervalMs);
547
+ Atomics.store(control, 1, 1);
548
+ if (stopped()) break;
549
+ let result;
550
+ try { result = beat(); } catch { result = "unknown"; }
551
+ Atomics.store(control, 1, 0);
552
+ Atomics.notify(control, 1);
553
+ if (result === "lost") break;
554
+ }
555
+ Atomics.store(control, 1, 0);
556
+ Atomics.notify(control, 1);
557
+ `;
558
+ function startHeartbeat(lockPath, identity, intervalMs) {
559
+ if (!(intervalMs > 0))
560
+ return () => { };
561
+ const controlBuffer = new SharedArrayBuffer(8);
562
+ const control = new Int32Array(controlBuffer);
563
+ let worker;
564
+ try {
565
+ worker = new Worker(HEARTBEAT_SOURCE, {
566
+ eval: true,
567
+ workerData: {
568
+ control: controlBuffer,
569
+ lockPath,
570
+ pid: identity.pid,
571
+ tool: identity.tool,
572
+ nonce: identity.nonce,
573
+ intervalMs,
574
+ mutexWaitMs: RELEASE_MUTEX_WAIT_MS,
575
+ mutexStaleMs: TAKEOVER_MUTEX_STALE_MS,
576
+ mutexFutureStaleMs: TAKEOVER_MUTEX_FUTURE_STALE_MS,
577
+ },
578
+ });
579
+ }
580
+ catch {
581
+ // Restricted runtimes can refuse workers. The lock still works; a hold
582
+ // longer than the TTL is then exposed exactly as it was before.
583
+ return () => { };
584
+ }
585
+ worker.on("error", () => {
586
+ // Best-effort: a dead heartbeat leaves the lock to age out by its TTL.
587
+ });
588
+ // on() re-refs the worker, so unref last: the heartbeat must never keep the
589
+ // process alive.
590
+ worker.unref();
591
+ let stopped = false;
592
+ return () => {
593
+ if (stopped)
594
+ return;
595
+ stopped = true;
596
+ Atomics.store(control, 0, 1);
597
+ Atomics.notify(control, 0);
598
+ // A beat holds the mutex for a few file operations, after waiting at most
599
+ // RELEASE_MUTEX_WAIT_MS for it. Waiting here keeps release from contending
600
+ // with our own beat; correctness does not depend on it, because a beat
601
+ // re-checks the stop flag under the mutex before it writes.
602
+ const deadline = performance.now() + RELEASE_MUTEX_WAIT_MS + 1000;
603
+ while (Atomics.load(control, 1) !== 0 && performance.now() < deadline) {
604
+ Atomics.wait(control, 1, 1, 50);
605
+ }
606
+ // Killing a worker mid-beat would leave its holder file in the mutex (and
607
+ // block every updater for the mutex TTL). A worker still in a beat sees the
608
+ // stop flag when the beat ends and exits on its own; it is unref'd.
609
+ if (Atomics.load(control, 1) === 0)
610
+ void worker.terminate().catch(() => undefined);
611
+ };
612
+ }
613
+ /**
614
+ * Remove the lock while it is still ours, inside the takeover mutex, renaming
615
+ * it aside first so a takeover between the check and the delete is put back.
616
+ * Returns false only when the lock was ours but the mutex stayed busy.
617
+ */
618
+ function releaseOwnedLock(lockPath, ctx) {
619
+ if (!lockIsOurs(readOrNull(lockPath), ctx.identity))
620
+ return true;
621
+ // Without the mutex another process may be replacing the lock, and moving
622
+ // it now could displace that process's lock.
623
+ const unlock = acquireTakeoverMutex(lockPath, { waitMs: ctx.releaseMutexWaitMs });
624
+ if (!unlock)
625
+ return false;
626
+ try {
627
+ // A takeover can have finished between the check above and the mutex.
628
+ // Moving the replacement could not always be undone, so it stays put.
629
+ if (!lockIsOurs(readOrNull(lockPath), ctx.identity))
630
+ return true;
631
+ ctx.beforeLockMove?.();
632
+ // Another process stole the mutex and may be working on the lock.
633
+ if (!unlock.stillOwned())
634
+ return true;
635
+ const aside = siblingTemp(lockPath, "release");
636
+ try {
637
+ fs.renameSync(lockPath, aside);
638
+ }
639
+ catch {
640
+ return true;
641
+ }
642
+ if (lockIsOurs(readOrNull(aside), ctx.identity)) {
118
643
  try {
119
- fs.rmSync(lockPath, { force: true });
644
+ fs.rmSync(aside, { force: true });
120
645
  }
121
646
  catch {
122
- // best-effort lock cleanup
647
+ // best-effort
123
648
  }
649
+ }
650
+ else {
651
+ restoreAside(aside, lockPath);
652
+ }
653
+ return true;
654
+ }
655
+ finally {
656
+ unlock();
657
+ }
658
+ }
659
+ /** Releases still owed at exit. One listener, however many handles defer. */
660
+ const pendingExitReleases = new Set();
661
+ function deferReleaseToExit(retry) {
662
+ if (pendingExitReleases.size === 0) {
663
+ process.once("exit", () => {
664
+ for (const release of pendingExitReleases)
665
+ release();
666
+ pendingExitReleases.clear();
667
+ });
668
+ }
669
+ pendingExitReleases.add(retry);
670
+ }
671
+ function handleFor(lockPath, ctx) {
672
+ let released = false;
673
+ const stopHeartbeat = startHeartbeat(lockPath, ctx.identity, ctx.heartbeatMs);
674
+ return {
675
+ path: lockPath,
676
+ stillHeld: () => !released && lockIsOurs(readOrNull(lockPath), ctx.identity),
677
+ release: () => {
678
+ if (released)
679
+ return;
680
+ released = true;
681
+ stopHeartbeat();
682
+ if (releaseOwnedLock(lockPath, ctx))
683
+ return;
684
+ // The mutex stayed busy. With the heartbeat stopped the lock ages out
685
+ // within the TTL; until then try once more when this process exits, so
686
+ // a long-running process does not keep other updaters out for minutes.
687
+ ctx.deferRelease(() => {
688
+ try {
689
+ releaseOwnedLock(lockPath, ctx);
690
+ }
691
+ catch {
692
+ // best-effort at exit
693
+ }
694
+ });
124
695
  },
125
696
  };
126
697
  }
698
+ /**
699
+ * Publish `body` at `lockPath` only if nothing is there. The body goes to a
700
+ * temp file first and is hard-linked into place (link never replaces), so
701
+ * the lock is never visible empty. Filesystems without hard links fall back
702
+ * to 'wx' + write.
703
+ */
704
+ function tryCreate(lockPath, body, ctx) {
705
+ const tmp = siblingTemp(lockPath, "tmp");
706
+ let linkError = null;
707
+ try {
708
+ fs.writeFileSync(tmp, body, { flag: "wx" });
709
+ try {
710
+ fs.linkSync(tmp, lockPath);
711
+ }
712
+ catch (err) {
713
+ linkError = err;
714
+ }
715
+ }
716
+ catch {
717
+ linkError = { code: "ETMP" };
718
+ }
719
+ finally {
720
+ try {
721
+ fs.rmSync(tmp, { force: true });
722
+ }
723
+ catch {
724
+ // best-effort temp cleanup
725
+ }
726
+ }
727
+ if (linkError == null)
728
+ return handleFor(lockPath, ctx);
729
+ if (linkError.code === "EEXIST")
730
+ return null;
731
+ return tryCreateInPlace(lockPath, body, ctx);
732
+ }
733
+ function tryCreateInPlace(lockPath, body, ctx) {
734
+ let fd;
735
+ try {
736
+ // 'wx' — O_CREAT|O_EXCL|O_WRONLY: fails atomically if the file exists.
737
+ fd = fs.openSync(lockPath, "wx");
738
+ }
739
+ catch {
740
+ return null;
741
+ }
742
+ // A lock the file does not fully hold can never pass `stillHeld()` and is
743
+ // never deleted by `release()`, so a failed or stalled write removes the
744
+ // file and reports no lock rather than handing back a broken one.
745
+ let written = false;
746
+ try {
747
+ const bytes = Buffer.from(body, "utf-8");
748
+ let offset = 0;
749
+ while (offset < bytes.length) {
750
+ const n = fs.writeSync(fd, bytes, offset, bytes.length - offset);
751
+ if (n <= 0)
752
+ break;
753
+ offset += n;
754
+ }
755
+ written = offset === bytes.length;
756
+ }
757
+ catch {
758
+ written = false;
759
+ }
760
+ finally {
761
+ try {
762
+ fs.closeSync(fd);
763
+ }
764
+ catch {
765
+ // already closed
766
+ }
767
+ }
768
+ if (!written) {
769
+ try {
770
+ fs.rmSync(lockPath, { force: true });
771
+ }
772
+ catch {
773
+ // best-effort; an unparseable lock is reclaimed after the grace period
774
+ }
775
+ return null;
776
+ }
777
+ return handleFor(lockPath, ctx);
778
+ }
779
+ /**
780
+ * Put a moved-aside lock back without clobbering one published meanwhile.
781
+ * Only a hard link is used (it never replaces). If it fails for any reason
782
+ * the file stays under its aside name — never deleted, never check-then-
783
+ * renamed — and the sweep removes it after the TTL. Its owner sees the loss
784
+ * through `stillHeld()` before installing.
785
+ */
786
+ function restoreAside(aside, lockPath) {
787
+ try {
788
+ fs.linkSync(aside, lockPath);
789
+ }
790
+ catch {
791
+ return;
792
+ }
793
+ try {
794
+ fs.rmSync(aside, { force: true });
795
+ }
796
+ catch {
797
+ // best-effort
798
+ }
799
+ }
800
+ /**
801
+ * Remove a lock judged stale: rename it aside, confirm it is exactly the
802
+ * content that was judged, and only then delete it. A mismatch means another
803
+ * process replaced it; put it back (or leave it aside) and report it held.
804
+ * `afterRename` is a test seam for interleaving another process.
805
+ */
806
+ export function takeOverStale(lockPath, judged, afterRename = () => { }) {
807
+ const aside = siblingTemp(lockPath, "stale");
808
+ try {
809
+ fs.renameSync(lockPath, aside);
810
+ }
811
+ catch (err) {
812
+ return err.code === "ENOENT";
813
+ }
814
+ afterRename();
815
+ const now = readOrNull(aside);
816
+ if (now !== null && now === judged) {
817
+ try {
818
+ fs.rmSync(aside, { force: true });
819
+ }
820
+ catch {
821
+ // best-effort
822
+ }
823
+ return true;
824
+ }
825
+ restoreAside(aside, lockPath);
826
+ return false;
827
+ }
127
828
  /**
128
829
  * Take the machine-wide CLI-update lock, or return `null` when a fresh holder
129
- * has it (this process should skip its install). A stale holder is removed and
130
- * acquisition retried exactly once — two genuinely-racing processes still
131
- * serialize correctly because the retry goes back through O_EXCL.
830
+ * has it or the takeover mutex could not be taken (this process should skip
831
+ * its install). Takeover and publish both run inside the shared mutex.
132
832
  *
133
- * Callers MUST release in a `finally` around the install.
833
+ * Callers MUST call `stillHeld()` right before installing and release in a
834
+ * `finally` around the install.
134
835
  */
135
836
  export function acquireUpdateLock(options = {}) {
136
837
  const lockPath = options.lockPath ?? updateLockPath();
@@ -141,33 +842,68 @@ export function acquireUpdateLock(options = {}) {
141
842
  startedAt: new Date(now).toISOString(),
142
843
  tool: options.tool ?? UPDATE_LOCK_TOOL,
143
844
  version: options.version ?? CLI_VERSION,
845
+ nonce: randomUUID(),
144
846
  };
145
847
  const body = JSON.stringify(info);
848
+ const ctx = {
849
+ identity: { pid: info.pid, tool: info.tool, nonce: info.nonce },
850
+ beforeLockMove: options.beforeLockMove,
851
+ heartbeatMs: options.heartbeatMs ?? UPDATE_LOCK_HEARTBEAT_MS,
852
+ releaseMutexWaitMs: options.releaseMutexWaitMs ?? RELEASE_MUTEX_WAIT_MS,
853
+ deferRelease: options.deferRelease ?? deferReleaseToExit,
854
+ };
146
855
  try {
147
856
  fs.mkdirSync(path.dirname(lockPath), { recursive: true });
148
857
  }
149
858
  catch {
150
859
  return null; // can't even create ~/.hq/locks — treat as held, skip update
151
860
  }
152
- const first = tryCreate(lockPath, body);
153
- if (first)
154
- return first;
155
- // Lock exists. Fresh holder → back off. Stale → remove and retry ONCE.
156
- let raw;
861
+ // Judge an existing lock without the mutex, so a fresh holder costs no wait.
862
+ let raw = null;
157
863
  try {
158
864
  raw = fs.readFileSync(lockPath, "utf-8");
159
865
  }
160
- catch {
161
- raw = null; // vanished (holder just released) or unreadable — stale path
866
+ catch (err) {
867
+ // Absent: nothing to judge. Unreadable: held.
868
+ if (err.code !== "ENOENT")
869
+ return null;
870
+ }
871
+ if (raw !== null) {
872
+ if (!isLockStale(raw, now, isPidAlive))
873
+ return null;
874
+ if (!isParseableLock(raw)) {
875
+ // A young unparseable lock may be a writer mid-write.
876
+ const age = ageMs(lockPath, Date.now());
877
+ if (age === null || age < UNPARSEABLE_LOCK_GRACE_MS)
878
+ return null;
879
+ }
162
880
  }
163
- if (!isLockStale(raw, now, isPidAlive))
881
+ // Every publish runs inside the mutex. A takeover empties the name while it
882
+ // compares, and a publish outside the mutex could land in that window.
883
+ const unlock = acquireTakeoverMutex(lockPath, {
884
+ waitMs: options.takeoverWaitMs,
885
+ isCancelled: options.isCancelled,
886
+ });
887
+ if (!unlock)
164
888
  return null;
165
889
  try {
166
- fs.rmSync(lockPath, { force: true });
890
+ sweepOldAsides(lockPath, Date.now());
891
+ // Re-read under the mutex: the lock may have changed since it was judged.
892
+ const again = readOrNull(lockPath);
893
+ if (again !== null && again !== raw)
894
+ return null;
895
+ if (again !== null) {
896
+ options.beforeLockMove?.();
897
+ // Another process stole the mutex and may be working on the lock.
898
+ if (!unlock.stillOwned())
899
+ return null;
900
+ if (!takeOverStale(lockPath, raw, options.afterTakeoverRename))
901
+ return null;
902
+ }
903
+ return tryCreate(lockPath, body, ctx);
167
904
  }
168
- catch {
169
- return null;
905
+ finally {
906
+ unlock();
170
907
  }
171
- return tryCreate(lockPath, body);
172
908
  }
173
909
  //# sourceMappingURL=update-lock.js.map