@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
@@ -6,24 +6,28 @@
6
6
  * signing in takes effect without restarting the daemon.
7
7
  */
8
8
  import { spawn, spawnSync } from "node:child_process";
9
+ import { EventEmitter } from "node:events";
9
10
  import * as fs from "node:fs";
10
11
  import { createRequire } from "node:module";
11
12
  import * as os from "node:os";
12
13
  import * as path from "node:path";
13
14
  import { fileURLToPath } from "node:url";
15
+ import { MessageChannel, Worker } from "node:worker_threads";
14
16
  import { loadCachedTokens } from "@indigoai-us/hq-cloud";
15
17
  import { CLI_VERSION } from "../../cli-version.js";
16
18
  import { anywhereRuntimeEnabled } from "../../commands/anywhere-runtime-flag.js";
17
19
  import { anywhereRuntimeAllowed, readHqAnywherePersonSetting, stickyPersonSettingReader } from "../anywhere-person-setting.js";
18
20
  import { watchRuntimeInputs } from "./runtime-notifications.js";
19
- import { currentPackageUseLeaseInstall, currentPackageUseUpdateRequested } from "../../utils/package-use-lease.js";
21
+ import { acquirePackageUseLease, currentPackageUseLeaseInstall, currentPackageUseUpdateRequested, PackageUseUpdatePendingError, } from "../../utils/package-use-lease.js";
20
22
  import { isLocalDependencyInstall, resolveRunningInstall } from "../../utils/version-gate.js";
21
23
  import { agentKitPaths } from "../agent-kit/paths.js";
22
24
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../bot/config.js";
23
25
  import { clearStaleReadyBeforeGatewayStart, planFleetBots } from "../bot/fleet-daemon.js";
24
26
  import { botsRoot } from "../bot/paths.js";
25
- import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits } from "./catalog.js";
27
+ import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, legacySearchIndexCommand, planUnits } from "./catalog.js";
26
28
  import { effectiveSyncOwner, readDaemonConfig } from "./config.js";
29
+ import { backgroundQosCommand } from "./background-qos.js";
30
+ import { serveQmdWorker } from "../search-index/worker-process.js";
27
31
  import { inspectEngineHome } from "../sync-core/engine-home.js";
28
32
  import { fullModeHold } from "../sync-core/reconcile.js";
29
33
  import { readSyncCoreRolloutState } from "../sync-core/rollout-state.js";
@@ -38,6 +42,7 @@ import { SUPERVISOR_HANDOFF_FLAG, createDaemonFlagSnapshotSource, readDaemonFlag
38
42
  import { createDaemonKillSwitchMonitors } from "./timed-flag-monitors.js";
39
43
  import { MACHINE_CHECKS_RESULT_FILE, readMachineCheckResults, startMachineCheckSchedule } from "./machine-checks.js";
40
44
  import { createLanesReconcileWatcher } from "./lanes-reconcile-watcher.js";
45
+ import { createLanesReconcileStatus, withLanesReconcileUnit } from "./lanes-reconcile-status.js";
41
46
  import { findLegacyUnits, legacyMeshUnitsToRetire, legacyOwnerLookup, } from "./legacy.js";
42
47
  import { readLegacySyncEnv } from "./legacy-sync-env.js";
43
48
  import { readVaultSyncSwitches, unreadableSwitchesWarning, writeVaultSyncSwitches } from "../vault-sync-switches.js";
@@ -73,10 +78,11 @@ import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, SYNC_RUNNER_LEASE_
73
78
  import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, planKey, } from "./supervisor.js";
74
79
  import { userToolDirs } from "./tools.js";
75
80
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
76
- import { createTccEpermGuard, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
81
+ import { createTccEpermGuard, filesAccessLaunch, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
77
82
  import { daemonRunGuard } from "./lanes-reconcile-guard.js";
78
83
  import { startStopJobDrainer } from "./stop-jobs.js";
79
84
  import { executeStopJob, pruneStopJobResults, stopJobCompleted } from "./stop-job-executor.js";
85
+ import { executeHookRequest, executeSessionClose, startHookRequestDrainer } from "./hook-requests.js";
80
86
  import { closeStopDiagnosticCursor, drainStopDiagnostics } from "./stop-diagnostics.js";
81
87
  export const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
82
88
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
@@ -350,23 +356,87 @@ export function daemonPlanCanReleasePackageUseLease(plans, replaceablePackageRoo
350
356
  return true;
351
357
  if (command.type === "hq")
352
358
  return hqBootstrapReady;
353
- if (command.type === "internal")
359
+ if (command.type === "internal" || command.type === "worker")
354
360
  return true;
355
361
  const executablePaths = command.type === "node" ? [command.script, ...command.args] : [command.file, ...command.args];
356
362
  return executablePaths.every((candidate) => replaceablePackageRoots.every((root) => !isPathWithin(root, candidate)));
357
363
  });
358
364
  }
359
- const DARWIN_TASKPOLICY = "/usr/sbin/taskpolicy";
360
- /**
361
- * Prefix a unit's command with `taskpolicy -b` on macOS. taskpolicy execs the
362
- * command in place, so the pid the supervisor tracks is the unit itself, and
363
- * PRIO_DARWIN_BG is inherited by everything the unit spawns (qmd included).
364
- */
365
- export function backgroundQosCommand(command, backgroundQos, platform = process.platform, exists = fs.existsSync) {
366
- if (!backgroundQos || platform !== "darwin" || !exists(DARWIN_TASKPOLICY))
367
- return command;
368
- return [DARWIN_TASKPOLICY, ["-b", command[0], ...command[1]]];
365
+ /** Keep the installed search-index entry and its qmd files stable for one pass. */
366
+ export async function withSearchIndexPackageLease(releasedPackagePrefix, run, acquire = acquirePackageUseLease, stopOnExpiry) {
367
+ if (!releasedPackagePrefix)
368
+ return run();
369
+ let lease;
370
+ try {
371
+ lease = acquire(releasedPackagePrefix, CLI_VERSION, undefined, "command", 0, stopOnExpiry);
372
+ }
373
+ catch (error) {
374
+ if (error instanceof PackageUseUpdatePendingError)
375
+ return true;
376
+ throw error;
377
+ }
378
+ try {
379
+ return await run();
380
+ }
381
+ finally {
382
+ lease.release();
383
+ }
369
384
  }
385
+ const searchIndexWorkerEntry = new URL("./search-index-worker-v1.js", import.meta.url);
386
+ export function runSearchIndexWorker(options, entry = searchIndexWorkerEntry) {
387
+ const { root, backgroundQos, env, logPath } = options;
388
+ fs.closeSync(openPrivateAppend(logPath));
389
+ return new Promise((resolve, reject) => {
390
+ // QMD's synchronous lock and work stay off the supervisor thread.
391
+ const channel = new MessageChannel();
392
+ const stop = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
393
+ const notifyStop = () => {
394
+ Atomics.store(stop, 0, 1);
395
+ Atomics.notify(stop, 0);
396
+ };
397
+ if (options.signal?.aborted)
398
+ notifyStop();
399
+ let worker;
400
+ try {
401
+ worker = new Worker(entry, {
402
+ workerData: { root, backgroundQos, qmdPort: channel.port2, stopBuffer: stop.buffer },
403
+ transferList: [channel.port2],
404
+ env,
405
+ stdout: true,
406
+ stderr: true,
407
+ });
408
+ }
409
+ catch (error) {
410
+ channel.port1.close();
411
+ channel.port2.close();
412
+ throw error;
413
+ }
414
+ const qmd = serveQmdWorker(channel.port1, options.signal);
415
+ options.signal?.addEventListener("abort", notifyStop, { once: true });
416
+ let failure;
417
+ const record = (chunk) => {
418
+ try {
419
+ appendPrivate(logPath, chunk);
420
+ }
421
+ catch (err) {
422
+ failure ??= err instanceof Error ? err : new Error(String(err));
423
+ }
424
+ };
425
+ worker.stdout.setEncoding("utf8").on("data", record);
426
+ worker.stderr.setEncoding("utf8").on("data", record);
427
+ worker.once("error", (err) => { failure ??= err; });
428
+ worker.once("exit", (code) => {
429
+ options.signal?.removeEventListener("abort", notifyStop);
430
+ void qmd.close().then(() => {
431
+ if (failure)
432
+ reject(failure);
433
+ else
434
+ resolve(code === 0);
435
+ }, reject);
436
+ });
437
+ });
438
+ }
439
+ export { backgroundQosCommand } from "./background-qos.js";
370
440
  export function daemonHqChildCommand(nodeBinary, hqBinary, args, bootstrapPath, packagePrefix, handoffWatchEnabled = true) {
371
441
  return bootstrapPath && packagePrefix
372
442
  ? [nodeBinary, [bootstrapPath, packagePrefix, CLI_VERSION, ...(handoffWatchEnabled ? [] : ["--handoff-watch=off"]), ...args]]
@@ -1085,6 +1155,17 @@ export async function runDaemon(opts) {
1085
1155
  let laneReconcileWatcher = null;
1086
1156
  let laneReconcileWatcherRoot = null;
1087
1157
  let laneReconcileWatchFailedRoot = null;
1158
+ // The watcher's reconcile has no planned unit; its last outcome is added to
1159
+ // the state file so `hq daemon status` has a line for it.
1160
+ let lastPlanSignedIn = false;
1161
+ let lastPlanServices = [];
1162
+ const writeDaemonState = (state) => writeJsonAtomic(paths.statePath, withLanesReconcileUnit(state, laneReconcileWatcher ? laneReconcileStatus.unit(lastPlanSignedIn) : null, lastPlanServices));
1163
+ const laneReconcileStatus = createLanesReconcileStatus({
1164
+ onChange: () => {
1165
+ if (supervisor && laneReconcileWatcher)
1166
+ writeDaemonState(supervisor.state());
1167
+ },
1168
+ });
1088
1169
  let laneReconcileHandlerLoadInFlight = false;
1089
1170
  let laneReconcileHandlerLoadFailed = false;
1090
1171
  const loadLaneReconcileHandler = (initialRoot) => {
@@ -1144,13 +1225,43 @@ export async function runDaemon(opts) {
1144
1225
  }),
1145
1226
  log: message => log("warn", message),
1146
1227
  });
1147
- /** Closes the watchers; the promise settles once the Stop job in progress (if any) has written its receipt. */
1228
+ /** The running hqd's session registry, for session-close request notes; undefined while hqd is stopped. */
1229
+ let hqdSessionsForRequests;
1230
+ // Request notes hq-hook leaves (hook-requests.ts): same lease, same stop signal, this daemon's HQ root only.
1231
+ // session-close is done in the running hqd's session registry (set in onServerChange below); nothing is started.
1232
+ const hookRequestDrainer = startHookRequestDrainer({
1233
+ home,
1234
+ root: () => readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1235
+ ownsQueue: ownsStopQueue,
1236
+ execute: request => request.operation.kind === "session-close"
1237
+ ? executeSessionClose(request, {
1238
+ sessions: hqdSessionsForRequests,
1239
+ allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1240
+ })
1241
+ : executeHookRequest(request, {
1242
+ nodeBinary: opts.nodeBinary,
1243
+ hqBinary: opts.hqBinary,
1244
+ allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1245
+ env,
1246
+ home,
1247
+ signal: stopJobAbort.signal,
1248
+ log: message => log("warn", message),
1249
+ }),
1250
+ log: message => log("warn", message),
1251
+ });
1252
+ let activeIndexWorker;
1253
+ /** Close runtime work before releasing the daemon lock. */
1148
1254
  const closeRuntimeWatchers = () => {
1149
1255
  if (stopDiagnosticRoot)
1150
1256
  closeStopDiagnosticCursor(stopDiagnosticRoot);
1151
1257
  clearInterval(stopDiagnosticTimer);
1152
1258
  stopJobAbort.abort();
1153
- const stopJobsClosed = stopJobDrainer.close().catch((err) => log("warn", `Stop job drainer did not close cleanly: ${String(err)}`));
1259
+ activeIndexWorker?.stop();
1260
+ const stopJobsClosed = Promise.all([
1261
+ activeIndexWorker?.done,
1262
+ stopJobDrainer.close().catch((err) => log("warn", `Stop job drainer did not close cleanly: ${String(err)}`)),
1263
+ hookRequestDrainer.close().catch((err) => log("warn", `Hook request drainer did not close cleanly: ${String(err)}`)),
1264
+ ]).then(() => undefined);
1154
1265
  laneReconcileWatcher?.close();
1155
1266
  laneReconcileWatcher = null;
1156
1267
  laneReconcileWatcherRoot = null;
@@ -1193,9 +1304,10 @@ export async function runDaemon(opts) {
1193
1304
  try {
1194
1305
  for (const directory of laneDirectories)
1195
1306
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
1307
+ laneReconcileStatus.reset();
1196
1308
  laneReconcileWatcher = createLanesReconcileWatcher({
1197
1309
  directories: laneDirectories,
1198
- reconcile: laneReconcileHandler,
1310
+ reconcile: laneReconcileStatus.track(laneReconcileHandler),
1199
1311
  intervalMs: 15_000,
1200
1312
  onError: (error) => log("error", `in-process lanes reconcile failed: ${error instanceof Error ? error.message : String(error)}`),
1201
1313
  onWatchError: (error) => {
@@ -1337,6 +1449,8 @@ export async function runDaemon(opts) {
1337
1449
  const runners = { ...packageRunners, syncRunner: syncSource.runnerPath };
1338
1450
  const services = enabledServices(machineType, config);
1339
1451
  const isSignedIn = signedIn(env, home, log);
1452
+ lastPlanSignedIn = isSignedIn;
1453
+ lastPlanServices = services;
1340
1454
  const syncOwner = effectiveSyncOwner(config, machineType);
1341
1455
  let syncRunnerProcesses = [];
1342
1456
  let syncRunnerOwnerPid = null;
@@ -1403,6 +1517,9 @@ export async function runDaemon(opts) {
1403
1517
  syncRunnerOwnerPid,
1404
1518
  daemonSyncRunnerPids,
1405
1519
  lanesReconcileInProcess: Boolean(laneReconcileWatcher && laneReconcileWatcherRoot === hqRoot),
1520
+ // The first plan runs under the daemon startup lease. If it cannot be
1521
+ // released, keep the old independent launcher on later reconciles.
1522
+ searchIndexWorkerAvailable: startupPlanOpen || !cliPackagePrefix || packageUseLeaseReleased,
1406
1523
  searchIndexOwnedBySyncRunner: searchIndexRunnerOwnsIndexFlag.status().enabled &&
1407
1524
  hqCloud !== null && !hqCloudVersionOlder(hqCloud.version, "6.18.75") &&
1408
1525
  syncOwner === "daemon" && services.includes("sync") && !config.syncPaused &&
@@ -1449,6 +1566,63 @@ export async function runDaemon(opts) {
1449
1566
  throw new Error(`${unit.id} has no process to start`);
1450
1567
  prepareUnitStart(unit, log);
1451
1568
  unitLogOffsets.set(unit.id, logOffset(paths.unitLogPath(unit.id)));
1569
+ if (command.type === "worker") {
1570
+ const root = unit.env.HQ_ROOT;
1571
+ if (!root)
1572
+ throw new Error("search index has no HQ folder");
1573
+ const events = new EventEmitter();
1574
+ if (activeIndexWorker) {
1575
+ log("info", "search-index is still stopping; skipping this pass");
1576
+ queueMicrotask(() => events.emit("exit", 0, null));
1577
+ return { skipped: true, on: events.on.bind(events), kill: () => false };
1578
+ }
1579
+ const controller = new AbortController();
1580
+ let fallback;
1581
+ const stop = (signal = "SIGTERM") => {
1582
+ controller.abort();
1583
+ return fallback?.kill(signal) ?? true;
1584
+ };
1585
+ let needsFallback = false;
1586
+ const done = withSearchIndexPackageLease(packageUseLeaseReleased ? cliPackagePrefix : null, () => {
1587
+ // A running daemon can survive a rollback to a package without v1.
1588
+ if (cliPackagePrefix && !fs.existsSync(searchIndexWorkerEntry)) {
1589
+ needsFallback = true;
1590
+ return Promise.resolve(true);
1591
+ }
1592
+ return runSearchIndexWorker({
1593
+ root,
1594
+ backgroundQos: unit.backgroundQos === true,
1595
+ env: unitProcessEnv(env, unit),
1596
+ logPath: paths.unitLogPath(unit.id),
1597
+ signal: controller.signal,
1598
+ });
1599
+ }, acquirePackageUseLease, stop).then((ok) => {
1600
+ if (!needsFallback || controller.signal.aborted)
1601
+ return ok;
1602
+ // The compatibility child acquires its own lease during bootstrap.
1603
+ return new Promise((resolve, reject) => {
1604
+ fallback = spawnUnit({ ...unit, command: legacySearchIndexCommand(root) });
1605
+ fallback.on("exit", (code) => resolve(code === 0));
1606
+ fallback.on("error", reject);
1607
+ });
1608
+ }).then((ok) => {
1609
+ if (activeIndexWorker?.stop === stop)
1610
+ activeIndexWorker = undefined;
1611
+ if (controller.signal.aborted)
1612
+ events.emit("exit", null, "SIGTERM");
1613
+ else
1614
+ events.emit("exit", ok ? 0 : 1, null);
1615
+ }, (error) => {
1616
+ if (activeIndexWorker?.stop === stop)
1617
+ activeIndexWorker = undefined;
1618
+ if (controller.signal.aborted)
1619
+ events.emit("exit", null, "SIGTERM");
1620
+ else
1621
+ events.emit("error", error);
1622
+ });
1623
+ activeIndexWorker = { stop, done };
1624
+ return { on: events.on.bind(events), kill: stop };
1625
+ }
1452
1626
  let [file, args] = command.type === "hq"
1453
1627
  ? daemonHqChildCommand(opts.nodeBinary, opts.hqBinary, command.args, stagedHqChildBootstrap?.bootstrapPath ?? null, cliPackagePrefix, childBootstrapHandoffWatchFlag.status().enabled)
1454
1628
  : command.type === "node"
@@ -1600,7 +1774,7 @@ export async function runDaemon(opts) {
1600
1774
  },
1601
1775
  restartDaemon: () => restartDaemon(),
1602
1776
  runGuard: daemonRunGuard,
1603
- writeState: (state) => writeJsonAtomic(paths.statePath, state),
1777
+ writeState: writeDaemonState,
1604
1778
  holds: {
1605
1779
  read: () => readUnitHolds(paths.holdsPath),
1606
1780
  write: (holds) => writeUnitHolds(paths.holdsPath, holds),
@@ -1682,6 +1856,8 @@ export async function runDaemon(opts) {
1682
1856
  platform,
1683
1857
  daemonDir: paths.root,
1684
1858
  restartable: restartsAfterTccEpermExit(opts),
1859
+ // Which program macOS checks, so the access message names the right one.
1860
+ launch: filesAccessLaunch({ managed: opts.managed, host: opts.host, ppid: process.ppid }),
1685
1861
  isStopping: () => daemonStopping,
1686
1862
  log,
1687
1863
  report: reportTccEperm,
@@ -1712,6 +1888,7 @@ export async function runDaemon(opts) {
1712
1888
  });
1713
1889
  },
1714
1890
  onServerChange: (server) => {
1891
+ hqdSessionsForRequests = server?.sessions;
1715
1892
  stopHeartbeat();
1716
1893
  stopHeartbeat = () => { };
1717
1894
  if (!server)
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=search-index-worker-v1.d.ts.map
@@ -0,0 +1,25 @@
1
+ import { workerData } from "node:worker_threads";
2
+ import { syncScheduledSearchIndex } from "../../commands/index-cmd.js";
3
+ import { qmdWorkerSpawn } from "../search-index/worker-process.js";
4
+ import { backgroundQosCommand } from "./background-qos.js";
5
+ const { root, backgroundQos, qmdPort, stopBuffer } = workerData;
6
+ try {
7
+ const spawnQmd = qmdWorkerSpawn(qmdPort);
8
+ const stop = new Int32Array(stopBuffer);
9
+ const waitForWriter = (milliseconds) => {
10
+ if (Atomics.wait(stop, 0, 0, milliseconds) !== "timed-out") {
11
+ throw new Error("The scheduled search index was stopped");
12
+ }
13
+ };
14
+ waitForWriter(0);
15
+ const result = syncScheduledSearchIndex(root, (command, args, options) => {
16
+ const [file, argv] = backgroundQosCommand([command, args], backgroundQos);
17
+ return spawnQmd(file, argv, options);
18
+ }, waitForWriter);
19
+ if (result.status === "updated")
20
+ console.log(`Updated search index for ${root}.`);
21
+ }
22
+ finally {
23
+ qmdPort.close();
24
+ }
25
+ //# sourceMappingURL=search-index-worker-v1.js.map
@@ -683,7 +683,12 @@ export async function startHqdServer(opts) {
683
683
  err instanceof MachineLoginError
684
684
  ? { code: err.code, message: err.message }
685
685
  : { code: "internal", message: err instanceof Error ? err.message : String(err) };
686
- if (error.code === "internal") {
686
+ if (error.code === "hq_root_unreadable") {
687
+ // Not a daemon bug (macOS privacy permission), so no error report,
688
+ // but it must stay visible in the daemon log.
689
+ log("warn", `hqd ${req.op} failed: ${error.message}`);
690
+ }
691
+ else if (error.code === "internal") {
687
692
  log("error", `hqd ${req.op} failed: ${error.message}`);
688
693
  try {
689
694
  opts.reportError?.(req.op, err);
@@ -25,7 +25,6 @@ export declare class SessionRegistry {
25
25
  get(runtime: string, sessionId: string): HqdSession | null;
26
26
  close(runtime: string, sessionId: string): boolean;
27
27
  clear(): void;
28
- list(): HqdSession[];
29
28
  get size(): number;
30
29
  }
31
30
  //# sourceMappingURL=session-registry.d.ts.map
@@ -35,9 +35,6 @@ export class SessionRegistry {
35
35
  clear() {
36
36
  this.sessions.clear();
37
37
  }
38
- list() {
39
- return [...this.sessions.values()];
40
- }
41
38
  get size() {
42
39
  return this.sessions.size;
43
40
  }
@@ -84,6 +84,8 @@ export declare function lockHolderPidFromOutput(output: string | undefined): num
84
84
  export declare function heartbeatProgressBytes(event: Record<string, unknown>): number | null;
85
85
  export interface SupervisedChild {
86
86
  pid?: number;
87
+ /** A scheduled attempt that finished without starting its work. */
88
+ readonly skipped?: true;
87
89
  stdout?: {
88
90
  on(event: "data" | "end", handler: (chunk?: Buffer | string) => void): unknown;
89
91
  };
@@ -145,7 +147,9 @@ interface UnitState {
145
147
  };
146
148
  lastRunAt?: number;
147
149
  nextRunAt?: number;
148
- lastResult?: "ok" | "failed";
150
+ lastResult?: "ok" | "failed" | "skipped";
151
+ /** Why the last run failed: one redacted, truncated line. Set for the in-process lanes reconcile. */
152
+ lastError?: string;
149
153
  lastHeartbeatAt?: string;
150
154
  lastPassResult?: ReturnType<typeof syncPassResult>;
151
155
  /** The pass-request folder the running child was started with; absent when it was not. */
@@ -872,7 +872,7 @@ export function createSupervisor(deps) {
872
872
  return;
873
873
  if (slot.plan.kind === "scheduled") {
874
874
  slot.busy = false;
875
- slot.state.lastResult = code === 0 ? "ok" : "failed";
875
+ slot.state.lastResult = child.skipped ? "skipped" : code === 0 ? "ok" : "failed";
876
876
  slot.state.status = "idle";
877
877
  if (code !== 0)
878
878
  deps.log("warn", `${slot.plan.id} run failed (code=${code ?? "null"} signal=${signal ?? "none"})`);
@@ -16,6 +16,14 @@
16
16
  * TCC_EPERM_EXIT_CODE. The daemon's LaunchAgent has KeepAlive=true, so launchd
17
17
  * starts it again (after its ThrottleInterval) whatever the exit code.
18
18
  *
19
+ * A daemon whose every op stops at the same file (policy.check opening the
20
+ * caller's session meta.yaml, for one) never shows a second path. So when the
21
+ * window holds enough hits on one path only, hqd lists the HQ root itself:
22
+ * macOS privacy refuses that with EPERM too, while one odd file (flags, an
23
+ * ACL) leaves the root readable. A refused root counts as the trip; a
24
+ * readable one does not, and is asked again at most once per
25
+ * TCC_EPERM_ROOT_CHECK_INTERVAL_MS.
26
+ *
19
27
  * It never exits for EPERM outside the HQ root, for EACCES, off macOS, while
20
28
  * the daemon is already stopping, or when no service manager would start it
21
29
  * again. A permission that stays revoked would otherwise restart the daemon
@@ -32,8 +40,13 @@ export declare const TCC_EPERM_EXIT_CODE = 74;
32
40
  export declare const TCC_EPERM_WINDOW_MS = 60000;
33
41
  /** Hits needed inside the window. */
34
42
  export declare const TCC_EPERM_MIN_EVENTS = 3;
35
- /** Distinct paths needed inside the window, so one odd file cannot trip it. */
43
+ /**
44
+ * Distinct paths needed inside the window, so one odd file cannot trip it.
45
+ * With fewer, the guard trips only if listing the HQ root is refused as well.
46
+ */
36
47
  export declare const TCC_EPERM_MIN_PATHS = 2;
48
+ /** While enough hits sit on too few paths, the guard lists the HQ root at most this often. */
49
+ export declare const TCC_EPERM_ROOT_CHECK_INTERVAL_MS = 10000;
37
50
  /** Exits allowed inside TCC_EPERM_EXIT_WINDOW_MS before the daemon stays up instead. */
38
51
  export declare const TCC_EPERM_MAX_EXITS = 3;
39
52
  export declare const TCC_EPERM_EXIT_WINDOW_MS: number;
@@ -41,7 +54,30 @@ export declare const TCC_EPERM_EXIT_WINDOW_MS: number;
41
54
  export declare const TCC_EPERM_EXITS_FILE = "tcc-eperm-exits.json";
42
55
  /** Under the daemon dir: present while hqd is up but cannot read the HQ folder. */
43
56
  export declare const FILES_ACCESS_NEEDED_MARKER = "files-access-needed.json";
44
- export declare const FILES_ACCESS_NEEDED_MESSAGE: string;
57
+ /**
58
+ * Which program macOS checks for the daemon's file access:
59
+ * - "node-direct": launchd runs the node binary itself (the LaunchAgent with
60
+ * no HQ.app launcher). macOS checks that binary; allowing HQ does not cover it.
61
+ * - "hq-app": HQ.app runs the daemon (desktop host, or the LaunchAgent still
62
+ * going through the HQ.app launcher). Allowing HQ covers it.
63
+ * - "terminal": started by hand, so the terminal app it ran from is checked.
64
+ */
65
+ export type FilesAccessLaunch = "node-direct" | "hq-app" | "terminal";
66
+ /**
67
+ * How this daemon was started, from its run options and parent pid. launchd
68
+ * is pid 1, so a managed daemon whose parent is launchd runs node directly;
69
+ * under the HQ.app launcher (--hq-launchd-task) the parent is the launcher.
70
+ */
71
+ export declare function filesAccessLaunch(opts: {
72
+ managed?: boolean;
73
+ host?: string;
74
+ ppid: number;
75
+ }): FilesAccessLaunch;
76
+ /**
77
+ * What to tell the user. With no known launch (a marker from an older
78
+ * daemon) this is the HQ-app wording the daemon always used.
79
+ */
80
+ export declare function filesAccessNeededMessage(launch?: FilesAccessLaunch, program?: string): string;
45
81
  export declare const TCC_EPERM_SENTRY_FINGERPRINT: readonly string[];
46
82
  export interface EpermHit {
47
83
  path: string;
@@ -98,7 +134,14 @@ export declare function decideEpermExit(input: EpermDecisionInput): EpermDecisio
98
134
  export declare function readEpermExits(daemonDir: string): number[];
99
135
  /** Add an exit at `now`, dropping ones older than the backoff window. */
100
136
  export declare function recordEpermExit(daemonDir: string, now: number, exitWindowMs?: number): number[];
101
- export declare function writeFilesAccessNeeded(daemonDir: string, now: number, reason: StayReason): void;
137
+ /**
138
+ * `launch`: how the daemon was started (filesAccessLaunch). `program`: the
139
+ * binary launchd runs (process.execPath in hqd); recorded only for
140
+ * "node-direct", the one case where it is the program macOS checks.
141
+ */
142
+ export declare function writeFilesAccessNeeded(daemonDir: string, now: number, reason: StayReason, launch?: FilesAccessLaunch, program?: string): void;
143
+ /** The message for the marker a running daemon wrote, from the launch and program it recorded. */
144
+ export declare function filesAccessNeededMessageFromMarker(daemonDir: string): string;
102
145
  export declare function clearFilesAccessNeeded(daemonDir: string): void;
103
146
  export declare function filesAccessNeeded(daemonDir: string): boolean;
104
147
  /** The one structured event logged and reported per trip. Holds counts only: no paths, no file contents. */
@@ -108,6 +151,8 @@ export interface TccEpermEvent {
108
151
  hits: number;
109
152
  distinctPaths: number;
110
153
  syscalls: string[];
154
+ /** Set when too few paths failed and the trip rests on the HQ root itself being refused. */
155
+ rootRefused?: true;
111
156
  windowMs: number;
112
157
  decision: EpermDecision["action"];
113
158
  reason?: string;
@@ -131,12 +176,22 @@ export interface TccEpermGuardDeps {
131
176
  window?: EpermWindowOptions;
132
177
  maxExits?: number;
133
178
  exitWindowMs?: number;
134
- /** Throws while the HQ root cannot be read. Default: list the root. */
179
+ /**
180
+ * Throws while the HQ root cannot be read. Default: list the root. Also
181
+ * confirms a window whose hits sit on too few paths: only an EPERM from it
182
+ * counts there.
183
+ */
135
184
  probe?: (hqRoot: string) => void;
185
+ /** How often that confirmation may list the root. Default: TCC_EPERM_ROOT_CHECK_INTERVAL_MS. */
186
+ rootCheckIntervalMs?: number;
136
187
  /** How often a daemon that stayed up checks whether access came back. */
137
188
  probeIntervalMs?: number;
138
189
  /** Run `fn` every `ms`; returns a cancel. Default: an unref'd setInterval. */
139
190
  schedule?: (fn: () => void, ms: number) => () => void;
191
+ /** How the daemon was started (filesAccessLaunch); picks the access message. Unset: the HQ-app wording. */
192
+ launch?: FilesAccessLaunch;
193
+ /** The binary launchd runs, named when `launch` is "node-direct". Default: process.execPath. */
194
+ program?: string;
140
195
  }
141
196
  export type TccEpermGuardState = "watching" | "exiting" | "access-needed";
142
197
  export interface TccEpermGuard {