@indigoai-us/hq-cli 5.345.226 → 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 (132) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/command-catalog.generated.d.ts +137 -0
  3. package/dist/command-catalog.generated.js +164 -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 +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/lazy-commands.js +3 -4
  38. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  39. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  40. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  41. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  42. package/dist/lib/core-utils/session-company.d.ts +13 -1
  43. package/dist/lib/core-utils/session-company.js +75 -4
  44. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  45. package/dist/lib/core-utils/worktree-resume.js +8 -4
  46. package/dist/lib/daemon/background-qos.d.ts +7 -0
  47. package/dist/lib/daemon/background-qos.js +13 -0
  48. package/dist/lib/daemon/catalog.d.ts +9 -0
  49. package/dist/lib/daemon/catalog.js +8 -1
  50. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  51. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  52. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  53. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  54. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  55. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  56. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  57. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  58. package/dist/lib/daemon/hook-requests.d.ts +349 -8
  59. package/dist/lib/daemon/hook-requests.js +1312 -46
  60. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  61. package/dist/lib/daemon/machine-checks.js +27 -10
  62. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  63. package/dist/lib/daemon/merge-sections.js +58 -16
  64. package/dist/lib/daemon/ops/policy.js +4 -2
  65. package/dist/lib/daemon/resolver.js +9 -2
  66. package/dist/lib/daemon/run.d.ts +11 -7
  67. package/dist/lib/daemon/run.js +168 -24
  68. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  69. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  70. package/dist/lib/daemon/session-registry.d.ts +0 -1
  71. package/dist/lib/daemon/session-registry.js +0 -3
  72. package/dist/lib/daemon/supervisor.d.ts +3 -1
  73. package/dist/lib/daemon/supervisor.js +1 -1
  74. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  75. package/dist/lib/daemon/tcc-eperm.js +110 -8
  76. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  77. package/dist/lib/doctor/fix/process-identity.js +48 -5
  78. package/dist/lib/hook-engine/canary-gate.js +1 -0
  79. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  80. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  81. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  82. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  83. package/dist/lib/lanes/company-outposts.js +164 -0
  84. package/dist/lib/lanes/liveness.d.ts +6 -0
  85. package/dist/lib/lanes/liveness.js +49 -8
  86. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  87. package/dist/lib/lanes/orphan-report.js +223 -0
  88. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  89. package/dist/lib/lanes/orphan-sweep.js +152 -0
  90. package/dist/lib/lanes/reaper.d.ts +2 -0
  91. package/dist/lib/lanes/reaper.js +11 -8
  92. package/dist/lib/lanes/reconcile.d.ts +8 -7
  93. package/dist/lib/lanes/reconcile.js +39 -0
  94. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  95. package/dist/lib/mesh/live/backfill-held.js +23 -0
  96. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  97. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  98. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  99. package/dist/lib/mesh/live/daemon/run.js +116 -7
  100. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  101. package/dist/lib/mesh/live/direct-drain.js +315 -0
  102. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  103. package/dist/lib/mesh/live/emit-replay.js +10 -0
  104. package/dist/lib/mesh/live/flush.d.ts +15 -0
  105. package/dist/lib/mesh/live/flush.js +27 -0
  106. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  107. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  108. package/dist/lib/mesh/live/spool.d.ts +19 -0
  109. package/dist/lib/mesh/live/spool.js +80 -0
  110. package/dist/lib/safe-store.d.ts +2 -0
  111. package/dist/lib/safe-store.js +8 -6
  112. package/dist/lib/search-index/index.d.ts +9 -3
  113. package/dist/lib/search-index/index.js +35 -10
  114. package/dist/lib/search-index/worker-process.d.ts +9 -0
  115. package/dist/lib/search-index/worker-process.js +171 -0
  116. package/dist/lib/session-company-lock.d.ts +3 -1
  117. package/dist/lib/session-company-lock.js +3 -2
  118. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  119. package/dist/utils/delegate-command-supervisor.js +44 -0
  120. package/dist/utils/delegate-lock.d.ts +12 -0
  121. package/dist/utils/delegate-lock.js +88 -0
  122. package/dist/utils/frontmatter.d.ts +27 -0
  123. package/dist/utils/frontmatter.js +33 -0
  124. package/dist/utils/hook-trust.d.ts +1 -0
  125. package/dist/utils/hook-trust.js +18 -2
  126. package/dist/utils/host-registration.d.ts +13 -1
  127. package/dist/utils/host-registration.js +98 -5
  128. package/dist/utils/package-use-lease.d.ts +1 -1
  129. package/dist/utils/package-use-lease.js +15 -7
  130. package/docs/anywhere-runtime.md +17 -0
  131. package/package.json +8 -7
  132. package/scripts/check-function-manifest.mjs +17 -3
@@ -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;
@@ -24,8 +24,8 @@ import { ensureDefaultCompany } from "../lib/work-context/default-company.js";
24
24
  import { cognitoSubFromTokens } from "../lib/work-context/person-identity.js";
25
25
  import { DefaultCompanyUnavailableError, WorkContextError, } from "../lib/work-context/errors.js";
26
26
  import { isValidSessionId } from "../lib/mesh/live/session-identity.js";
27
- import { flushSessionEvents } from "../lib/mesh/live/flush.js";
28
- import { backfillHeldSessions } from "../lib/mesh/live/backfill-held.js";
27
+ import { flushForEmitMode } from "../lib/mesh/live/direct-drain.js";
28
+ import { backfillHeldSessionsForMode, HeldBackfillRefusedError } from "../lib/mesh/live/backfill-held.js";
29
29
  import { createSessionEventsPoster, resolveVaultApiBase, } from "../lib/mesh/live/session-events-client.js";
30
30
  const ONLINE_MEMBERSHIP_VALIDATION_TIMEOUT_MS = 5_000;
31
31
  // Leave 500 ms of headroom inside SessionStart's 2 s process-group limit.
@@ -37,7 +37,7 @@ import { enrichSessionEndEvent } from "../lib/mesh/live/report-summary.js";
37
37
  import { emitEvents, formatEmitRejectionLines } from "../lib/mesh/live/emit.js";
38
38
  import { readEmitRetry, writeEmitRetry } from "../lib/mesh/live/emit-retry.js";
39
39
  import { generateUlid } from "../lib/mesh/live/ulid.js";
40
- import { readLegacyBacklog } from "../lib/mesh/live/emit-replay.js";
40
+ import { readLegacyBacklogForMode } from "../lib/mesh/live/emit-replay.js";
41
41
  import { resolveMeshEmitMode, writeMeshConfigMode, } from "../lib/mesh/live/daemon/mode.js";
42
42
  import { workMeshRoot } from "../lib/mesh/live/paths.js";
43
43
  import { buildInstallPaths, daemonServiceIsLoaded, daemonServiceStatus, detectPlatform, installDaemonIfStale, installDaemonService, resolveAbsoluteNodeBinary, resolveRunningCliEntry, uninstallDaemonService, installedUnitHqRoot, } from "../lib/mesh/live/daemon/install.js";
@@ -1611,6 +1611,11 @@ async function runContextBackfillHeld(opts) {
1611
1611
  const root = workContextHomeRoot();
1612
1612
  const meshRoot = workMeshRoot(undefined, process.env);
1613
1613
  const dryRun = Boolean(opts.dryRun);
1614
+ // Direct mode refuses a real run before a token is fetched or anything is
1615
+ // read: exit 1 with the reason (US-038, owner decision 70).
1616
+ const emitMode = resolveMeshEmitMode({ env: process.env, meshRoot });
1617
+ if (emitMode === "direct" && !dryRun)
1618
+ fail(new HeldBackfillRefusedError().message);
1614
1619
  const parsedLimit = opts.limit ? Number.parseInt(opts.limit, 10) : 0;
1615
1620
  const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : 0;
1616
1621
  const companyHint = opts.company?.trim() || undefined;
@@ -1643,7 +1648,7 @@ async function runContextBackfillHeld(opts) {
1643
1648
  }
1644
1649
  }
1645
1650
  }
1646
- const result = await backfillHeldSessions({
1651
+ const result = await backfillHeldSessionsForMode(emitMode, {
1647
1652
  workMeshRoot: meshRoot,
1648
1653
  workContextRoot: root,
1649
1654
  hqRoot: process.env.HQ_ROOT?.trim() || findHqRoot(),
@@ -2441,14 +2446,41 @@ const HARNESSES = new Set([
2441
2446
  "agent-box",
2442
2447
  "agents-v2",
2443
2448
  ]);
2449
+ /**
2450
+ * Session lifecycle events: a hook or lane runner reports these, and they go
2451
+ * through the spool only (US-038 c1). The daemon delivers the spool.
2452
+ */
2453
+ const SPOOL_ONLY_SESSION_KINDS = new Set([
2454
+ "session_start",
2455
+ "turn_start",
2456
+ "turn_end",
2457
+ "session_end",
2458
+ ]);
2459
+ /**
2460
+ * Whether `hq mesh session <verb>` appends to the spool instead of posting.
2461
+ * Only a hook-tracked session (one with a local session state file) goes to
2462
+ * the spool: the drain needs that state to deliver the line. For such a
2463
+ * session `--enqueue` always appends (no network) and the lifecycle kinds do
2464
+ * with or without it. A session with no local state (the lane runner,
2465
+ * hq-delegate-transfer.sh) keeps the old direct post, even with `--enqueue`,
2466
+ * so its delivery and flags are exactly as before. A hand-run task-status,
2467
+ * blocked or note without `--enqueue` still posts directly.
2468
+ */
2469
+ export function sessionEventGoesToSpool(kind, enqueue, hasLocalState) {
2470
+ if (!hasLocalState)
2471
+ return false;
2472
+ return enqueue === true || SPOOL_ONLY_SESSION_KINDS.has(kind);
2473
+ }
2444
2474
  function workMeshHomeRoot() {
2445
2475
  return workMeshRoot(os.homedir(), process.env);
2446
2476
  }
2447
2477
  async function runSessionEnqueue(cliKind, opts) {
2448
2478
  const { CLI_KIND_TO_SCHEMA, resolveEnqueueSessionId } = await import("../lib/mesh/live/enqueue.js");
2449
- // `--enqueue` is retained for hook back-compat but now means "emit directly"
2450
- // (owner decision 2026-09-08: sessions POST events to the server over HTTPS;
2451
- // no local spool/daemon on the emit path).
2479
+ // US-038 c1: a hook-tracked session's events go through the spool only.
2480
+ // `--enqueue` and the lifecycle kinds append one spool line (no token, no
2481
+ // network) and the daemon delivers it. A session with no local state keeps
2482
+ // the 2026-09-08 direct post (see sessionEventGoesToSpool), as does a
2483
+ // hand-run task-status, blocked or note without `--enqueue`.
2452
2484
  const kind = CLI_KIND_TO_SCHEMA[cliKind];
2453
2485
  if (!kind)
2454
2486
  fail(`Unknown session verb: ${cliKind}`);
@@ -2480,6 +2512,48 @@ async function runSessionEnqueue(cliKind, opts) {
2480
2512
  /* prompt rebind is fail-soft */
2481
2513
  }
2482
2514
  }
2515
+ const hasLocalState = readSessionState(sessionId, workContextHomeRoot()) !== null;
2516
+ if (sessionEventGoesToSpool(kind, opts.enqueue, hasLocalState)) {
2517
+ // The spool line has no field for these, and the drain posts no
2518
+ // evidence, so refuse rather than drop them.
2519
+ const unsupported = [
2520
+ (opts.touchedPath ?? []).some((p) => p.trim()) ? "--touched-path" : null,
2521
+ opts.repoPath?.trim() ? "--repo-path" : null,
2522
+ ].filter((flag) => flag !== null);
2523
+ if (unsupported.length > 0) {
2524
+ fail(`${unsupported.join(" and ")} cannot be carried through the Work Mesh spool for session ${sessionId} ` +
2525
+ "(it has local session state, so this event goes to the spool). Drop the flag; nothing was written.");
2526
+ }
2527
+ const { enqueueSessionEvent } = await import("../lib/mesh/live/enqueue.js");
2528
+ const toolWrites = opts.toolWrites === undefined ? undefined : Number(opts.toolWrites);
2529
+ const { event } = enqueueSessionEvent({
2530
+ kind,
2531
+ sessionId,
2532
+ harness,
2533
+ adapterVersion,
2534
+ runtimeVersion: opts.runtimeVersion?.trim() || undefined,
2535
+ source: "hooks",
2536
+ at: opts.at?.trim() || undefined,
2537
+ seq,
2538
+ eventId: opts.eventId,
2539
+ taskId: opts.taskId,
2540
+ status: opts.status,
2541
+ reason: opts.reason,
2542
+ summary: opts.summary,
2543
+ cwd: opts.cwd,
2544
+ hqRoot: opts.hqRoot?.trim() || undefined,
2545
+ companySlug: opts.companySlug,
2546
+ project: opts.project,
2547
+ task: opts.task,
2548
+ toolWrites: toolWrites !== undefined && Number.isInteger(toolWrites) && toolWrites >= 0 ? toolWrites : undefined,
2549
+ root: workMeshHomeRoot(),
2550
+ env: process.env,
2551
+ });
2552
+ if (opts.json) {
2553
+ console.log(JSON.stringify({ ok: true, action: "enqueue", kind, eventId: event.eventId }, null, 2));
2554
+ }
2555
+ return;
2556
+ }
2483
2557
  const evidence = buildEmitEvidence({
2484
2558
  sessionId: sessionId,
2485
2559
  hqRoot: opts.hqRoot,
@@ -2644,7 +2718,9 @@ async function runMeshEmit(opts) {
2644
2718
  let skipped = 0;
2645
2719
  let newEvents = [];
2646
2720
  if (opts.replayLegacy) {
2647
- const backlog = readLegacyBacklog(meshRoot);
2721
+ // Direct mode: a queue that predates the drain's first run is set aside
2722
+ // before anything is read (US-038, owner decision 70).
2723
+ const backlog = readLegacyBacklogForMode(resolveMeshEmitMode(), meshRoot);
2648
2724
  scanned = backlog.scanned;
2649
2725
  skipped = backlog.skipped;
2650
2726
  newEvents = backlog.events;
@@ -2674,14 +2750,20 @@ async function runSessionFlush(opts) {
2674
2750
  token,
2675
2751
  baseUrl: resolveVaultApiBase(process.env),
2676
2752
  });
2677
- const summary = await flushSessionEvents({
2753
+ // In direct mode this is one drain cycle: the first run on a machine moves
2754
+ // the queued files aside and posts nothing (US-038, owner decision 70).
2755
+ const { summary, firstRun, setAside } = await flushForEmitMode(resolveMeshEmitMode(), {
2678
2756
  reportingAllowed: () => reportingRuntimeAllowed(isMachineIdentity()),
2679
2757
  workMeshRoot: workMeshHomeRoot(),
2680
2758
  workContextRoot: workContextHomeRoot(),
2681
2759
  poster,
2682
2760
  });
2683
2761
  if (opts.json) {
2684
- console.log(JSON.stringify({ ok: true, action: "flush", ...summary }, null, 2));
2762
+ console.log(JSON.stringify({ ok: true, action: "flush", ...summary, firstRun, setAside }, null, 2));
2763
+ return;
2764
+ }
2765
+ if (firstRun) {
2766
+ console.log(`work-mesh flush: first run in direct mode; moved ${setAside.length} queued file(s) aside, nothing posted`);
2685
2767
  return;
2686
2768
  }
2687
2769
  console.log(`work-mesh flush: claimed=${summary.claimed} posted=${summary.posted}` +
@@ -1,6 +1,7 @@
1
1
  import { reconcileHookRegistrations } from '../lib/hook-engine/reconcile.js';
2
2
  import { SKIP_CANARY_GATE_ENV } from '../lib/hook-engine/canary-gate.js';
3
3
  import { trustCodexUserHooks } from '../utils/hook-trust.js';
4
+ import { REINDEX_FROM_HOOK_ENV } from '../utils/host-registration.js';
4
5
  /**
5
6
  * hq reindex — surface namespaced skills and commands, clean up retired
6
7
  * personal-overlay mirror links, capture coding-harness session logs, regenerate
@@ -749,6 +750,11 @@ export function registerReindexCommand(program) {
749
750
  // install, reindex and the Grok trust step all honor it the same way.
750
751
  if (opts.skipHostCanaryGate)
751
752
  process.env[SKIP_CANARY_GATE_ENV] = '1';
753
+ // A reindex started by a hook never changes a host's core (#3039
754
+ // Q-ST2-04-1, ruling (A)): the host canary gate keeps each host on the
755
+ // core it is on now. Read from the environment for the same reason.
756
+ if (opts.fromHook)
757
+ process.env[REINDEX_FROM_HOOK_ENV] = '1';
752
758
  // Resolve the lock-wait bound. An explicit --lock-timeout wins; otherwise
753
759
  // --from-hook forces 0 (refuse-fast) so a hook fired while a sync/rescue
754
760
  // holds the shared per-root operation lock can never stall the agent.