@indigoai-us/hq-cli 5.345.222 → 5.345.225

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 (128) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +79 -5
  5. package/dist/command-catalog.generated.js +95 -5
  6. package/dist/commands/bot.d.ts +1 -1
  7. package/dist/commands/bot.js +34 -33
  8. package/dist/commands/cloud-provision.d.ts +4 -1
  9. package/dist/commands/cloud-provision.js +7 -3
  10. package/dist/commands/cloud-retire.js +1 -1
  11. package/dist/commands/core-delegate-w1b.js +210 -188
  12. package/dist/commands/core-delegate.d.ts +5 -0
  13. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  14. package/dist/commands/core-dm-bind-native.js +4 -0
  15. package/dist/commands/core-job-notify-native.d.ts +5 -1
  16. package/dist/commands/core-job-notify-native.js +8 -2
  17. package/dist/commands/core-jobs-native.d.ts +27 -1
  18. package/dist/commands/core-jobs-native.js +49 -28
  19. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  20. package/dist/commands/core-pipeline-driver-native.js +5 -5
  21. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  22. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  23. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  24. package/dist/commands/daemon.d.ts +2 -0
  25. package/dist/commands/daemon.js +67 -1
  26. package/dist/commands/lanes-hold.d.ts +2 -27
  27. package/dist/commands/lanes-hold.js +3 -75
  28. package/dist/commands/lanes-loop.js +1 -1
  29. package/dist/commands/lanes-session-start.js +2 -2
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +13 -4
  32. package/dist/commands/monitor.js +1 -1
  33. package/dist/commands/packs.js +14 -3
  34. package/dist/commands/sync-core.js +31 -12
  35. package/dist/commands/whoami.d.ts +10 -17
  36. package/dist/commands/whoami.js +7 -79
  37. package/dist/data/command-states.json +13 -0
  38. package/dist/index.js +1 -1
  39. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  40. package/dist/lib/bot/fleet-cron.js +44 -4
  41. package/dist/lib/bot/run.d.ts +4 -4
  42. package/dist/lib/bot/run.js +5 -3
  43. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  44. package/dist/lib/bot/signals-engine-flag.js +202 -9
  45. package/dist/lib/daemon/catalog.d.ts +8 -5
  46. package/dist/lib/daemon/catalog.js +13 -7
  47. package/dist/lib/daemon/config.d.ts +5 -0
  48. package/dist/lib/daemon/config.js +6 -0
  49. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  50. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  51. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  52. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  53. package/dist/lib/daemon/machine-checks.d.ts +45 -0
  54. package/dist/lib/daemon/machine-checks.js +95 -11
  55. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  56. package/dist/lib/daemon/merge-sections.js +556 -0
  57. package/dist/lib/daemon/native-notice-ledger.d.ts +9 -0
  58. package/dist/lib/daemon/native-notice-ledger.js +43 -0
  59. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  60. package/dist/lib/daemon/ops/policy.js +1 -1
  61. package/dist/lib/daemon/protocol.d.ts +1 -1
  62. package/dist/lib/daemon/protocol.js +0 -6
  63. package/dist/lib/daemon/run.js +76 -3
  64. package/dist/lib/daemon/selfcheck.js +2 -2
  65. package/dist/lib/daemon/server.d.ts +2 -4
  66. package/dist/lib/daemon/server.js +5 -48
  67. package/dist/lib/daemon/state-file.d.ts +74 -4
  68. package/dist/lib/daemon/state-file.js +159 -19
  69. package/dist/lib/daemon/supervisor.d.ts +11 -1
  70. package/dist/lib/daemon/supervisor.js +86 -0
  71. package/dist/lib/daemon/updater.d.ts +2 -6
  72. package/dist/lib/daemon/updater.js +4 -11
  73. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  74. package/dist/lib/daemon/whoami-cache.js +244 -0
  75. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  76. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  77. package/dist/lib/flag-registry-worker.js +33 -3
  78. package/dist/lib/flag-registry.js +13 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  80. package/dist/lib/hook-engine/coverage.js +71 -0
  81. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  82. package/dist/lib/hook-engine/reconcile.js +14 -8
  83. package/dist/lib/install/hook-target.d.ts +13 -3
  84. package/dist/lib/install/hook-target.js +14 -11
  85. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  86. package/dist/lib/lanes/monitor.d.ts +2 -0
  87. package/dist/lib/lanes/monitor.js +2 -1
  88. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  89. package/dist/lib/lanes/registry-flag.js +3 -2
  90. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  91. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  92. package/dist/lib/lanes/watcher-main.js +3 -3
  93. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  94. package/dist/lib/mesh/live/daemon/install.js +2 -2
  95. package/dist/lib/scan-packages/index.js +8 -9
  96. package/dist/lib/signals/engine.d.ts +8 -0
  97. package/dist/lib/signals/engine.js +15 -5
  98. package/dist/lib/sync-core/flag.d.ts +18 -0
  99. package/dist/lib/sync-core/flag.js +66 -0
  100. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  101. package/dist/lib/sync-core/reconcile.js +15 -0
  102. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  103. package/dist/lib/sync-core/rollout-state.js +7 -0
  104. package/dist/lib/sync-core/vault-settings.d.ts +12 -1
  105. package/dist/lib/sync-core/vault-settings.js +23 -7
  106. package/dist/lib/windows/install-followup.js +1 -1
  107. package/dist/utils/client-health-contract.d.ts +1 -0
  108. package/dist/utils/client-health-contract.js +5 -0
  109. package/dist/utils/client-health.d.ts +2 -0
  110. package/dist/utils/client-health.js +40 -0
  111. package/dist/utils/cognito-session.d.ts +2 -14
  112. package/dist/utils/cognito-session.js +2 -40
  113. package/dist/utils/daemon-cli-version.d.ts +13 -0
  114. package/dist/utils/daemon-cli-version.js +47 -0
  115. package/dist/utils/duplicate-command-usage.js +1 -1
  116. package/dist/utils/machine-token-cache.d.ts +21 -0
  117. package/dist/utils/machine-token-cache.js +49 -0
  118. package/dist/utils/pack-contributions.d.ts +14 -2
  119. package/dist/utils/pack-contributions.js +31 -5
  120. package/dist/utils/resident-package-preload.js +4 -0
  121. package/dist/utils/whoami-identity.d.ts +54 -0
  122. package/dist/utils/whoami-identity.js +108 -0
  123. package/package.json +7 -7
  124. package/scripts/bench-core.mjs +34 -3
  125. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  126. package/dist/lib/daemon/ops/memory.js +0 -65
  127. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  128. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * The daemon's state file: one JSON file, rewritten atomically after each
3
- * flag registry request the daemon's timed flag monitors share, that hooks
4
- * read instead of starting Node or calling the network.
3
+ * flag registry request the daemon's timed flag monitors share, and again
4
+ * after each refresh of the merge sections (every 15 s, merge-sections.ts),
5
+ * that hooks read instead of starting Node or calling the network.
5
6
  *
6
- * It holds three sections and nothing else:
7
+ * It holds these sections and nothing else:
7
8
  * - flags: every flag value the registry returned for the daemon's scope
8
9
  * (person, or one company uid), with the time the registry answered;
9
10
  * - vault_access: per company slug, the caller's role, whether the access
@@ -13,7 +14,18 @@
13
14
  * today (id, status, time, optional one-line summary, and for a finding
14
15
  * its text, cut to 4096 bytes, and a fingerprint the hook engine uses to
15
16
  * show it once). The finding text can name local paths, so like the rest
16
- * of the file it is never logged or sent.
17
+ * of the file it is never logged or sent;
18
+ * - lanes_monitor (optional, written only when the daemon computed it): per
19
+ * Claude senior session of an active lane, the active and uncovered lane
20
+ * ids, the Monitor calls that would cover the uncovered ones, and the
21
+ * reminder text (lanes-monitor-state.ts). It is what `hq lanes
22
+ * monitor-check` would answer, precomputed so the UserPromptSubmit hook
23
+ * starts no program. A missing or stale section means no reminder.
24
+ * - merge_holds and merge_approvals (merge-sections.ts): the repository
25
+ * merge holds with each owning company's hold flag, and per session the
26
+ * conduct decision queue and review gate the native merge check reads.
27
+ * Each has its own refreshed_at and a 60-second max age; a section that
28
+ * cannot be built is left out, which makes that check refuse merges.
17
29
  *
18
30
  * No token, key or other secret is written. The vault access list tells which
19
31
  * companies and paths a person can reach, so the file lives in the per-host
@@ -70,6 +82,13 @@ export function cutUtf8(text, maxBytes) {
70
82
  end -= 1;
71
83
  return bytes.subarray(0, end).toString("utf8");
72
84
  }
85
+ /** At most this many sessions are written into lanes_monitor. */
86
+ export const LANES_MONITOR_MAX_SESSIONS = 64;
87
+ /** The hook engine refuses an extra section larger than this (crates/hq-hook). */
88
+ export const LANES_MONITOR_READER_MAX_BYTES = 256 * 1024;
89
+ /** The writer keeps lanes_monitor, serialized, at or under this many bytes. */
90
+ export const LANES_MONITOR_MAX_BYTES = 192 * 1024;
91
+ export const LANES_MONITOR_SESSION_ID_RE = /^[A-Za-z0-9._-]+$/;
73
92
  /** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
74
93
  export function daemonStateFilePath(home, env = process.env) {
75
94
  const explicit = env.HQ_STATE_FILE?.trim();
@@ -202,6 +221,70 @@ function machineChecksOf(results) {
202
221
  }
203
222
  return out;
204
223
  }
224
+ function isLaneIdList(value) {
225
+ return Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0);
226
+ }
227
+ function lanesMonitorSessionOf(value) {
228
+ if (!isRecord(value) || value.engine !== "claude" || !isIsoTime(value.checked_at))
229
+ return null;
230
+ if (typeof value.reminder !== "string")
231
+ return null;
232
+ const active = value.active_lane_ids;
233
+ const uncovered = value.uncovered_lane_ids;
234
+ if (!isLaneIdList(active) || !isLaneIdList(uncovered))
235
+ return null;
236
+ const activeSet = new Set(active);
237
+ if (!uncovered.every((id) => activeSet.has(id)))
238
+ return null;
239
+ if (!Array.isArray(value.monitor_calls))
240
+ return null;
241
+ const calls = [];
242
+ for (const call of value.monitor_calls) {
243
+ if (!isRecord(call) || typeof call.command !== "string" || !call.command)
244
+ return null;
245
+ if (typeof call.timeout_ms !== "number" || !Number.isInteger(call.timeout_ms) || call.timeout_ms <= 0)
246
+ return null;
247
+ if (call.persistent !== false)
248
+ return null;
249
+ calls.push({ command: call.command, timeout_ms: call.timeout_ms, persistent: false });
250
+ }
251
+ return {
252
+ engine: "claude",
253
+ checked_at: value.checked_at,
254
+ active_lane_ids: [...active],
255
+ uncovered_lane_ids: [...uncovered],
256
+ monitor_calls: calls,
257
+ reminder: value.reminder,
258
+ };
259
+ }
260
+ /**
261
+ * The lanes_monitor section with only its documented fields, in key order, or
262
+ * null when any part of it is malformed (a bad session id or entry, an
263
+ * uncovered id that is not active, more than LANES_MONITOR_MAX_SESSIONS
264
+ * sessions, or more than LANES_MONITOR_READER_MAX_BYTES serialized). The whole
265
+ * section is dropped rather than part of it, so a reader never takes a partial
266
+ * answer for a complete one.
267
+ */
268
+ export function lanesMonitorSectionOf(value) {
269
+ if (!isRecord(value) || !isIsoTime(value.checked_at) || !isRecord(value.sessions))
270
+ return null;
271
+ const ids = Object.keys(value.sessions);
272
+ if (ids.length > LANES_MONITOR_MAX_SESSIONS)
273
+ return null;
274
+ const sessions = {};
275
+ for (const id of ids) {
276
+ if (!LANES_MONITOR_SESSION_ID_RE.test(id))
277
+ return null;
278
+ const entry = lanesMonitorSessionOf(value.sessions[id]);
279
+ if (!entry)
280
+ return null;
281
+ sessions[id] = entry;
282
+ }
283
+ const section = { checked_at: value.checked_at, sessions };
284
+ if (Buffer.byteLength(JSON.stringify(section), "utf8") > LANES_MONITOR_READER_MAX_BYTES)
285
+ return null;
286
+ return section;
287
+ }
205
288
  /** The exact bytes written: one line of JSON with the keys in schema order. */
206
289
  export function renderDaemonStateFile(state) {
207
290
  const scopes = {};
@@ -218,7 +301,12 @@ export function renderDaemonStateFile(state) {
218
301
  ? { refreshed_at: state.vault_access.refreshed_at, companies: state.vault_access.companies }
219
302
  : null,
220
303
  machine_checks: { results: machineChecksOf(state.machine_checks.results) },
304
+ ...(state.merge_holds ? { merge_holds: state.merge_holds } : {}),
305
+ ...(state.merge_approvals ? { merge_approvals: state.merge_approvals } : {}),
221
306
  };
307
+ const lanesMonitor = state.lanes_monitor ? lanesMonitorSectionOf(state.lanes_monitor) : null;
308
+ if (lanesMonitor)
309
+ ordered.lanes_monitor = lanesMonitor;
222
310
  return `${JSON.stringify(ordered)}\n`;
223
311
  }
224
312
  /**
@@ -297,6 +385,7 @@ export function readDaemonStateFile(file) {
297
385
  const checks = isRecord(parsed.machine_checks) && Array.isArray(parsed.machine_checks.results)
298
386
  ? machineChecksOf(parsed.machine_checks.results)
299
387
  : [];
388
+ const lanesMonitor = parsed.lanes_monitor === undefined ? null : lanesMonitorSectionOf(parsed.lanes_monitor);
300
389
  return {
301
390
  schema: DAEMON_STATE_SCHEMA,
302
391
  written_at: parsed.written_at,
@@ -306,6 +395,9 @@ export function readDaemonStateFile(file) {
306
395
  ? { refreshed_at: vault.refreshed_at, companies: vault.companies }
307
396
  : null,
308
397
  machine_checks: { results: checks },
398
+ ...(isRecord(parsed.merge_holds) ? { merge_holds: parsed.merge_holds } : {}),
399
+ ...(isRecord(parsed.merge_approvals) ? { merge_approvals: parsed.merge_approvals } : {}),
400
+ ...(lanesMonitor ? { lanes_monitor: lanesMonitor } : {}),
309
401
  };
310
402
  }
311
403
  /** `person`, a company uid, or null for a slug that resolves to no uid (its flags are not written). */
@@ -360,6 +452,7 @@ export function createDaemonStateWriter(options) {
360
452
  const log = options.log ?? (() => { });
361
453
  let closed = false;
362
454
  let lastProblem;
455
+ let lanesMonitorProblem;
363
456
  // The file left from before the switch went off is removed once per off period.
364
457
  let removedWhileOff = false;
365
458
  const ownFile = options.defaultFile === undefined || path.resolve(options.defaultFile) === path.resolve(options.file);
@@ -373,7 +466,62 @@ export function createDaemonStateWriter(options) {
373
466
  log("info", "state file: written again");
374
467
  };
375
468
  const errorName = (error) => (error instanceof Error ? error.name : "UnknownError");
469
+ // The flags of the last registry request while the file is on; null before
470
+ // the first one and while it is off. Kept in memory only, never read back
471
+ // from the file.
472
+ let lastScopes = null;
473
+ /** Write the file; the problem to report, or undefined when it was written. */
474
+ const write = (now, scopes) => {
475
+ const merge = options.readMergeSections?.() ?? { merge_holds: null, merge_approvals: null };
476
+ let lanesMonitor = null;
477
+ try {
478
+ lanesMonitor = options.readLanesMonitor?.() ?? null;
479
+ if (lanesMonitorProblem)
480
+ log("info", "state file: lanes_monitor section computed again");
481
+ lanesMonitorProblem = undefined;
482
+ }
483
+ catch (error) {
484
+ // The hook reads a missing section as "no reminder"; the rest of the
485
+ // file is still written.
486
+ lanesMonitor = null;
487
+ const problem = errorName(error);
488
+ if (problem !== lanesMonitorProblem)
489
+ log("warn", `state file: lanes_monitor section left out (${problem})`);
490
+ lanesMonitorProblem = problem;
491
+ }
492
+ try {
493
+ writeDaemonStateFile(options.file, {
494
+ schema: DAEMON_STATE_SCHEMA,
495
+ written_at: now.toISOString(),
496
+ max_age_seconds: maxAgeSeconds,
497
+ flags: { scopes },
498
+ vault_access: options.readVaultAccess?.() ?? null,
499
+ machine_checks: { results: options.readMachineChecks?.() ?? [] },
500
+ merge_holds: merge.merge_holds,
501
+ merge_approvals: merge.merge_approvals,
502
+ ...(lanesMonitor ? { lanes_monitor: lanesMonitor } : {}),
503
+ }, { ...options.writeDeps, ...(options.defaultFile ? { defaultFile: options.defaultFile } : {}) });
504
+ }
505
+ catch (error) {
506
+ // Never the contents: the file holds the vault access list.
507
+ const code = error.code;
508
+ return `could not be written (${typeof code === "string" ? code : errorName(error)}); readers keep the previous file`;
509
+ }
510
+ return undefined;
511
+ };
376
512
  return {
513
+ refresh() {
514
+ if (closed || !lastScopes)
515
+ return;
516
+ try {
517
+ const problem = write(wallClock(), lastScopes);
518
+ if (problem)
519
+ report(problem);
520
+ }
521
+ catch {
522
+ // a failing section reader or log sink cannot reach the caller
523
+ }
524
+ },
377
525
  onRegistryRead(read, env) {
378
526
  if (closed)
379
527
  return;
@@ -381,6 +529,7 @@ export function createDaemonStateWriter(options) {
381
529
  const snapshot = !read.signedOut && read.errors.length === 0 ? read.client?.snapshot?.() ?? null : null;
382
530
  const off = (options.offReason ?? defaultOffReason)(read, env);
383
531
  if (off) {
532
+ lastScopes = null;
384
533
  let removed = "";
385
534
  if (!removedWhileOff && ownFile) {
386
535
  removedWhileOff = true;
@@ -401,25 +550,16 @@ export function createDaemonStateWriter(options) {
401
550
  // request: a file planted or loosened by another process is never
402
551
  // rewritten as the daemon's own, and when the daemon is signed out or
403
552
  // the request failed the flags are absent, so readers use each flag's
404
- // default.
553
+ // default. refresh() rewrites these same flags, with this request's
554
+ // fetched_at, until the next request.
405
555
  const scopes = {};
406
556
  if (snapshot && scope) {
407
557
  scopes[scope] = { fetched_at: now.toISOString(), values: daemonStateFlagValues(snapshot.flags) };
408
558
  }
409
- try {
410
- writeDaemonStateFile(options.file, {
411
- schema: DAEMON_STATE_SCHEMA,
412
- written_at: now.toISOString(),
413
- max_age_seconds: maxAgeSeconds,
414
- flags: { scopes },
415
- vault_access: options.readVaultAccess?.() ?? null,
416
- machine_checks: { results: options.readMachineChecks?.() ?? [] },
417
- }, { ...options.writeDeps, ...(options.defaultFile ? { defaultFile: options.defaultFile } : {}) });
418
- }
419
- catch (error) {
420
- // Never the contents: the file holds the vault access list.
421
- const code = error.code;
422
- report(`could not be written (${typeof code === "string" ? code : errorName(error)}); readers keep the previous file`);
559
+ lastScopes = scopes;
560
+ const problem = write(now, scopes);
561
+ if (problem) {
562
+ report(problem);
423
563
  return;
424
564
  }
425
565
  if (read.signedOut)
@@ -41,6 +41,16 @@ export declare const EPISODE_MAX_FAILURES = 6;
41
41
  export declare const EPISODE_HEALTHY_RESET_MS: number;
42
42
  export declare const STOP_ESCALATION_MS = 10000;
43
43
  export declare const SYNC_RUNNER_PERSIST_GRACE_MS = 60000;
44
+ /**
45
+ * Longest wait for a sync-core engine's cycle to end before a parallel-download
46
+ * settings change restarts it anyway. A first-sync cycle can run about 14 minutes.
47
+ */
48
+ export declare const SYNC_CORE_SETTINGS_IDLE_MAX_MS: number;
49
+ /**
50
+ * True when two sync-core plans differ only in the parallel-download env keys,
51
+ * so the change can wait for the engine to finish its cycle.
52
+ */
53
+ export declare function onlySyncCoreSettingsChanged(before: UnitPlan, after: UnitPlan): boolean;
44
54
  export declare const CLI_UPDATE_SYNC_IDLE_KILL_GRACE_MS = 60000;
45
55
  /** After a handoff, how long a replaced unit must stay up before the next one is replaced. */
46
56
  export declare const HANDOFF_STAGGER_MS = 15000;
@@ -81,7 +91,7 @@ export interface SupervisedChild {
81
91
  on(event: "error", handler: (err: Error) => void): unknown;
82
92
  kill(signal?: NodeJS.Signals | number): boolean;
83
93
  }
84
- type UnitStatus = "running" | "waiting" | "unavailable" | "backoff" | "exited" | "idle" | "stopped" | "held";
94
+ type UnitStatus = "running" | "waiting" | "unavailable" | "backoff" | "exited" | "idle" | "stopped" | "held" | "paused";
85
95
  /**
86
96
  * Why a long-running unit is held down. `permanent`: the last exit had a cause
87
97
  * a restart cannot fix. `exhausted`: EPISODE_MAX_FAILURES failures without a
@@ -44,6 +44,32 @@ export const EPISODE_HEALTHY_RESET_MS = 30 * 60_000;
44
44
  export const STOP_ESCALATION_MS = 10_000;
45
45
  export const SYNC_RUNNER_PERSIST_GRACE_MS = 60_000;
46
46
  const CLI_UPDATE_SYNC_IDLE_MAX_MS = 10 * 60_000;
47
+ /**
48
+ * Longest wait for a sync-core engine's cycle to end before a parallel-download
49
+ * settings change restarts it anyway. A first-sync cycle can run about 14 minutes.
50
+ */
51
+ export const SYNC_CORE_SETTINGS_IDLE_MAX_MS = 30 * 60_000;
52
+ /** Engine env keys whose change waits for the engine to be between cycles. */
53
+ const SYNC_CORE_IDLE_RESTART_ENV_KEYS = new Set(["HQ_SYNC_PARALLEL_DOWNLOADS", "HQ_SYNC_DOWNLOAD_STREAMS"]);
54
+ /**
55
+ * True when two sync-core plans differ only in the parallel-download env keys,
56
+ * so the change can wait for the engine to finish its cycle.
57
+ */
58
+ export function onlySyncCoreSettingsChanged(before, after) {
59
+ if (before.service !== "sync-core" || after.service !== "sync-core")
60
+ return false;
61
+ const strip = (plan) => ({
62
+ ...plan,
63
+ env: Object.fromEntries(Object.entries(plan.env ?? {}).filter(([key]) => !SYNC_CORE_IDLE_RESTART_ENV_KEYS.has(key))),
64
+ });
65
+ const b = strip(before);
66
+ const a = strip(after);
67
+ if (planKey(b) !== planKey(a))
68
+ return false;
69
+ if ((b.blocked === undefined) !== (a.blocked === undefined))
70
+ return false;
71
+ return planKey(before) !== planKey(after);
72
+ }
47
73
  export const CLI_UPDATE_SYNC_IDLE_KILL_GRACE_MS = 60_000;
48
74
  const MESH_OWNER_RECHECK_MS = 15_000;
49
75
  const MESH_OWNER_LOG_INTERVAL_MS = 10 * 60_000;
@@ -398,6 +424,50 @@ export function createSupervisor(deps) {
398
424
  pending.timer = setT(() => finishPendingSyncCommandRestart(true), CLI_UPDATE_SYNC_IDLE_MAX_MS);
399
425
  }
400
426
  };
427
+ const clearEngineIdleRestart = (slot) => {
428
+ const pending = slot.engineIdleRestart;
429
+ if (!pending)
430
+ return;
431
+ if (pending.timer !== undefined)
432
+ clearT(pending.timer);
433
+ slot.engineIdleRestart = undefined;
434
+ };
435
+ const runEngineIdleRestart = (slot) => {
436
+ const pending = slot.engineIdleRestart;
437
+ if (!pending)
438
+ return;
439
+ clearEngineIdleRestart(slot);
440
+ pending.run();
441
+ };
442
+ /**
443
+ * Restart a sync-core engine whose parallel-download settings changed once it
444
+ * is between cycles (after its all-complete), or after
445
+ * SYNC_CORE_SETTINGS_IDLE_MAX_MS. Each engine unit has its own pending restart.
446
+ */
447
+ const deferEngineRestartUntilIdle = (slot) => {
448
+ const run = () => {
449
+ deps.log("info", `restarting ${slot.plan.id}: its parallel download settings changed`);
450
+ terminate(slot, () => activate(slot));
451
+ };
452
+ if (slot.engineCycleActive === false) {
453
+ clearEngineIdleRestart(slot);
454
+ run();
455
+ return;
456
+ }
457
+ if (slot.engineIdleRestart) {
458
+ slot.engineIdleRestart.run = run;
459
+ return;
460
+ }
461
+ deps.log("info", `deferring restart of ${slot.plan.id} until its sync cycle ends (maximum ${SYNC_CORE_SETTINGS_IDLE_MAX_MS / 60_000} minutes)`);
462
+ const pending = { run };
463
+ slot.engineIdleRestart = pending;
464
+ pending.timer = setT(() => {
465
+ if (slot.engineIdleRestart !== pending)
466
+ return;
467
+ deps.log("warn", `${slot.plan.id} did not finish its sync cycle within ${SYNC_CORE_SETTINGS_IDLE_MAX_MS / 60_000} minutes; restarting it to apply the changed settings`);
468
+ runEngineIdleRestart(slot);
469
+ }, SYNC_CORE_SETTINGS_IDLE_MAX_MS);
470
+ };
401
471
  const setBlocked = (slot) => {
402
472
  const block = slot.plan.blocked;
403
473
  slot.state.status = block.state;
@@ -559,6 +629,7 @@ export function createSupervisor(deps) {
559
629
  */
560
630
  const terminate = (slot, then, drain = false, killGraceMs = slot.plan.stopGraceMs ?? STOP_ESCALATION_MS) => {
561
631
  clearPendingSyncCommandRestart(slot);
632
+ clearEngineIdleRestart(slot);
562
633
  clearTimer(slot);
563
634
  clearHeartbeatTimer(slot);
564
635
  const child = slot.child;
@@ -703,6 +774,12 @@ export function createSupervisor(deps) {
703
774
  }
704
775
  }
705
776
  if (slot.plan.service === "sync-core") {
777
+ if (event.type === "fanout-plan")
778
+ slot.engineCycleActive = true;
779
+ else if (event.type === "all-complete") {
780
+ slot.engineCycleActive = false;
781
+ runEngineIdleRestart(slot);
782
+ }
706
783
  const bytes = heartbeatProgressBytes(event);
707
784
  if (bytes !== null) {
708
785
  // The first progress heartbeat of a run is the baseline: counters are
@@ -758,6 +835,8 @@ export function createSupervisor(deps) {
758
835
  if (slot.child !== child)
759
836
  return;
760
837
  slot.child = undefined;
838
+ // The next start uses the current plan, so a waiting settings restart is moot.
839
+ clearEngineIdleRestart(slot);
761
840
  if (pendingSyncCommandRestart?.slot === slot) {
762
841
  clearPendingSyncCommandRestart(slot);
763
842
  if (deferredCliRestart)
@@ -919,6 +998,7 @@ export function createSupervisor(deps) {
919
998
  delete slot.lastProtocolLine;
920
999
  delete slot.lastProtocolStatus;
921
1000
  delete slot.syncPassActive;
1001
+ delete slot.engineCycleActive;
922
1002
  delete slot.progressBytes;
923
1003
  delete slot.progressedThisRun;
924
1004
  let child;
@@ -1193,6 +1273,7 @@ export function createSupervisor(deps) {
1193
1273
  existing.adopted = false;
1194
1274
  const hadDrainSignal = existing.plan.drainSignal !== undefined;
1195
1275
  const key = planKey(plan, deps.cliVersion);
1276
+ const settingsOnly = onlySyncCoreSettingsChanged(existing.plan, plan);
1196
1277
  const wasBlocked = existing.plan.blocked !== undefined;
1197
1278
  const changed = key !== existing.key;
1198
1279
  existing.plan = plan;
@@ -1259,6 +1340,11 @@ export function createSupervisor(deps) {
1259
1340
  deps.log("info", `will replace ${plan.id}: it runs an older CLI or command`);
1260
1341
  handoffQueue.push(existing);
1261
1342
  }
1343
+ else if (changed && settingsOnly && existing.child && !existing.expectingExit) {
1344
+ existing.attempts = 0;
1345
+ existing.state.restarts = 0;
1346
+ deferEngineRestartUntilIdle(existing);
1347
+ }
1262
1348
  else if (changed) {
1263
1349
  deps.log("info", `restarting ${plan.id}: its command changed`);
1264
1350
  existing.attempts = 0;
@@ -16,6 +16,7 @@
16
16
  * and every service run the new version. The remote-control hosts notice an
17
17
  * updated Claude or Codex on disk themselves and restart once idle.
18
18
  */
19
+ import { daemonVersionFromBootstrapCommandLine } from "../../utils/daemon-cli-version.js";
19
20
  import type { SelfUpdateOutcome } from "../../utils/self-update.js";
20
21
  import type { HqCloudUpdateOutcome } from "./hq-cloud.js";
21
22
  import { type ToolInstall, type ToolName } from "./tools.js";
@@ -57,12 +58,7 @@ export interface UpdaterResult {
57
58
  }
58
59
  /** Only a strictly older, parseable daemon version triggers a restart, so a dev build never loops. */
59
60
  export declare function daemonIsOlderThanCli(running: string, installed: string): boolean;
60
- /**
61
- * The version a daemon handed to the staged child bootstrap that started this
62
- * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
63
- * Daemons have started units this way since 2026-10-05 (#1541).
64
- */
65
- export declare function daemonVersionFromBootstrapCommandLine(line: string | null): string | null;
61
+ export { daemonVersionFromBootstrapCommandLine };
66
62
  export interface RunningDaemonVersionDeps {
67
63
  /** Ask hqd; it listens only while HQ Anywhere is on, so this often fails. */
68
64
  ping: () => Promise<string>;
@@ -17,6 +17,7 @@
17
17
  * updated Claude or Codex on disk themselves and restart once idle.
18
18
  */
19
19
  import { spawnSync } from "node:child_process";
20
+ import { daemonVersionFromBootstrapCommandLine } from "../../utils/daemon-cli-version.js";
20
21
  import * as fs from "node:fs";
21
22
  import semver from "semver";
22
23
  import { locateTool, toolUpdateCommand } from "./tools.js";
@@ -26,17 +27,9 @@ export function daemonIsOlderThanCli(running, installed) {
26
27
  const i = semver.valid(installed);
27
28
  return r !== null && i !== null && semver.lt(r, i);
28
29
  }
29
- /**
30
- * The version a daemon handed to the staged child bootstrap that started this
31
- * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
32
- * Daemons have started units this way since 2026-10-05 (#1541).
33
- */
34
- export function daemonVersionFromBootstrapCommandLine(line) {
35
- if (!line)
36
- return null;
37
- const match = /hq-child-bootstrap\.m?js\s.*?(?:^|\s)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?=\s|$)/.exec(line);
38
- return match?.[1] ?? null;
39
- }
30
+ // Defined in the leaf module so client health can use it without importing the
31
+ // updater (resident daemon paths must not lazily import package modules).
32
+ export { daemonVersionFromBootstrapCommandLine };
40
33
  /**
41
34
  * The hq-cli version the running daemon was started from. hqd first; then the
42
35
  * version a newer daemon puts in the unit's environment; then the version an
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The daemon's cached `hq whoami` answer (hq-core-rust US-036).
3
+ *
4
+ * CLI commands that need the signed-in identity used to start `hq whoami
5
+ * --json` as a child, which loads the whole CLI and makes network calls. The
6
+ * daemon is already running on most machines, so it keeps the answer in
7
+ * `<daemon folder>/whoami.json` and those commands read the file instead.
8
+ *
9
+ * The file holds the identity `hq whoami --json` prints without `planLimits`:
10
+ * email, Cognito subject, delegated person, `prs_*`/`agt_*` uids, machine
11
+ * username and session expiry. No token is written. Like the state file it is
12
+ * 0600 in the per-host daemon folder and its contents are never logged.
13
+ *
14
+ * A reader uses the file only when it is current and still describes this
15
+ * session: the schema matches, it is younger than its stated maximum age, and
16
+ * the token source, subject, delegated subject, email, machine username and
17
+ * agent uid equal what the local token caches and machine credentials say now. The session fields that change with time
18
+ * (`authenticated`, `sessionExpiresAt`, `sessionExpiring`) are taken from the
19
+ * local caches, never from the file. Anything else (no daemon, a bot or a
20
+ * Windows box without one, a sign-in as someone else) reads as no answer, and
21
+ * the caller falls back to running `hq whoami` as before.
22
+ *
23
+ * The daemon refreshes the file on an in-process timer. The person-uid lookup
24
+ * is its only network call: once per signed-in subject, retried at most every
25
+ * 30 minutes while it has no answer.
26
+ */
27
+ import { type WhoamiIdentity, type WhoamiTokenIdentity } from "../../utils/whoami-identity.js";
28
+ export declare const WHOAMI_CACHE_SCHEMA = "hq-whoami.v1";
29
+ export declare const WHOAMI_CACHE_FILE = "whoami.json";
30
+ /** Written into the file; a reader ignores the file past this age. */
31
+ export declare const WHOAMI_CACHE_MAX_AGE_SECONDS = 1800;
32
+ /** How often the daemon rewrites the file. */
33
+ export declare const WHOAMI_CACHE_REFRESH_MS: number;
34
+ /** How long the daemon waits before asking again for a person uid it could not get. */
35
+ export declare const WHOAMI_PERSON_UID_RETRY_MS: number;
36
+ export interface WhoamiCacheFile {
37
+ schema: typeof WHOAMI_CACHE_SCHEMA;
38
+ written_at: string;
39
+ max_age_seconds: number;
40
+ identity: WhoamiIdentity;
41
+ }
42
+ /**
43
+ * `HQ_WHOAMI_CACHE_FILE` when set in `env` or in this process (tests and
44
+ * isolated daemons), else `<daemon folder>/whoami.json` for this home.
45
+ */
46
+ export declare function whoamiCachePath(home?: string, env?: NodeJS.ProcessEnv): string;
47
+ /** The file, or null when it is not a complete, current-schema, unexpired file at `now`. */
48
+ export declare function parseWhoamiCache(text: string, now?: Date): WhoamiCacheFile | null;
49
+ export interface ReadCachedWhoamiOptions {
50
+ home?: string;
51
+ env?: NodeJS.ProcessEnv;
52
+ now?: Date;
53
+ /** This session's identity from the local token caches (no network). Read only when the file exists. */
54
+ local: () => WhoamiIdentity;
55
+ /** Test seam for the file read. */
56
+ readFile?: (file: string) => string | null;
57
+ }
58
+ /**
59
+ * The daemon's whoami answer for this session, or null when the caller
60
+ * should run `hq whoami` itself (see the file comment).
61
+ */
62
+ export declare function readCachedWhoami(options: ReadCachedWhoamiOptions): WhoamiIdentity | null;
63
+ /**
64
+ * What `hq whoami` (plain, or `--json`) would print for `identity`, for
65
+ * callers that parse that output. `--json` matches the command's own output
66
+ * with `planLimits` unknown (null); the plain form carries the identity lines
67
+ * only, without the plan or deleted-company notices.
68
+ */
69
+ export declare function renderCachedWhoami(identity: WhoamiIdentity, json: boolean): string;
70
+ export interface WhoamiCacheWriterOptions {
71
+ home: string;
72
+ env: NodeJS.ProcessEnv;
73
+ log: (level: "info" | "warn" | "error", message: string) => void;
74
+ /** Builds the identity; `readPersonUid` is called only for an authenticated person session. */
75
+ build: (readPersonUid: (token: WhoamiTokenIdentity) => Promise<string | null>) => Promise<WhoamiIdentity>;
76
+ /** The network person-uid lookup (`hq whoami`'s own). */
77
+ lookupPersonUid: (token: WhoamiTokenIdentity) => Promise<string | null>;
78
+ intervalMs?: number;
79
+ now?: () => number;
80
+ schedule?: (callback: () => void, delayMs: number) => () => void;
81
+ write?: (file: string, text: string) => void;
82
+ }
83
+ export interface WhoamiCacheWriter {
84
+ /** Rewrite the file now. Resolves when written; a failure is logged, never thrown. */
85
+ refresh(): Promise<void>;
86
+ close(): void;
87
+ }
88
+ /** The daemon side: write the file at start and on an in-process timer. */
89
+ export declare function startWhoamiCacheWriter(options: WhoamiCacheWriterOptions): WhoamiCacheWriter;
90
+ /**
91
+ * For CLI commands that used to run `hq whoami [--json]`: that command's
92
+ * output from the daemon's cached answer, or null when there is no usable
93
+ * answer and the caller should run `hq whoami` itself.
94
+ */
95
+ export declare function daemonWhoamiOutput(json: boolean, env?: NodeJS.ProcessEnv): string | null;
96
+ //# sourceMappingURL=whoami-cache.d.ts.map