@indigoai-us/hq-cli 5.345.225 → 5.345.228

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 (164) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/command-catalog.generated.d.ts +215 -0
  3. package/dist/command-catalog.generated.js +261 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +3 -3
  18. package/dist/commands/deploy-domains.js +38 -2
  19. package/dist/commands/index-cmd.d.ts +3 -1
  20. package/dist/commands/index-cmd.js +12 -0
  21. package/dist/commands/lanes-accounts.d.ts +14 -0
  22. package/dist/commands/lanes-accounts.js +119 -0
  23. package/dist/commands/lanes-checks.js +1 -1
  24. package/dist/commands/lanes-move.js +10 -0
  25. package/dist/commands/lanes-session-start.d.ts +1 -2
  26. package/dist/commands/lanes-session-start.js +9 -145
  27. package/dist/commands/lanes-shared.d.ts +3 -0
  28. package/dist/commands/lanes-shared.js +9 -0
  29. package/dist/commands/lanes.d.ts +3 -0
  30. package/dist/commands/lanes.js +231 -39
  31. package/dist/commands/link.d.ts +8 -3
  32. package/dist/commands/link.js +14 -17
  33. package/dist/commands/mcp-registration.d.ts +65 -7
  34. package/dist/commands/mcp-registration.js +289 -51
  35. package/dist/commands/mesh.d.ts +12 -0
  36. package/dist/commands/mesh.js +92 -10
  37. package/dist/commands/reindex.js +6 -0
  38. package/dist/commands/repo.d.ts +13 -0
  39. package/dist/commands/repo.js +39 -1
  40. package/dist/commands/sync-held.d.ts +22 -0
  41. package/dist/commands/sync-held.js +167 -18
  42. package/dist/commands/sync-mode.d.ts +3 -1
  43. package/dist/commands/sync-mode.js +11 -1
  44. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  45. package/dist/hq-cloud-sync-runner/package.json +1 -1
  46. package/dist/lazy-commands.js +3 -4
  47. package/dist/lib/capacity/accounts.d.ts +4 -0
  48. package/dist/lib/capacity/accounts.js +4 -0
  49. package/dist/lib/capacity/route.js +14 -0
  50. package/dist/lib/capacity/sign-in.d.ts +18 -0
  51. package/dist/lib/capacity/sign-in.js +34 -1
  52. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  53. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  54. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  55. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  56. package/dist/lib/core-utils/session-company.d.ts +13 -1
  57. package/dist/lib/core-utils/session-company.js +75 -4
  58. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  59. package/dist/lib/core-utils/worktree-resume.js +8 -4
  60. package/dist/lib/daemon/background-qos.d.ts +7 -0
  61. package/dist/lib/daemon/background-qos.js +13 -0
  62. package/dist/lib/daemon/catalog.d.ts +10 -0
  63. package/dist/lib/daemon/catalog.js +9 -2
  64. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  65. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  66. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  67. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  68. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  69. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  70. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  71. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  72. package/dist/lib/daemon/hook-requests.d.ts +417 -0
  73. package/dist/lib/daemon/hook-requests.js +1747 -0
  74. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  75. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  76. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  77. package/dist/lib/daemon/machine-checks.js +27 -10
  78. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  79. package/dist/lib/daemon/merge-sections.js +58 -16
  80. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  81. package/dist/lib/daemon/ops/policy.js +47 -6
  82. package/dist/lib/daemon/resolver.js +9 -2
  83. package/dist/lib/daemon/run.d.ts +11 -7
  84. package/dist/lib/daemon/run.js +195 -18
  85. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  86. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  87. package/dist/lib/daemon/server.js +6 -1
  88. package/dist/lib/daemon/session-registry.d.ts +0 -1
  89. package/dist/lib/daemon/session-registry.js +0 -3
  90. package/dist/lib/daemon/supervisor.d.ts +5 -1
  91. package/dist/lib/daemon/supervisor.js +1 -1
  92. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  93. package/dist/lib/daemon/tcc-eperm.js +110 -8
  94. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  95. package/dist/lib/doctor/fix/process-identity.js +48 -5
  96. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  97. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  98. package/dist/lib/hook-engine/canary-gate.js +1 -0
  99. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  100. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  101. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  102. package/dist/lib/lanes/account-company.d.ts +7 -1
  103. package/dist/lib/lanes/account-company.js +22 -4
  104. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  105. package/dist/lib/lanes/account-ownership.js +134 -0
  106. package/dist/lib/lanes/accounts.js +9 -2
  107. package/dist/lib/lanes/claude-balance.js +9 -3
  108. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  109. package/dist/lib/lanes/company-outposts.js +164 -0
  110. package/dist/lib/lanes/config.js +17 -0
  111. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  112. package/dist/lib/lanes/host-capacity.js +37 -0
  113. package/dist/lib/lanes/liveness.d.ts +6 -0
  114. package/dist/lib/lanes/liveness.js +49 -8
  115. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  116. package/dist/lib/lanes/orphan-report.js +223 -0
  117. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  118. package/dist/lib/lanes/orphan-sweep.js +152 -0
  119. package/dist/lib/lanes/reaper.d.ts +2 -0
  120. package/dist/lib/lanes/reaper.js +11 -8
  121. package/dist/lib/lanes/reconcile.d.ts +8 -7
  122. package/dist/lib/lanes/reconcile.js +83 -3
  123. package/dist/lib/lanes/spawn.d.ts +0 -10
  124. package/dist/lib/lanes/spawn.js +51 -1
  125. package/dist/lib/lanes/types.d.ts +12 -0
  126. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  127. package/dist/lib/mesh/live/backfill-held.js +23 -0
  128. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  129. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  130. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  131. package/dist/lib/mesh/live/daemon/run.js +116 -7
  132. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  133. package/dist/lib/mesh/live/direct-drain.js +315 -0
  134. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  135. package/dist/lib/mesh/live/emit-replay.js +10 -0
  136. package/dist/lib/mesh/live/flush.d.ts +15 -0
  137. package/dist/lib/mesh/live/flush.js +27 -0
  138. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  139. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  140. package/dist/lib/mesh/live/spool.d.ts +19 -0
  141. package/dist/lib/mesh/live/spool.js +80 -0
  142. package/dist/lib/safe-store.d.ts +2 -0
  143. package/dist/lib/safe-store.js +8 -6
  144. package/dist/lib/search-index/index.d.ts +9 -3
  145. package/dist/lib/search-index/index.js +35 -10
  146. package/dist/lib/search-index/worker-process.d.ts +9 -0
  147. package/dist/lib/search-index/worker-process.js +171 -0
  148. package/dist/lib/session-company-lock.d.ts +3 -1
  149. package/dist/lib/session-company-lock.js +3 -2
  150. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  151. package/dist/utils/delegate-command-supervisor.js +44 -0
  152. package/dist/utils/delegate-lock.d.ts +12 -0
  153. package/dist/utils/delegate-lock.js +88 -0
  154. package/dist/utils/frontmatter.d.ts +27 -0
  155. package/dist/utils/frontmatter.js +33 -0
  156. package/dist/utils/hook-trust.d.ts +1 -0
  157. package/dist/utils/hook-trust.js +18 -2
  158. package/dist/utils/host-registration.d.ts +13 -1
  159. package/dist/utils/host-registration.js +98 -5
  160. package/dist/utils/package-use-lease.d.ts +1 -1
  161. package/dist/utils/package-use-lease.js +15 -7
  162. package/docs/anywhere-runtime.md +17 -0
  163. package/package.json +9 -8
  164. package/scripts/check-function-manifest.mjs +17 -3
@@ -52,6 +52,7 @@
52
52
  * first-class skip), and {@link registerMcpServers} is the pack-install routing
53
53
  * seam over it.
54
54
  */
55
+ import * as path from 'path';
55
56
  /** Base for every MCP-registration error; carries a stable machine-checkable `code`. */
56
57
  export declare abstract class McpRegistrationError extends Error {
57
58
  abstract readonly code: string;
@@ -282,15 +283,58 @@ export declare function readConfigDoc<T>(target: string, format: ConfigFormat<T>
282
283
  * separate snippet block) cannot leak. The result never contains raw file content.
283
284
  */
284
285
  export declare function sanitizeParserMessage(message: string): string;
286
+ /**
287
+ * Default maximum hold time. A lock older than this is reclaimed even when its
288
+ * recorded PID still reports alive: the PID may have been reused by an unrelated
289
+ * process (routine on Windows), or the holder may be hung. A normal hold is one
290
+ * read, merge and write of a small config file, well under a second, and every
291
+ * waiter gives up after {@link DEFAULT_LOCK_WAIT_MS}; ten minutes is far above
292
+ * both. Sentry HQ-CLI-HQ: without this limit a `.claude.json.hqlock` naming a
293
+ * live PID blocked `hq install --global` for 20 hours.
294
+ */
295
+ export declare const DEFAULT_LOCK_MAX_HOLD_MS: number;
296
+ /** Env var that overrides {@link DEFAULT_LOCK_MAX_HOLD_MS} (whole milliseconds, > 0). */
297
+ export declare const CONFIG_LOCK_MAX_HOLD_ENV = "HQ_CONFIG_LOCK_MAX_HOLD_MS";
298
+ /**
299
+ * The smallest maximum hold time in force, one full wait of a waiting command
300
+ * ({@link DEFAULT_LOCK_WAIT_MS}). A smaller limit makes a live holder's lock
301
+ * reclaimable while it is still writing, which turns the lock off.
302
+ */
303
+ export declare const MIN_LOCK_MAX_HOLD_MS = 10000;
304
+ /**
305
+ * The largest maximum hold time in force, 7 days. A real hold lasts well under
306
+ * a second; a larger value would only keep a wedged lock longer, and a value
307
+ * past what a Date can hold would make the refusal's clear time unprintable.
308
+ */
309
+ export declare const MAX_LOCK_MAX_HOLD_MS: number;
285
310
  /** A held advisory lock; release with {@link releaseLock} (idempotent). */
286
311
  export interface ConfigLock {
287
312
  /** The lockfile path (`~/.<basename>.hqlock`). */
288
313
  lockPath: string;
314
+ /**
315
+ * The exact bytes this acquisition wrote. {@link releaseLock} removes the file
316
+ * only while it still holds these bytes, so a holder whose lock was reclaimed
317
+ * never deletes the next holder's lock.
318
+ */
319
+ body?: string;
289
320
  }
321
+ /**
322
+ * The maximum hold time in force: a valid explicit option, else a valid
323
+ * `HQ_CONFIG_LOCK_MAX_HOLD_MS`, else the default. An option that is not a
324
+ * finite number above zero, or an env value that is not a whole number of
325
+ * milliseconds above zero, is ignored. A valid value is kept between
326
+ * {@link MIN_LOCK_MAX_HOLD_MS} and {@link MAX_LOCK_MAX_HOLD_MS}.
327
+ */
328
+ export declare function resolveLockMaxHoldMs(explicit: number | undefined, env?: NodeJS.ProcessEnv): number;
290
329
  /** Options for {@link acquireLock} — overridable so tests can use tiny timeouts. */
291
330
  export interface AcquireLockOptions {
292
331
  /** Age beyond which a dead-PID lock is considered stale + breakable. */
293
332
  staleMs?: number;
333
+ /**
334
+ * Age beyond which a lock is reclaimed even if its PID reports alive. Defaults
335
+ * to `HQ_CONFIG_LOCK_MAX_HOLD_MS`, then {@link DEFAULT_LOCK_MAX_HOLD_MS}.
336
+ */
337
+ maxHoldMs?: number;
294
338
  /** Total time to spin waiting for a live lock before throwing. */
295
339
  waitMs?: number;
296
340
  /** Poll interval while waiting. */
@@ -299,9 +343,17 @@ export interface AcquireLockOptions {
299
343
  isPidAlive?: (pid: number) => boolean;
300
344
  /** Injectable clock (tests). */
301
345
  now?: () => number;
346
+ /**
347
+ * Injectable delete of a stale lock file (tests simulate a Windows handle
348
+ * that denies delete access). Defaults to `fs.unlinkSync`.
349
+ */
350
+ removeLockFile?: (lockPath: string) => void;
302
351
  }
303
- /** The lockfile path for a target: `~/.<basename>.hqlock` (a sibling, hidden). */
304
- export declare function lockPathFor(target: string): string;
352
+ /**
353
+ * The lockfile path for a target: `~/.<basename>.hqlock` (a sibling, hidden).
354
+ * `pathImpl` exists so the Windows form can be checked on any platform.
355
+ */
356
+ export declare function lockPathFor(target: string, pathImpl?: path.PlatformPath): string;
305
357
  /**
306
358
  * Acquire an advisory O_EXCL lock for `target`, held across the whole
307
359
  * read->merge->write cycle so a concurrent register cannot interleave and lose a
@@ -310,14 +362,20 @@ export declare function lockPathFor(target: string): string;
310
362
  * - `O_EXCL | O_CREAT` create-or-fail; on EEXIST another holder exists.
311
363
  * - A held lock whose PID is DEAD and whose mtime is older than `staleMs` is
312
364
  * broken (unlinked) and re-acquired.
313
- * - A held lock whose PID is ALIVE (or fresh) is waited on up to `waitMs`; if
314
- * it never frees, this throws (the concurrent register ABORTS rather than
315
- * racing — the first writer's work is preserved).
365
+ * - A held lock older than `maxHoldMs` is broken and re-acquired even when its
366
+ * PID reports alive (reused PID or hung holder).
367
+ * - A held lock whose PID is ALIVE inside `maxHoldMs` (or dead but fresh) is
368
+ * waited on up to `waitMs`; if it never frees, this throws (the concurrent
369
+ * register ABORTS rather than racing — the first writer's work is preserved).
316
370
  *
317
- * The lockfile body is the holder's PID + an ISO timestamp (diagnostic).
371
+ * The lockfile body is the holder's PID, an ISO timestamp, and a random token.
318
372
  */
319
373
  export declare function acquireLock(target: string, opts?: AcquireLockOptions): ConfigLock;
320
- /** Release a held lock. Idempotent — a missing lockfile is not an error. */
374
+ /**
375
+ * Release a held lock. Idempotent — a missing lockfile is not an error. The file
376
+ * is removed only while it still holds the bytes this acquisition wrote: after a
377
+ * reclaim the file at this path belongs to the next holder and is left alone.
378
+ */
321
379
  export declare function releaseLock(lock: ConfigLock): void;
322
380
  /** UTC `YYYY-MM-DDTHH-MM-SSZ` (dash-separated) — the hq rescue timestamp format. */
323
381
  export declare function rescueStamp(d?: Date): string;
@@ -365,18 +365,76 @@ export function sanitizeParserMessage(message) {
365
365
  // ---------------------------------------------------------------------------
366
366
  /** Default stale-lock timeout — a lock older than this whose PID is dead is broken. */
367
367
  const DEFAULT_LOCK_STALE_MS = 30_000;
368
+ /**
369
+ * Default maximum hold time. A lock older than this is reclaimed even when its
370
+ * recorded PID still reports alive: the PID may have been reused by an unrelated
371
+ * process (routine on Windows), or the holder may be hung. A normal hold is one
372
+ * read, merge and write of a small config file, well under a second, and every
373
+ * waiter gives up after {@link DEFAULT_LOCK_WAIT_MS}; ten minutes is far above
374
+ * both. Sentry HQ-CLI-HQ: without this limit a `.claude.json.hqlock` naming a
375
+ * live PID blocked `hq install --global` for 20 hours.
376
+ */
377
+ export const DEFAULT_LOCK_MAX_HOLD_MS = 10 * 60_000;
378
+ /** Env var that overrides {@link DEFAULT_LOCK_MAX_HOLD_MS} (whole milliseconds, > 0). */
379
+ export const CONFIG_LOCK_MAX_HOLD_ENV = 'HQ_CONFIG_LOCK_MAX_HOLD_MS';
380
+ /**
381
+ * The smallest maximum hold time in force, one full wait of a waiting command
382
+ * ({@link DEFAULT_LOCK_WAIT_MS}). A smaller limit makes a live holder's lock
383
+ * reclaimable while it is still writing, which turns the lock off.
384
+ */
385
+ export const MIN_LOCK_MAX_HOLD_MS = 10_000;
386
+ /**
387
+ * The largest maximum hold time in force, 7 days. A real hold lasts well under
388
+ * a second; a larger value would only keep a wedged lock longer, and a value
389
+ * past what a Date can hold would make the refusal's clear time unprintable.
390
+ */
391
+ export const MAX_LOCK_MAX_HOLD_MS = 7 * 24 * 60 * 60_000;
392
+ /** How long a `.takeover` claim is honoured before a later breaker clears it. */
393
+ const TAKEOVER_CLAIM_TTL_MS = 30_000;
368
394
  /** Default total time to wait for a held lock before giving up. */
369
395
  const DEFAULT_LOCK_WAIT_MS = 10_000;
370
- /** The lockfile path for a target: `~/.<basename>.hqlock` (a sibling, hidden). */
371
- export function lockPathFor(target) {
372
- const dir = path.dirname(target);
373
- const base = path.basename(target);
396
+ /**
397
+ * Locks this process holds right now: lock path -> the body it wrote. A lock
398
+ * file naming `process.pid` whose body is not in this map was written by an
399
+ * earlier process that had the same PID, so its holder is gone.
400
+ */
401
+ const locksHeldHere = new Map();
402
+ /**
403
+ * The maximum hold time in force: a valid explicit option, else a valid
404
+ * `HQ_CONFIG_LOCK_MAX_HOLD_MS`, else the default. An option that is not a
405
+ * finite number above zero, or an env value that is not a whole number of
406
+ * milliseconds above zero, is ignored. A valid value is kept between
407
+ * {@link MIN_LOCK_MAX_HOLD_MS} and {@link MAX_LOCK_MAX_HOLD_MS}.
408
+ */
409
+ export function resolveLockMaxHoldMs(explicit, env = process.env) {
410
+ const bound = (ms) => Math.min(Math.max(ms, MIN_LOCK_MAX_HOLD_MS), MAX_LOCK_MAX_HOLD_MS);
411
+ if (explicit !== undefined && Number.isFinite(explicit) && explicit > 0)
412
+ return bound(explicit);
413
+ const raw = env[CONFIG_LOCK_MAX_HOLD_ENV]?.trim() ?? '';
414
+ if (/^\d+$/.test(raw)) {
415
+ const parsed = Number(raw);
416
+ if (Number.isSafeInteger(parsed) && parsed > 0)
417
+ return bound(parsed);
418
+ }
419
+ return DEFAULT_LOCK_MAX_HOLD_MS;
420
+ }
421
+ /**
422
+ * The lockfile path for a target: `~/.<basename>.hqlock` (a sibling, hidden).
423
+ * `pathImpl` exists so the Windows form can be checked on any platform.
424
+ */
425
+ export function lockPathFor(target, pathImpl = path) {
426
+ const dir = pathImpl.dirname(target);
427
+ const base = pathImpl.basename(target);
374
428
  // `~/.claude.json` -> `~/..claude.json.hqlock` is ugly; collapse a leading dot
375
429
  // so the lock for a dotfile reads `~/.claude.json.hqlock`.
376
430
  const stem = base.startsWith('.') ? base.slice(1) : base;
377
- return path.join(dir, `.${stem}.hqlock`);
431
+ return pathImpl.join(dir, `.${stem}.hqlock`);
378
432
  }
379
- /** Default PID-liveness check (Unix `kill(pid, 0)` semantics via `process.kill`). */
433
+ /**
434
+ * Default PID-liveness check (`process.kill(pid, 0)`). It reports whether SOME
435
+ * process has that PID, not whether it is the process that wrote the lock;
436
+ * Windows reuses PIDs quickly. The maximum hold time covers a reused PID.
437
+ */
380
438
  function defaultIsPidAlive(pid) {
381
439
  if (!Number.isInteger(pid) || pid <= 0)
382
440
  return false;
@@ -397,21 +455,25 @@ function defaultIsPidAlive(pid) {
397
455
  * - `O_EXCL | O_CREAT` create-or-fail; on EEXIST another holder exists.
398
456
  * - A held lock whose PID is DEAD and whose mtime is older than `staleMs` is
399
457
  * broken (unlinked) and re-acquired.
400
- * - A held lock whose PID is ALIVE (or fresh) is waited on up to `waitMs`; if
401
- * it never frees, this throws (the concurrent register ABORTS rather than
402
- * racing — the first writer's work is preserved).
458
+ * - A held lock older than `maxHoldMs` is broken and re-acquired even when its
459
+ * PID reports alive (reused PID or hung holder).
460
+ * - A held lock whose PID is ALIVE inside `maxHoldMs` (or dead but fresh) is
461
+ * waited on up to `waitMs`; if it never frees, this throws (the concurrent
462
+ * register ABORTS rather than racing — the first writer's work is preserved).
403
463
  *
404
- * The lockfile body is the holder's PID + an ISO timestamp (diagnostic).
464
+ * The lockfile body is the holder's PID, an ISO timestamp, and a random token.
405
465
  */
406
466
  export function acquireLock(target, opts = {}) {
407
467
  const lockPath = lockPathFor(target);
408
468
  const staleMs = opts.staleMs ?? DEFAULT_LOCK_STALE_MS;
469
+ const maxHoldMs = resolveLockMaxHoldMs(opts.maxHoldMs);
409
470
  const waitMs = opts.waitMs ?? DEFAULT_LOCK_WAIT_MS;
410
471
  const pollMs = opts.pollMs ?? 50;
411
472
  const isPidAlive = opts.isPidAlive ?? defaultIsPidAlive;
412
473
  const now = opts.now ?? Date.now;
474
+ const removeLockFile = opts.removeLockFile ?? fs.unlinkSync;
413
475
  const deadline = now() + waitMs;
414
- const body = `${process.pid}\n${new Date().toISOString()}\n`;
476
+ const body = `${process.pid}\n${new Date().toISOString()}\n${crypto.randomBytes(8).toString('hex')}\n`;
415
477
  // Spin until we win the O_EXCL create, break a stale lock, or time out.
416
478
  for (;;) {
417
479
  try {
@@ -422,7 +484,8 @@ export function acquireLock(target, opts = {}) {
422
484
  finally {
423
485
  fs.closeSync(fd);
424
486
  }
425
- return { lockPath };
487
+ locksHeldHere.set(lockPath, body);
488
+ return { lockPath, body };
426
489
  }
427
490
  catch (e) {
428
491
  const err = e;
@@ -431,20 +494,120 @@ export function acquireLock(target, opts = {}) {
431
494
  throw new ConfigPermissionError(`cannot acquire lock ${lockPath}: ${err.code ?? 'open error'} (${err.message})`);
432
495
  }
433
496
  // EEXIST: a lock is held. Decide stale-break vs wait.
434
- if (tryBreakStaleLock(lockPath, staleMs, isPidAlive, now)) {
497
+ if (tryBreakStaleLock(lockPath, { staleMs, maxHoldMs, isPidAlive, now, removeLockFile })) {
435
498
  continue; // broke it — retry the create immediately.
436
499
  }
437
500
  if (now() >= deadline) {
438
- const holder = readLockHolder(lockPath);
439
- throw new ConfigPermissionError(`config ${target} is locked by ${holder} and did not release within ${waitMs}ms; ` +
440
- 'aborting rather than racing a concurrent registration (the in-flight write is preserved).');
501
+ throw lockRefusal(target, lockPath, waitMs, { staleMs, maxHoldMs, isPidAlive, now });
441
502
  }
442
503
  sleepMs(pollMs);
443
504
  }
444
505
  }
445
506
  }
446
- /** Release a held lock. Idempotent — a missing lockfile is not an error. */
507
+ /**
508
+ * The refusal a waiting command throws when the lock never freed. It never tells
509
+ * the user to delete the lock file: deleting it under a hung holder lets two
510
+ * writers run, and the lock clears itself.
511
+ *
512
+ * The clear time is the lock's mtime plus the limit that applies to its holder:
513
+ * `staleMs` for a dead holder, `maxHoldMs` for a live one. When that time is not
514
+ * in the future the lock is already reclaimable, so it is still here only
515
+ * because deleting it failed (on Windows, another program has the file open
516
+ * without delete sharing). Printing that past time would be false, so the
517
+ * message says the lock clears once that program closes the file.
518
+ */
519
+ function lockRefusal(target, lockPath, waitMs, opts) {
520
+ const holder = readLockHolder(lockPath);
521
+ const head = `config ${target} is locked by ${holder} and did not release within ${waitMs}ms, ` +
522
+ 'so nothing was written. ';
523
+ let mtimeMs;
524
+ let body;
525
+ try {
526
+ mtimeMs = fs.statSync(lockPath).mtimeMs;
527
+ body = fs.readFileSync(lockPath, 'utf-8');
528
+ }
529
+ catch (e) {
530
+ const code = e.code ?? 'read error';
531
+ if (code === 'ENOENT' && !lockPathExists(lockPath)) {
532
+ // The holder released the lock after the last attempt.
533
+ return new ConfigPermissionError(head + `The lock ${lockPath} was released just now. Run this command again.`);
534
+ }
535
+ // The lock is there but this user cannot read it (for example it was left
536
+ // by an hq run as root, the path is a directory, or it is a symlink whose
537
+ // target is missing). hq cannot judge its holder or age, so it never clears it.
538
+ // On Windows, EBUSY or EPERM on a read is a sharing violation, not ownership.
539
+ const sharing = process.platform === 'win32' && (code === 'EBUSY' || code === 'EPERM');
540
+ return new ConfigPermissionError(head +
541
+ `The lock ${lockPath} could not be read (${code}), so hq cannot tell whether it ` +
542
+ 'is still held and will not clear it by itself. ' +
543
+ (sharing
544
+ ? 'Another program has the file open; run this command again once it closes it.'
545
+ : 'It may belong to another user (for example an hq command run as root) or not ' +
546
+ 'be a regular file. Make it readable by your user, then run this command again.'));
547
+ }
548
+ const limitMs = lockHolderAlive(lockPath, body, opts.isPidAlive)
549
+ ? opts.maxHoldMs
550
+ : Math.min(opts.staleMs, opts.maxHoldMs);
551
+ const clearsAtMs = mtimeMs + limitMs;
552
+ // The same age rule as tryBreakStaleLock: distance from now in either
553
+ // direction, so a lock dated more than one limit in the future is past it too.
554
+ if (Math.abs(opts.now() - mtimeMs) >= limitMs) {
555
+ return new ConfigPermissionError(head +
556
+ `The lock ${lockPath} is past its limit of ${describeDuration(limitMs)}, but another ` +
557
+ 'program has the file open, so hq cannot clear it yet. hq will clear it by itself ' +
558
+ 'once that program closes it; run this command again then.');
559
+ }
560
+ return new ConfigPermissionError(head +
561
+ `Another hq command holds the lock ${lockPath} and is probably still updating that ` +
562
+ 'file: wait for it to finish, then run this command again. hq clears this lock by ' +
563
+ `itself once it is ${describeDuration(limitMs)} old, so hq will clear it by itself at ` +
564
+ `${new Date(clearsAtMs).toISOString()}; run this command again then.`);
565
+ }
566
+ /**
567
+ * Whether the holder of the lock whose bytes are `body` is alive. Our own PID
568
+ * on a lock this process did not write is a reused PID: the process that wrote
569
+ * it has exited, so no liveness question is needed.
570
+ */
571
+ function lockHolderAlive(lockPath, body, isPidAlive) {
572
+ const pid = parseLockPid(body);
573
+ return pid === process.pid
574
+ ? locksHeldHere.get(lockPath) === body
575
+ : Number.isFinite(pid) && isPidAlive(pid);
576
+ }
577
+ /** `600000` -> `10 minutes`; whole days, hours, minutes or seconds, else ms. */
578
+ function describeDuration(ms) {
579
+ const plural = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'}`;
580
+ if (ms >= 86_400_000 && ms % 86_400_000 === 0)
581
+ return plural(ms / 86_400_000, 'day');
582
+ if (ms >= 3_600_000 && ms % 3_600_000 === 0)
583
+ return plural(ms / 3_600_000, 'hour');
584
+ if (ms >= 60_000 && ms % 60_000 === 0)
585
+ return plural(ms / 60_000, 'minute');
586
+ if (ms >= 1000 && ms % 1000 === 0)
587
+ return plural(ms / 1000, 'second');
588
+ return `${ms} ms`;
589
+ }
590
+ /**
591
+ * Release a held lock. Idempotent — a missing lockfile is not an error. The file
592
+ * is removed only while it still holds the bytes this acquisition wrote: after a
593
+ * reclaim the file at this path belongs to the next holder and is left alone.
594
+ */
447
595
  export function releaseLock(lock) {
596
+ if (lock.body !== undefined) {
597
+ if (locksHeldHere.get(lock.lockPath) === lock.body)
598
+ locksHeldHere.delete(lock.lockPath);
599
+ let current;
600
+ try {
601
+ current = fs.readFileSync(lock.lockPath, 'utf-8');
602
+ }
603
+ catch (e) {
604
+ if (e.code === 'ENOENT')
605
+ return;
606
+ throw e;
607
+ }
608
+ if (current !== lock.body)
609
+ return; // reclaimed: not ours to remove.
610
+ }
448
611
  try {
449
612
  fs.unlinkSync(lock.lockPath);
450
613
  }
@@ -453,15 +616,47 @@ export function releaseLock(lock) {
453
616
  throw e;
454
617
  }
455
618
  }
456
- /** Read the PID written into a lockfile, or NaN if unreadable/garbage. */
457
- function readLockPid(lockPath) {
458
- try {
459
- const first = fs.readFileSync(lockPath, 'utf-8').split('\n', 1)[0]?.trim() ?? '';
460
- return Number.parseInt(first, 10);
461
- }
462
- catch {
463
- return Number.NaN;
619
+ /** The PID on the first line of a lock body, or NaN if it is garbage. */
620
+ function parseLockPid(body) {
621
+ const first = body.split('\n', 1)[0]?.trim() ?? '';
622
+ return /^\d+$/.test(first) ? Number.parseInt(first, 10) : Number.NaN;
623
+ }
624
+ /**
625
+ * Take the `.takeover` claim that serialises lock breakers. Only the claim
626
+ * holder may remove a stale lock, so two breakers can never both judge the same
627
+ * stale lock and have the slower one unlink the fresh lock the faster one just
628
+ * created. The claim is held for a stat, a read and an unlink; one left behind
629
+ * by a breaker that died is cleared after {@link TAKEOVER_CLAIM_TTL_MS}.
630
+ */
631
+ function claimTakeover(claimPath, now) {
632
+ for (let attempt = 0; attempt < 2; attempt++) {
633
+ try {
634
+ const fd = fs.openSync(claimPath, 'wx', 0o600);
635
+ try {
636
+ fs.writeSync(fd, `${process.pid}\n`);
637
+ }
638
+ finally {
639
+ fs.closeSync(fd);
640
+ }
641
+ return true;
642
+ }
643
+ catch (e) {
644
+ if (e.code !== 'EEXIST')
645
+ return false;
646
+ }
647
+ try {
648
+ const age = Math.abs(now() - fs.statSync(claimPath).mtimeMs);
649
+ if (age < TAKEOVER_CLAIM_TTL_MS)
650
+ return false; // a breaker is at work — wait.
651
+ fs.unlinkSync(claimPath);
652
+ }
653
+ catch (e) {
654
+ // ENOENT => the other breaker just finished; try the create once more.
655
+ if (e.code !== 'ENOENT')
656
+ return false;
657
+ }
464
658
  }
659
+ return false;
465
660
  }
466
661
  /** A human-readable "pid N (since …)" description of the current lock holder. */
467
662
  function readLockHolder(lockPath) {
@@ -474,12 +669,20 @@ function readLockHolder(lockPath) {
474
669
  }
475
670
  }
476
671
  /**
477
- * If the lock at `lockPath` is stale (holder PID dead AND mtime older than
478
- * `staleMs`), unlink it and return true. Otherwise return false. A dead PID with
479
- * a FRESH mtime is NOT broken (the holder may have just started and not yet
480
- * recorded a live PID under our liveness check), guarding against TOCTOU.
672
+ * If the lock at `lockPath` is stale, unlink it and return true; otherwise
673
+ * return false. Stale means either:
674
+ *
675
+ * - the holder PID is dead AND the lock is older than `staleMs` (a dead PID
676
+ * with a FRESH mtime is NOT broken: the holder may have just started and not
677
+ * yet be visible to the liveness check), or
678
+ * - the lock is older than `maxHoldMs`, whatever the liveness check says.
679
+ *
680
+ * Age is the distance between now and the lock's mtime in either direction, so a
681
+ * clock that moved backwards cannot leave a lock with a negative age that never
682
+ * expires.
481
683
  */
482
- function tryBreakStaleLock(lockPath, staleMs, isPidAlive, now) {
684
+ function tryBreakStaleLock(lockPath, opts) {
685
+ const { staleMs, maxHoldMs, isPidAlive, now, removeLockFile } = opts;
483
686
  let st;
484
687
  let originalBody;
485
688
  try {
@@ -491,25 +694,34 @@ function tryBreakStaleLock(lockPath, staleMs, isPidAlive, now) {
491
694
  // inspected and unlink it (passes on macOS, fails on Linux CI).
492
695
  originalBody = fs.readFileSync(lockPath, 'utf-8');
493
696
  }
494
- catch {
495
- // Vanished between EEXIST and here — the create will now succeed.
496
- return true;
497
- }
498
- const age = now() - st.mtimeMs;
499
- const pid = readLockPid(lockPath);
500
- const holderAlive = Number.isFinite(pid) && isPidAlive(pid);
501
- if (holderAlive)
502
- return false; // live holder — must wait, never steal.
503
- if (age < staleMs)
504
- return false; // dead PID but fresh — be conservative, wait.
505
- // Dead holder + stale mtime: break it — but IDENTITY-SAFELY. `unlinkSync(path)`
506
- // is not atomic with the stat/read that justified breaking it: between them a
507
- // third contender may have removed the stale lock and created a FRESH, valid
508
- // one at the same path (and, on Linux, the same recycled inode). Re-read and
509
- // require BOTH (inode+dev) AND the exact body to still match before unlinking,
510
- // so we only ever remove the precise stale lock we inspected — never an
511
- // unrelated fresh one. (The O_EXCL re-create is still the true mutual-exclusion
512
- // guard; this just prevents a spurious break of someone else's lock.)
697
+ catch (e) {
698
+ // ENOENT with nothing at the path: vanished between EEXIST and here — the
699
+ // create will now succeed. ENOENT while the path itself still exists is a
700
+ // symlink whose target is missing (O_EXCL refuses it with EEXIST), and any
701
+ // other error (EACCES on a lock another user left, such as one written by an
702
+ // hq run as root; EISDIR when the lock path is a directory) means the lock is
703
+ // there but cannot be judged. It is not broken, and returning false lets the
704
+ // caller poll to its deadline and refuse instead of spinning forever.
705
+ return e.code === 'ENOENT' && !lockPathExists(lockPath);
706
+ }
707
+ const age = Math.abs(now() - st.mtimeMs);
708
+ if (age < maxHoldMs) {
709
+ if (lockHolderAlive(lockPath, originalBody, isPidAlive))
710
+ return false; // live holder inside the hold limit — wait, never steal.
711
+ if (age < staleMs)
712
+ return false; // dead PID but fresh — be conservative, wait.
713
+ }
714
+ // Stale: break it — but only the exact lock we judged, and only as the one
715
+ // breaker holding the takeover claim. `unlinkSync(path)` is not atomic with the
716
+ // stat/read that justified it: between them another contender may have removed
717
+ // the stale lock and created a FRESH, valid one at the same path (and, on
718
+ // Linux, the same recycled inode). The claim keeps other breakers out of that
719
+ // window; the re-read under the claim requires BOTH (inode+dev) AND the exact
720
+ // body to still match, so we only ever remove the precise stale lock we
721
+ // inspected. (The O_EXCL re-create is still the true mutual-exclusion guard.)
722
+ const claimPath = `${lockPath}.takeover`;
723
+ if (!claimTakeover(claimPath, now))
724
+ return false;
513
725
  try {
514
726
  const recheck = fs.statSync(lockPath);
515
727
  const currentBody = fs.readFileSync(lockPath, 'utf-8');
@@ -519,15 +731,41 @@ function tryBreakStaleLock(lockPath, staleMs, isPidAlive, now) {
519
731
  // The lock at this path is no longer the one we judged stale — leave it.
520
732
  return false;
521
733
  }
522
- fs.unlinkSync(lockPath);
734
+ removeLockFile(lockPath);
523
735
  }
524
736
  catch (e) {
525
- // ENOENT => already gone (a concurrent breaker won); the create will succeed.
737
+ // ENOENT => already gone (the holder released it); the create will succeed.
738
+ // Anything else (on Windows, EPERM or EBUSY while another handle has the
739
+ // file open) leaves the lock in place; the caller polls and tries again.
526
740
  if (e.code !== 'ENOENT')
527
741
  return false;
528
742
  }
743
+ finally {
744
+ try {
745
+ fs.unlinkSync(claimPath);
746
+ }
747
+ catch {
748
+ // Already gone, or briefly undeletable; the claim TTL clears it later.
749
+ }
750
+ }
529
751
  return true;
530
752
  }
753
+ /**
754
+ * Whether anything is at `lockPath` itself, without following a symlink. A
755
+ * symlink whose target is missing makes stat and read fail with ENOENT while the
756
+ * link still blocks the O_EXCL create.
757
+ */
758
+ function lockPathExists(lockPath) {
759
+ try {
760
+ fs.lstatSync(lockPath);
761
+ return true;
762
+ }
763
+ catch {
764
+ // ENOENT (gone) or the parent cannot be searched; either way there is
765
+ // nothing here this process can judge, and the create reports a real error.
766
+ return false;
767
+ }
768
+ }
531
769
  /** Busy-sleep for `ms` (small poll intervals only — bounded by the wait deadline). */
532
770
  function sleepMs(ms) {
533
771
  const end = Date.now() + ms;
@@ -1,6 +1,7 @@
1
1
  import { Command } from "commander";
2
2
  import { type MeshCompany, type MeshProjectRepo, type MeshProjectStoryInput, type MeshThread } from "../lib/mesh/api.js";
3
3
  import { UnknownProjectStoryStateError } from "../lib/mesh/story-status.js";
4
+ import type { SessionEventKind } from "../lib/mesh/live/format-spool-line.js";
4
5
  import { type DaemonInstallPlatform, type InstallPaths } from "../lib/mesh/live/daemon/install.js";
5
6
  import { type RunCommand } from "../lib/service-manager/launchd.js";
6
7
  export declare function formatCheckLines(threads: MeshThread[], company: MeshCompany, projectId?: string): string[];
@@ -61,6 +62,17 @@ export declare function runContextCorrect(opts: {
61
62
  }, deps?: {
62
63
  confirm?: MeshConfirmFn;
63
64
  }): Promise<void>;
65
+ /**
66
+ * Whether `hq mesh session <verb>` appends to the spool instead of posting.
67
+ * Only a hook-tracked session (one with a local session state file) goes to
68
+ * the spool: the drain needs that state to deliver the line. For such a
69
+ * session `--enqueue` always appends (no network) and the lifecycle kinds do
70
+ * with or without it. A session with no local state (the lane runner,
71
+ * hq-delegate-transfer.sh) keeps the old direct post, even with `--enqueue`,
72
+ * so its delivery and flags are exactly as before. A hand-run task-status,
73
+ * blocked or note without `--enqueue` still posts directly.
74
+ */
75
+ export declare function sessionEventGoesToSpool(kind: SessionEventKind, enqueue: boolean | undefined, hasLocalState: boolean): boolean;
64
76
  export declare function registerMeshCommand(program: Command, deps?: {
65
77
  defaultCompanyPrompt?: DefaultCompanyPromptDeps;
66
78
  }): void;