@indigoai-us/hq-cli 5.345.208 → 5.345.211

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 (133) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/assets/scaffold/core/scripts/lib/trigger-fact-text.awk +152 -41
  4. package/dist/command-catalog.generated.d.ts +33 -8
  5. package/dist/command-catalog.generated.js +40 -8
  6. package/dist/command-registration-plan.d.ts +2 -2
  7. package/dist/command-registration-plan.js +1 -1
  8. package/dist/commands/access.js +11 -5
  9. package/dist/commands/agents.d.ts +8 -0
  10. package/dist/commands/agents.js +5 -0
  11. package/dist/commands/bot.d.ts +8 -0
  12. package/dist/commands/bot.js +67 -7
  13. package/dist/commands/channels.js +4 -0
  14. package/dist/commands/cloud.d.ts +83 -2
  15. package/dist/commands/cloud.js +161 -31
  16. package/dist/commands/company.d.ts +9 -0
  17. package/dist/commands/company.js +44 -14
  18. package/dist/commands/core-checkpoint-native.js +21 -0
  19. package/dist/commands/core-derive-trigger-facts-native.d.ts +1 -0
  20. package/dist/commands/core-derive-trigger-facts-native.js +75 -14
  21. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  22. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  23. package/dist/commands/core-job-run-native.d.ts +8 -0
  24. package/dist/commands/core-job-run-native.js +11 -3
  25. package/dist/commands/core-jobs-native.js +1 -1
  26. package/dist/commands/core-register-project-native.js +31 -1
  27. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  28. package/dist/commands/core-scan-packages-fast.js +8 -1
  29. package/dist/commands/core-work-mesh-bind-trusted-native.d.ts +14 -2
  30. package/dist/commands/core-work-mesh-bind-trusted-native.js +62 -8
  31. package/dist/commands/core.js +12 -3
  32. package/dist/commands/dm-attach.d.ts +10 -0
  33. package/dist/commands/dm-attach.js +33 -5
  34. package/dist/commands/integrations-connect.d.ts +16 -0
  35. package/dist/commands/integrations-connect.js +70 -6
  36. package/dist/commands/lanes-session-start.d.ts +17 -0
  37. package/dist/commands/lanes-session-start.js +281 -13
  38. package/dist/commands/lanes-watch.js +11 -3
  39. package/dist/commands/lanes.d.ts +4 -0
  40. package/dist/commands/lanes.js +95 -22
  41. package/dist/commands/library.d.ts +10 -0
  42. package/dist/commands/library.js +30 -3
  43. package/dist/commands/meetings.d.ts +42 -0
  44. package/dist/commands/meetings.js +157 -12
  45. package/dist/commands/mesh.js +3 -0
  46. package/dist/commands/monitor.d.ts +6 -0
  47. package/dist/commands/monitor.js +29 -19
  48. package/dist/commands/onboard.js +8 -1
  49. package/dist/commands/sources.js +7 -3
  50. package/dist/index.js +9 -0
  51. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  52. package/dist/lanes-monitor-check-argv.js +2 -2
  53. package/dist/lanes-session-start-argv.d.ts +4 -1
  54. package/dist/lanes-session-start-argv.js +5 -2
  55. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  56. package/dist/lib/bot/fleet-daemon.js +227 -0
  57. package/dist/lib/bot/fleet-local.d.ts +26 -0
  58. package/dist/lib/bot/fleet-local.js +51 -2
  59. package/dist/lib/bot/index.d.ts +1 -0
  60. package/dist/lib/bot/index.js +1 -0
  61. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  62. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  63. package/dist/lib/bot/log.js +3 -1
  64. package/dist/lib/bot/probe.js +2 -0
  65. package/dist/lib/bot/run.js +28 -3
  66. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  67. package/dist/lib/bot/runtime-failure.js +9 -1
  68. package/dist/lib/bot/status.d.ts +17 -0
  69. package/dist/lib/bot/status.js +53 -2
  70. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  71. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  72. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  73. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  74. package/dist/lib/core-utils/session-company.d.ts +25 -8
  75. package/dist/lib/core-utils/session-company.js +59 -17
  76. package/dist/lib/daemon/catalog.d.ts +34 -1
  77. package/dist/lib/daemon/catalog.js +42 -3
  78. package/dist/lib/daemon/run.d.ts +5 -4
  79. package/dist/lib/daemon/run.js +40 -16
  80. package/dist/lib/daemon/server.js +26 -7
  81. package/dist/lib/daemon/supervisor.d.ts +2 -0
  82. package/dist/lib/daemon/supervisor.js +60 -1
  83. package/dist/lib/daemon/tools.js +17 -1
  84. package/dist/lib/db/sqlite-binding.js +2 -1
  85. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  86. package/dist/lib/doctor/checks/bots.js +11 -0
  87. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  88. package/dist/lib/doctor/checks/work-context.js +5 -2
  89. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  90. package/dist/lib/hook-engine/resolve.js +4 -1
  91. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  92. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  93. package/dist/lib/lanes/index.d.ts +1 -1
  94. package/dist/lib/lanes/index.js +1 -1
  95. package/dist/lib/lanes/monitor.d.ts +14 -0
  96. package/dist/lib/lanes/monitor.js +51 -10
  97. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  98. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  99. package/dist/lib/lanes/store.d.ts +1 -1
  100. package/dist/lib/lanes/store.js +2 -1
  101. package/dist/lib/mesh/client.js +7 -1
  102. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  103. package/dist/lib/mesh/live/backfill-held.js +167 -7
  104. package/dist/lib/mesh/live/flush.d.ts +7 -0
  105. package/dist/lib/mesh/live/flush.js +10 -1
  106. package/dist/lib/monitor.d.ts +9 -0
  107. package/dist/lib/monitor.js +33 -7
  108. package/dist/lib/onboarding/orchestrator.js +269 -132
  109. package/dist/lib/onboarding/types.d.ts +2 -0
  110. package/dist/lib/scaffold-cli-floor.js +2 -1
  111. package/dist/lib/signals/failure-alert.js +3 -1
  112. package/dist/lib/sync-core/reconcile.js +15 -11
  113. package/dist/lib/work-context/organize.d.ts +6 -0
  114. package/dist/lib/work-context/organize.js +28 -0
  115. package/dist/lib/work-context/paths.d.ts +9 -0
  116. package/dist/lib/work-context/paths.js +15 -0
  117. package/dist/lib/work-context/prd-sync.js +2 -1
  118. package/dist/runners-alias.d.ts +54 -0
  119. package/dist/runners-alias.js +86 -0
  120. package/dist/utils/install-tree-torn.js +5 -3
  121. package/dist/utils/npm-install-flags.d.ts +27 -0
  122. package/dist/utils/npm-install-flags.js +68 -0
  123. package/dist/utils/package-use-lease.js +1 -1
  124. package/dist/utils/qmd-native-binding-error.js +2 -1
  125. package/dist/utils/self-update.js +2 -1
  126. package/dist/utils/staged-install.js +2 -1
  127. package/dist/utils/staged-npm-install.js +2 -1
  128. package/dist/utils/upload-author.d.ts +2 -1
  129. package/dist/utils/upload-author.js +9 -5
  130. package/dist/utils/version-check.js +2 -1
  131. package/dist/utils/version-gate.js +7 -6
  132. package/package.json +7 -7
  133. package/scripts/install-hook-engine.mjs +7 -3
@@ -1,4 +1,5 @@
1
1
  import * as fs from "node:fs";
2
+ import * as os from "node:os";
2
3
  import * as path from "node:path";
3
4
  import { resolveSessionId } from "./session-id.js";
4
5
  function metaValue(contents, key) {
@@ -75,38 +76,79 @@ export function sessionCompanySlugs(root, env = process.env, multiCompanyLockEna
75
76
  }
76
77
  return listedCompanySlugs(contents).filter((slug) => slug === "personal" || isExactCompanyDirectory(root, slug));
77
78
  }
79
+ /**
80
+ * Whether the multi-company session lock is on for a session whose primary
81
+ * company is `primary`, as hq-session.sh last recorded it. hq-session.sh
82
+ * (session_scope_multi_company_enabled) evaluates hooks.multi-company-session-lock
83
+ * scoped to the primary company and caches the answer in
84
+ * ~/.hq/hook-flag.multi-company-session-lock.<primary> as "<true|false> <epoch>".
85
+ * The flag is a kill switch: hq-session.sh treats a missing or unreadable
86
+ * record as on, so only a well-formed "false" record turns the lock off here.
87
+ */
88
+ export function multiCompanySessionLockRecordedOn(primary, env = process.env) {
89
+ if (!/^[A-Za-z0-9_-]+$/.test(primary))
90
+ return true;
91
+ const home = env.HOME || os.homedir();
92
+ if (!home)
93
+ return true;
94
+ let record;
95
+ try {
96
+ record = fs.readFileSync(path.join(home, ".hq", `hook-flag.multi-company-session-lock.${primary}`), "utf8");
97
+ }
98
+ catch {
99
+ return true;
100
+ }
101
+ return !/^false [0-9]+\r?\n?$/.test(record);
102
+ }
78
103
  /** A caller session id that is safe to use as one path segment. */
79
104
  const SESSION_DIR_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
80
105
  /**
81
- * The company a session bound itself to, from
82
- * workspace/sessions/<sessionId>/meta.yaml `company_slug`. This is the bind a
83
- * company bot's runner and `hq-session.sh add company` write, and that the
84
- * HQ hooks read.
106
+ * The companies a session bound itself to, from
107
+ * workspace/sessions/<sessionId>/meta.yaml: `company_slug` first, then any
108
+ * other company its `company_slugs` lock lists (`hq-session.sh add company`).
109
+ * This is the bind a company bot's runner and `hq-session.sh` write, and that
110
+ * the HQ hooks read. `company_slugs` counts only while the multi-company
111
+ * session lock is on for the session's primary company, as hq-session.sh
112
+ * recorded it; with the lock off only `company_slug` counts, the same as
113
+ * `hq-session.sh get company_slugs`.
85
114
  *
86
- * Returns undefined unless the slug names a real (non-symlink) directory
87
- * under companies/. hqd's own synthetic `hqd-*` check sessions are ignored,
88
- * so a caller cannot borrow the binding hqd wrote for a different check.
115
+ * Returns [] unless `company_slug` names a real (non-symlink) directory under
116
+ * companies/. Listed companies that are not real directories are dropped.
117
+ * hqd's own synthetic `hqd-*` check sessions are ignored, so a caller cannot
118
+ * borrow the binding hqd wrote for a different check. The session folder and
119
+ * its meta.yaml must both be real entries, not symlinks: a symlinked session
120
+ * folder could point at any meta.yaml on disk (feedback_76cb8dc3).
89
121
  */
90
- export function sessionMetaCompany(root, sessionId) {
122
+ export function sessionMetaCompanies(root, sessionId, env = process.env) {
91
123
  if (!SESSION_DIR_RE.test(sessionId) || sessionId.includes("..") || sessionId.startsWith("hqd-"))
92
- return undefined;
93
- const metaPath = path.join(root, "workspace", "sessions", sessionId, "meta.yaml");
124
+ return [];
125
+ const sessionDir = path.join(root, "workspace", "sessions", sessionId);
126
+ const metaPath = path.join(sessionDir, "meta.yaml");
94
127
  let contents;
95
128
  try {
129
+ const dirStat = fs.lstatSync(sessionDir);
130
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
131
+ return [];
96
132
  const stat = fs.lstatSync(metaPath);
97
133
  if (!stat.isFile())
98
- return undefined;
99
- contents = fs.readFileSync(metaPath, "utf8");
134
+ return [];
135
+ contents = fs.readFileSync(metaPath, "utf8").replace(/\r$/gm, "");
100
136
  }
101
137
  catch (error) {
102
138
  const code = error.code;
103
139
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "ELOOP")
104
- return undefined;
140
+ return [];
105
141
  throw error;
106
142
  }
107
- const slug = metaValue(contents, "company_slug").replace(/\r$/, "");
108
- if (!slug || slug === "personal" || !/^[A-Za-z0-9_-]+$/.test(slug))
109
- return undefined;
110
- return isExactCompanyDirectory(root, slug) ? slug : undefined;
143
+ const primary = metaValue(contents, "company_slug");
144
+ if (!primary || primary === "personal" || !/^[A-Za-z0-9_-]+$/.test(primary))
145
+ return [];
146
+ if (!isExactCompanyDirectory(root, primary))
147
+ return [];
148
+ if (!multiCompanySessionLockRecordedOn(primary, env))
149
+ return [primary];
150
+ const others = listedCompanySlugs(contents)
151
+ .filter((slug) => slug !== primary && slug !== "personal" && isExactCompanyDirectory(root, slug));
152
+ return [primary, ...others];
111
153
  }
112
154
  //# sourceMappingURL=session-company.js.map
@@ -77,6 +77,10 @@ export interface UnitPlan {
77
77
  drainSignal?: "SIGUSR2";
78
78
  /** A new CLI version alone does not restart this unit; it restarts itself when idle. */
79
79
  keepAcrossCliUpdates?: true;
80
+ /** Working directory for the process; the HQ folder, else the home folder, when absent. */
81
+ cwd?: string;
82
+ /** How long after SIGTERM the unit may keep running before SIGKILL; the supervisor's default when absent. */
83
+ stopGraceMs?: number;
80
84
  /**
81
85
  * Scheduled units only: before each timed run the supervisor asks
82
86
  * `SupervisorDeps.runGuard` whether there is work. `spawn` runs as usual,
@@ -92,6 +96,26 @@ export interface SyncCoreRunning {
92
96
  personal: boolean;
93
97
  companies: ReadonlySet<string>;
94
98
  }
99
+ /** An HQ Fleet bot on this machine, as the daemon sees it (see bot/fleet-daemon.ts). */
100
+ export interface FleetBotPlan {
101
+ name: string;
102
+ /** The gateway process, or null while the bot's HQ Fleet runtime is not fully installed. */
103
+ gateway: {
104
+ file: string;
105
+ args: string[];
106
+ env: Record<string, string>;
107
+ cwd: string;
108
+ } | null;
109
+ /** `hq bot auth <name>` has not run yet. */
110
+ authPending: boolean;
111
+ /** `hq bot start <name>` has not run yet. */
112
+ installPending: boolean;
113
+ /** The runtime's own LaunchAgent still exists (it could not be retired), by label. */
114
+ legacyAgent?: string;
115
+ /** A gateway for this bot started outside the daemon is still running; it has been asked to exit. */
116
+ outsideGateway?: number;
117
+ }
118
+ export declare const FLEET_BOT_STOP_GRACE_MS = 30000;
95
119
  export declare const FLEET_BOTS_UPDATE_UNIT = "fleet-bots-update";
96
120
  export declare const FLEET_BOTS_UPDATE_INTERVAL_SEC: number;
97
121
  export declare const FLEET_BOTS_UPDATE_INITIAL_DELAY_SEC = 120;
@@ -103,6 +127,14 @@ export declare const SYNC_CORE_SELFCHECK_UNIT = "sync-core-selfcheck";
103
127
  export declare const SYNC_CORE_SELFCHECK_INTERVAL_SEC = 3600;
104
128
  export declare const SYNC_CORE_MANIFEST_INTERVAL_SEC: number;
105
129
  export declare const SYNC_CORE_LEGACY_SETTLE_MS: number;
130
+ export type LegacySyncHolder = {
131
+ status: "started";
132
+ startedAt: number;
133
+ } | {
134
+ status: "missing";
135
+ } | {
136
+ status: "unreadable";
137
+ };
106
138
  export interface PlanContext {
107
139
  machineType: MachineType;
108
140
  platform: NodeJS.Platform;
@@ -133,6 +165,7 @@ export interface PlanContext {
133
165
  syncCoreVaults?: readonly SyncCoreVaultPlan[];
134
166
  syncCoreRunning?: SyncCoreRunning;
135
167
  legacySyncReadyForCore?: boolean;
168
+ legacySyncHolder?: LegacySyncHolder;
136
169
  now?: number;
137
170
  /** A legacy desktop app or sync unit is still managing sync. */
138
171
  desktopAppManagesSync: boolean;
@@ -154,7 +187,7 @@ export interface PlanContext {
154
187
  /** ~/.hq-agent/kit.json exists. */
155
188
  kitConfigured: boolean;
156
189
  bots: readonly string[];
157
- fleetBots?: readonly string[];
190
+ fleetBots?: readonly FleetBotPlan[];
158
191
  /** Name of a pre-daemon unit that still runs this unit id, or null. */
159
192
  legacyOwner: (unitId: string) => string | null;
160
193
  /** This CLI is a global install the updater can replace (not a project dependency). */
@@ -92,6 +92,7 @@ export function enabledServices(machineType, overrides) {
92
92
  };
93
93
  return SERVICE_NAMES.filter((s) => wanted(s) || implied(s));
94
94
  }
95
+ export const FLEET_BOT_STOP_GRACE_MS = 30_000;
95
96
  export const FLEET_BOTS_UPDATE_UNIT = "fleet-bots-update";
96
97
  export const FLEET_BOTS_UPDATE_INTERVAL_SEC = 30 * 60;
97
98
  export const FLEET_BOTS_UPDATE_INITIAL_DELAY_SEC = 120;
@@ -203,6 +204,9 @@ function planService(service, ctx) {
203
204
  ...ctx.legacySyncEnv,
204
205
  ...(vaultSync ? vaultSkipEnv(vaultSync) : {}),
205
206
  HQ_SYNC_PASS_REQUEST_DIR: ctx.syncPassRequestsDir,
207
+ // feedback_65ee9e51: nobody watches an Outpost or agent machine's
208
+ // sync, so hq-cloud holds deletes of files other members created.
209
+ ...(ctx.machineType === "outpost" || agentMachine ? { HQ_SYNC_UNATTENDED: "1" } : {}),
206
210
  },
207
211
  heartbeatTimeoutMs: ctx.syncHeartbeatTimeoutMs,
208
212
  blocked: commonBlock,
@@ -237,9 +241,20 @@ function planService(service, ctx) {
237
241
  : ctx.vaultSync?.offCompanies.has(vault.slug ?? "") === true;
238
242
  const offSince = vault.legacyOffSince ? Date.parse(vault.legacyOffSince) : Number.NaN;
239
243
  const settled = Number.isFinite(offSince) && now - offSince >= SYNC_CORE_LEGACY_SETTLE_MS;
240
- const settleNeeded = ctx.desktopAppManagesSync && !daemonAloneRunsLegacySync(ctx);
244
+ const settleNeeded = ctx.legacySyncHolder !== undefined
245
+ || (ctx.desktopAppManagesSync && !daemonAloneRunsLegacySync(ctx));
241
246
  const legacyReady = ctx.legacySyncReadyForCore === true && (!settleNeeded || settled);
242
247
  const what = vault.kind === "personal" ? "the personal vault" : `the ${vault.slug} vault`;
248
+ const holder = ctx.legacySyncHolder;
249
+ const holderBlock = holder === undefined
250
+ ? undefined
251
+ : holder.status === "missing"
252
+ ? "waiting for the current sync to take the sync lock again (the runner that held it has exited)"
253
+ : holder.status === "unreadable"
254
+ ? "waiting to learn when the sync that holds the sync lock started (its owner status could not be read)"
255
+ : !Number.isFinite(offSince) || holder.startedAt < offSince
256
+ ? `waiting for the running sync (started before the switch was turned off for ${what}) to restart`
257
+ : undefined;
243
258
  return base(service, {
244
259
  id: syncCoreUnitId(vault.uid),
245
260
  description: full
@@ -262,6 +277,7 @@ function planService(service, ctx) {
262
277
  [!ctx.signedIn, NOT_SIGNED_IN],
263
278
  [!!vault.blockedReason, vault.blockedReason ?? ""],
264
279
  [full && !legacyOff, `waiting for the current sync to be turned off for ${what}`],
280
+ [full && !!holderBlock, holderBlock ?? ""],
265
281
  [full && !legacyReady, ctx.legacySyncReadyForCore !== true
266
282
  ? "waiting for the current sync to run its plan without this vault"
267
283
  : "waiting for the desktop app's sync to pick up the off-switch"],
@@ -352,7 +368,29 @@ function planService(service, ctx) {
352
368
  }),
353
369
  ]
354
370
  : [];
355
- if (ctx.bots.length === 0) {
371
+ // On macOS the daemon runs each HQ Fleet gateway itself, so no bot needs
372
+ // its own login item (macOS reports each as "python" from an unknown
373
+ // developer). Elsewhere the runtime's own service manager keeps them.
374
+ const fleetUnits = ctx.platform === "darwin"
375
+ ? (ctx.fleetBots ?? []).map((bot) => base(service, {
376
+ id: `fleet-bots:${bot.name}`,
377
+ description: `runs the HQ Fleet bot ${bot.name}`,
378
+ restart: "always",
379
+ command: bot.gateway ? { type: "exec", file: bot.gateway.file, args: bot.gateway.args } : null,
380
+ env: bot.gateway?.env ?? {},
381
+ ...(bot.gateway ? { cwd: bot.gateway.cwd } : {}),
382
+ // The gateway finishes the reply it is sending before it exits; its own LaunchAgent gave it 25 s.
383
+ stopGraceMs: FLEET_BOT_STOP_GRACE_MS,
384
+ blocked: firstBlock([
385
+ [bot.authPending, `not signed in (run \`hq bot auth ${bot.name}\`)`],
386
+ [bot.installPending, `waiting for \`hq bot start ${bot.name}\``],
387
+ [bot.gateway === null, `the HQ Fleet runtime is not installed for ${bot.name} (run \`hq bot start ${bot.name}\`)`],
388
+ [bot.legacyAgent !== undefined, `still started by its own login item ${bot.legacyAgent} (run \`hq bot start ${bot.name}\`)`],
389
+ [bot.outsideGateway !== undefined, `waiting for its gateway started outside hq daemon (pid ${bot.outsideGateway}) to exit`],
390
+ ]),
391
+ }))
392
+ : [];
393
+ if (ctx.bots.length === 0 && fleetUnits.length === 0) {
356
394
  return fleetWatch.length > 0 ? fleetWatch : [base(service, { blocked: { state: "waiting", reason: "no local bots" } })];
357
395
  }
358
396
  return [
@@ -364,6 +402,7 @@ function planService(service, ctx) {
364
402
  // A bot drains on SIGUSR2: running turns finish, then it exits.
365
403
  drainSignal: "SIGUSR2",
366
404
  })),
405
+ ...fleetUnits,
367
406
  ...fleetWatch,
368
407
  ];
369
408
  }
@@ -390,7 +429,7 @@ function planService(service, ctx) {
390
429
  // timer for due keep-alive work, avoiding a fresh CLI process per poll.
391
430
  intervalSec: 15,
392
431
  initialDelaySec: 30,
393
- command: { type: "hq", args: ["lanes", "reconcile"] },
432
+ command: { type: "hq", args: ["runners", "reconcile"] },
394
433
  env: ctx.hqRoot ? { HQ_ROOT: ctx.hqRoot } : {},
395
434
  ...(ctx.machineType === "desktop"
396
435
  ? { runGuard: { name: "lanes-reconcile", idleIntervalSec: 60 } }
@@ -5,18 +5,20 @@
5
5
  * legacy units, the desktop app), so enabling a service, creating a bot, or
6
6
  * signing in takes effect without restarting the daemon.
7
7
  */
8
- import { type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
8
+ import { type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
9
9
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
10
10
  import { type LegacyUnit, type WindowsTaskOwner } from "./legacy.js";
11
11
  import { type DaemonLockResult } from "./lock.js";
12
12
  import { type MachineType } from "./machine-type.js";
13
13
  import { type PickedHqCloud } from "./hq-cloud.js";
14
- import { type HostApp, type Supervisor } from "./supervisor.js";
14
+ import { type WatchRunnerOwnerStatus } from "./sync-runner.js";
15
+ import { type DaemonState, type HostApp, type Supervisor } from "./supervisor.js";
15
16
  export declare const LOG_ROTATE_BYTES: number;
16
17
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
17
18
  export declare const RESTART_EXIT_CODE = 75;
18
19
  export declare function syncCoreVaultPlans(home: string, hqRoot: string | undefined, platform: NodeJS.Platform): SyncCoreVaultPlan[];
19
- export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined): UnitPlan[];
20
+ export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined, readOwnerStatus: () => WatchRunnerOwnerStatus | null): UnitPlan[];
21
+ export declare function legacySyncHeldByOtherOwner(units: DaemonState["units"], readOwnerStatus: () => WatchRunnerOwnerStatus | null): LegacySyncHolder | undefined;
20
22
  /** A bounded shutdown deadline that can account for sync push persistence. */
21
23
  export declare function createShutdownCap(): {
22
24
  promise: Promise<"timeout">;
@@ -101,7 +103,6 @@ export declare function daemonInstantSyncEnabled(env: NodeJS.ProcessEnv, configu
101
103
  * background service, so it is not one of them.
102
104
  */
103
105
  export declare function listLocalBots(root?: string): string[];
104
- export declare function listFleetRuntimeBots(root?: string): string[];
105
106
  /** Whose task `taskName` is: only the current user's own task may be taken over. */
106
107
  export declare function windowsTaskOwner(taskName: string): WindowsTaskOwner;
107
108
  export declare function probeLegacyUnits(platform: NodeJS.Platform, home: string): LegacyUnit[];
@@ -19,6 +19,7 @@ import { currentPackageUseLeaseInstall, currentPackageUseUpdateRequested } from
19
19
  import { isLocalDependencyInstall, resolveRunningInstall } from "../../utils/version-gate.js";
20
20
  import { agentKitPaths } from "../agent-kit/paths.js";
21
21
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../bot/config.js";
22
+ import { planFleetBots } from "../bot/fleet-daemon.js";
22
23
  import { botsRoot } from "../bot/paths.js";
23
24
  import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits } from "./catalog.js";
24
25
  import { effectiveSyncOwner, readDaemonConfig } from "./config.js";
@@ -57,7 +58,7 @@ import { stageSyncRunnerBundle } from "./sync-runner-bundle.js";
57
58
  import { stageHqChildBootstrap } from "./hq-child-bootstrap-stage.js";
58
59
  import { runnerSessionName } from "./remote-control.js";
59
60
  import { adoptChild, createChildTracker, finishSuccession, handoffEligible, readProcStart, stopOrphans, successionPaths, systemdKillMode, takeSuccession, writeHandoff, } from "./succession.js";
60
- import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, syncHeartbeatTimeoutMs, syncRunnerNodeOptions, watchRunnerOwnerStatusPath, } from "./sync-runner.js";
61
+ import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, SYNC_RUNNER_LEASE_CONFLICT_EXIT, syncHeartbeatTimeoutMs, syncRunnerNodeOptions, watchRunnerOwnerStatusPath, } from "./sync-runner.js";
61
62
  import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, planKey, } from "./supervisor.js";
62
63
  import { userToolDirs } from "./tools.js";
63
64
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
@@ -87,7 +88,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
87
88
  });
88
89
  }
89
90
  const rememberedSyncCoreVaults = new Map();
90
- export function planUnitsWithSyncCoreInterlock(services, context, supervisor) {
91
+ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, readOwnerStatus) {
91
92
  const companies = new Set();
92
93
  const runningVaults = new Set();
93
94
  let personal = false;
@@ -154,9 +155,39 @@ export function planUnitsWithSyncCoreInterlock(services, context, supervisor) {
154
155
  waiting = planUnits(services, transitionContext);
155
156
  legacy = waiting.find((unit) => unit.id === "sync");
156
157
  }
158
+ const holder = context.syncCoreVaults?.some((vault) => vault.phase === "full")
159
+ ? legacySyncHeldByOtherOwner(supervisor?.state().units ?? [], readOwnerStatus)
160
+ : undefined;
157
161
  const legacySyncReadyForCore = legacy !== undefined
158
- && (legacy.blocked !== undefined || supervisor?.runningPlanKey("sync") === planKey(legacy, CLI_VERSION));
159
- return planUnits(services, { ...transitionContext, legacySyncReadyForCore });
162
+ && (legacy.blocked !== undefined
163
+ || holder !== undefined
164
+ || supervisor?.runningPlanKey("sync") === planKey(legacy, CLI_VERSION));
165
+ return planUnits(services, {
166
+ ...transitionContext,
167
+ legacySyncReadyForCore,
168
+ ...(holder !== undefined ? { legacySyncHolder: holder } : {}),
169
+ });
170
+ }
171
+ export function legacySyncHeldByOtherOwner(units, readOwnerStatus) {
172
+ const sync = units.find((unit) => unit.id === "sync");
173
+ if (sync?.lastExit?.code !== SYNC_RUNNER_LEASE_CONFLICT_EXIT)
174
+ return undefined;
175
+ const retrying = sync.status === "running" && sync.startedAt !== undefined && sync.startedAt >= sync.lastExit.at;
176
+ if (sync.status !== "waiting" && !retrying)
177
+ return undefined;
178
+ let owner;
179
+ try {
180
+ owner = readOwnerStatus();
181
+ }
182
+ catch {
183
+ return { status: "unreadable" };
184
+ }
185
+ if (!owner)
186
+ return { status: "missing" };
187
+ if (retrying && sync.pid !== undefined && owner.pid === sync.pid)
188
+ return undefined;
189
+ const startedAt = Date.parse(owner.startedAt);
190
+ return Number.isFinite(startedAt) ? { status: "started", startedAt } : { status: "unreadable" };
160
191
  }
161
192
  /** A bounded shutdown deadline that can account for sync push persistence. */
162
193
  export function createShutdownCap() {
@@ -359,15 +390,6 @@ export function listLocalBots(root = botsRoot()) {
359
390
  .map((d) => d.name)
360
391
  .sort();
361
392
  }
362
- export function listFleetRuntimeBots(root = botsRoot()) {
363
- if (!fs.existsSync(root))
364
- return [];
365
- return fs
366
- .readdirSync(root, { withFileTypes: true })
367
- .filter((d) => d.isDirectory() && readBotConfig(path.join(root, d.name))?.engine?.id === HQ_FLEET_RUNTIME_ENGINE_ID)
368
- .map((d) => d.name)
369
- .sort();
370
- }
371
393
  /** Whose task `taskName` is: only the current user's own task may be taken over. */
372
394
  export function windowsTaskOwner(taskName) {
373
395
  const run = (cmd, args) => {
@@ -1153,7 +1175,7 @@ export async function runDaemon(opts) {
1153
1175
  !appManagesSync && Boolean(hqRoot && isSignedIn && runners.syncRunner),
1154
1176
  syncHeartbeatTimeoutMs: syncHeartbeatTimeoutMs(env),
1155
1177
  bots: listLocalBots(),
1156
- fleetBots: listFleetRuntimeBots(),
1178
+ fleetBots: planFleetBots({ platform, home, env, log: (message) => log("info", message) }),
1157
1179
  legacyOwner: legacyOwnerLookup(legacy),
1158
1180
  cliSelfUpdatable: updatable,
1159
1181
  claudePath: findUserBinary("claude", env, home),
@@ -1171,7 +1193,9 @@ export async function runDaemon(opts) {
1171
1193
  availablePoolFrontends,
1172
1194
  unverifiablePoolFrontends,
1173
1195
  };
1174
- const plans = planUnitsWithSyncCoreInterlock(services, context, supervisor);
1196
+ const plans = planUnitsWithSyncCoreInterlock(services, context, supervisor, () => hqRoot
1197
+ ? readWatchRunnerOwnerStatus(watchRunnerOwnerStatusPath(hqRoot, home, env))
1198
+ : null);
1175
1199
  if (startupPlanOpen) {
1176
1200
  const replaceablePackageRoots = cliPackageRoot ? [cliPackageRoot] : [];
1177
1201
  if (hqCloud?.source === "bundled")
@@ -1197,7 +1221,7 @@ export async function runDaemon(opts) {
1197
1221
  : [command.file, command.args];
1198
1222
  [file, args] = backgroundQosCommand([file, args], unit.backgroundQos === true);
1199
1223
  const logPath = paths.unitLogPath(unit.id);
1200
- const cwd = unit.env.HQ_ROOT && fs.existsSync(unit.env.HQ_ROOT) ? unit.env.HQ_ROOT : home;
1224
+ const cwd = unit.cwd && fs.existsSync(unit.cwd) ? unit.cwd : unit.env.HQ_ROOT && fs.existsSync(unit.env.HQ_ROOT) ? unit.env.HQ_ROOT : home;
1201
1225
  const childEnv = daemonChildOwnershipEnv(env, unit, succession ? succession.handoffPath : null);
1202
1226
  const trackOwner = command.type === "hq";
1203
1227
  if (unit.heartbeatTimeoutMs && succession) {
@@ -16,7 +16,7 @@ import { createResolver } from "./resolver.js";
16
16
  export { createResolver };
17
17
  import { createLineSplitter, encodeMessage, HQD_DEFAULT_REQUEST_TIMEOUT_MS, HQD_MAX_LINE_BYTES, parseRequestLine } from "./protocol.js";
18
18
  import { SessionRegistry } from "./session-registry.js";
19
- import { sessionMetaCompany } from "../core-utils/session-company.js";
19
+ import { sessionMetaCompanies } from "../core-utils/session-company.js";
20
20
  import { journalAppend, JournalOpError } from "./ops/journal.js";
21
21
  import { memoryGet, memoryPut, MemoryOpError } from "./ops/memory.js";
22
22
  import { meshPresence, MeshOpError } from "./ops/mesh.js";
@@ -322,7 +322,19 @@ export async function startHqdServer(opts) {
322
322
  throw new OpError("company_mismatch", `explicit company ${explicit} conflicts with bound company ${bound}`);
323
323
  }
324
324
  };
325
- /** Resolve a call's company while keeping any session or cwd binding authoritative. */
325
+ /** The companies a session's own meta.yaml locks it to; [] when it has no usable persisted bind. */
326
+ const persistedCompanies = (sessionId) => opts.hqRoot && sessionId ? sessionMetaCompanies(opts.hqRoot, sessionId, env) : [];
327
+ /**
328
+ * A session that persisted a company bind may act only for the companies it
329
+ * locked. An explicit company, a cwd-linked company or a session.open company
330
+ * outside that lock is a conflict, not an override (feedback_76cb8dc3).
331
+ */
332
+ const assertCompanyMatchesPersisted = (company, source, persisted) => {
333
+ if (company && persisted.length > 0 && !persisted.includes(company)) {
334
+ throw new OpError("company_mismatch", `${source} company ${company} conflicts with the session's persisted company ${persisted.join(",")}`);
335
+ }
336
+ };
337
+ /** Resolve a call's company while keeping any session, cwd or persisted binding authoritative. */
326
338
  const companyFor = (args) => {
327
339
  const explicit = stringArg(args, "company", false);
328
340
  const runtime = stringArg(args, "runtime", false);
@@ -335,15 +347,19 @@ export async function startHqdServer(opts) {
335
347
  }
336
348
  const boundCompany = session?.company ?? cwdCompany;
337
349
  assertCompanyMatchesBinding(explicit, boundCompany);
350
+ const persisted = persistedCompanies(sessionId);
351
+ assertCompanyMatchesPersisted(explicit, "explicit", persisted);
352
+ assertCompanyMatchesPersisted(session?.company ?? undefined, "session", persisted);
353
+ assertCompanyMatchesPersisted(cwdCompany, "cwd-bound", persisted);
338
354
  if (explicit ?? boundCompany)
339
355
  return explicit ?? boundCompany;
340
356
  // Neither the call, the in-memory session nor the cwd names a company:
341
- // fall back to the session's own persisted bind (meta.yaml company_slug),
342
- // which a company bot's runner writes for every turn and which survives a
343
- // daemon restart. A bot at the unlinked HQ root then resolves its own
344
- // company, and the policy check still scopes it to that one company
357
+ // use the session's own persisted bind (meta.yaml company_slug), which a
358
+ // company bot's runner writes for every turn and which survives a daemon
359
+ // restart. A bot at the unlinked HQ root then resolves its own company,
360
+ // and the policy check still scopes it to that one company
345
361
  // (feedback_578dd8ff).
346
- return opts.hqRoot && sessionId ? sessionMetaCompany(opts.hqRoot, sessionId) : undefined;
362
+ return persisted[0];
347
363
  };
348
364
  let hqMcp = opts.mcpBridge;
349
365
  if (!isPipe) {
@@ -507,6 +523,9 @@ export async function startHqdServer(opts) {
507
523
  const boundCompany = resolve(cwd).company;
508
524
  assertCompanyMatchesBinding(explicit, boundCompany ?? undefined);
509
525
  const company = explicit ?? boundCompany;
526
+ // Opening must not give the session a company its own persisted bind
527
+ // does not lock (feedback_76cb8dc3).
528
+ assertCompanyMatchesPersisted(company ?? undefined, explicit ? "explicit" : "cwd-bound", persistedCompanies(sessionId));
510
529
  return sessions.open({ runtime, sessionId, cwd: canonicalDir(cwd), company });
511
530
  }
512
531
  case "session.get": {
@@ -57,6 +57,8 @@ export declare const SYNC_CORE_LOCK_HELD_EXIT = 17;
57
57
  export declare const SYNC_CORE_PROGRESS_EXEMPT_MAX = 6;
58
58
  /** How often a unit held for exit 17 checks whether the lock holder is still alive. */
59
59
  export declare const LOCK_HOLDER_POLL_MS = 5000;
60
+ export declare const WAKE_TICK_MS = 5000;
61
+ export declare const WAKE_GAP_MS = 30000;
60
62
  /**
61
63
  * The pid hq-syncd names when it exits 17: "local sync engine is already
62
64
  * running (pid N)" or "HQ operation lock for ... is held by "cmd" (pid N)".
@@ -62,6 +62,8 @@ export const SYNC_CORE_LOCK_HELD_EXIT = 17;
62
62
  export const SYNC_CORE_PROGRESS_EXEMPT_MAX = 6;
63
63
  /** How often a unit held for exit 17 checks whether the lock holder is still alive. */
64
64
  export const LOCK_HOLDER_POLL_MS = 5_000;
65
+ export const WAKE_TICK_MS = 5_000;
66
+ export const WAKE_GAP_MS = 30_000;
65
67
  /**
66
68
  * The pid hq-syncd names when it exits 17: "local sync engine is already
67
69
  * running (pid N)" or "HQ operation lock for ... is held by "cmd" (pid N)".
@@ -238,6 +240,55 @@ export function createSupervisor(deps) {
238
240
  clearT(slot.heartbeatTimer);
239
241
  slot.heartbeatTimer = undefined;
240
242
  };
243
+ let wakeTickTimer;
244
+ let lastWakeTickAt;
245
+ let resumedAt;
246
+ const noteWakeGap = () => {
247
+ if (lastWakeTickAt === undefined)
248
+ return;
249
+ const at = now();
250
+ if (at - lastWakeTickAt > WAKE_GAP_MS)
251
+ resumedAt = at;
252
+ lastWakeTickAt = at;
253
+ };
254
+ const stopWakeTicker = () => {
255
+ if (wakeTickTimer !== undefined)
256
+ clearT(wakeTickTimer);
257
+ wakeTickTimer = undefined;
258
+ lastWakeTickAt = undefined;
259
+ };
260
+ const scheduleWakeTick = () => {
261
+ const handle = setT(() => {
262
+ wakeTickTimer = undefined;
263
+ noteWakeGap();
264
+ if (stopped || ![...slots.values()].some((s) => s.heartbeatTimer !== undefined)) {
265
+ lastWakeTickAt = undefined;
266
+ return;
267
+ }
268
+ scheduleWakeTick();
269
+ }, WAKE_TICK_MS);
270
+ if (typeof handle === "object" && handle !== null && "unref" in handle && typeof handle.unref === "function") {
271
+ handle.unref();
272
+ }
273
+ wakeTickTimer = handle;
274
+ };
275
+ const ensureWakeTicker = () => {
276
+ if (wakeTickTimer !== undefined)
277
+ return;
278
+ lastWakeTickAt = now();
279
+ scheduleWakeTick();
280
+ };
281
+ const resumedWithin = (windowMs) => {
282
+ noteWakeGap();
283
+ if (resumedAt === undefined)
284
+ return false;
285
+ const sinceResume = now() - resumedAt;
286
+ if (sinceResume < 0) {
287
+ resumedAt = undefined;
288
+ return false;
289
+ }
290
+ return sinceResume < windowMs;
291
+ };
241
292
  const clearDeferredCliRestart = () => {
242
293
  deferredCliRestart = false;
243
294
  if (deferredCliRestartTimer !== undefined)
@@ -505,7 +556,7 @@ export function createSupervisor(deps) {
505
556
  * `drain`, a unit that has a drain signal gets it first and SIGTERM only
506
557
  * after HANDOFF_DRAIN_MAX_MS; SIGKILL follows SIGTERM after STOP_ESCALATION_MS.
507
558
  */
508
- const terminate = (slot, then, drain = false, killGraceMs = STOP_ESCALATION_MS) => {
559
+ const terminate = (slot, then, drain = false, killGraceMs = slot.plan.stopGraceMs ?? STOP_ESCALATION_MS) => {
509
560
  clearPendingSyncCommandRestart(slot);
510
561
  clearTimer(slot);
511
562
  clearHeartbeatTimer(slot);
@@ -587,10 +638,16 @@ export function createSupervisor(deps) {
587
638
  if (!timeoutMs)
588
639
  return;
589
640
  clearHeartbeatTimer(slot);
641
+ ensureWakeTicker();
590
642
  slot.heartbeatTimer = setT(() => {
591
643
  slot.heartbeatTimer = undefined;
592
644
  if (stopped || slot.child !== child || slot.expectingExit)
593
645
  return;
646
+ if (resumedWithin(timeoutMs)) {
647
+ deps.log("info", `${slot.plan.id} emitted no sync protocol heartbeat for ${timeoutMs}ms, but this machine resumed from sleep ${now() - (resumedAt ?? now())}ms ago; waiting another ${timeoutMs}ms before restarting it`);
648
+ armHeartbeatWatchdog();
649
+ return;
650
+ }
594
651
  // An engine that reported bytes moving during this run is slow, not
595
652
  // hung: restart it, but do not count it toward the exhausted hold.
596
653
  // Bounded per episode: past SYNC_CORE_PROGRESS_EXEMPT_MAX these count again.
@@ -1451,6 +1508,7 @@ export function createSupervisor(deps) {
1451
1508
  clearT(handoffTimer);
1452
1509
  clearDeferredCliRestart();
1453
1510
  clearPendingSyncCommandRestart();
1511
+ stopWakeTicker();
1454
1512
  const childOwners = new Map(liveOwners);
1455
1513
  for (const slot of slots.values()) {
1456
1514
  clearTimer(slot);
@@ -1546,6 +1604,7 @@ export function createSupervisor(deps) {
1546
1604
  if (handoffTimer !== undefined)
1547
1605
  clearT(handoffTimer);
1548
1606
  clearDeferredCliRestart();
1607
+ stopWakeTicker();
1549
1608
  for (const slot of slots.values()) {
1550
1609
  clearTimer(slot);
1551
1610
  if (slot.killTimer !== undefined)
@@ -8,6 +8,7 @@
8
8
  * it can update) and never updates a copy it cannot write.
9
9
  */
10
10
  import * as path from "node:path";
11
+ import { npmGlobalInstallArgv } from "../../utils/npm-install-flags.js";
11
12
  export const TOOL_NAMES = ["claude", "codex", "grok"];
12
13
  /** npm package for tools that can be installed with npm. */
13
14
  const NPM_PACKAGES = {
@@ -15,6 +16,17 @@ const NPM_PACKAGES = {
15
16
  codex: "@openai/codex",
16
17
  grok: "@vibe-kit/grok-cli",
17
18
  };
19
+ /**
20
+ * Packages in each tool's npm install tree whose install scripts must run
21
+ * (npm 12 blocks unlisted ones). Claude Code's postinstall links its native
22
+ * binary; Codex ships its binary only as an optional dependency, which
23
+ * `--include=optional` keeps. Matches the HQ desktop app's allow-list.
24
+ */
25
+ const NPM_ALLOW_SCRIPTS = {
26
+ claude: ["@anthropic-ai/claude-code"],
27
+ codex: [],
28
+ grok: [],
29
+ };
18
30
  /** Environment each tool's own `update` command needs to run unattended. */
19
31
  const UPDATE_ENV = {
20
32
  codex: { CODEX_NON_INTERACTIVE: "1" },
@@ -88,7 +100,11 @@ export function toolUpdateCommand(name, install, platform = process.platform) {
88
100
  const pkg = NPM_PACKAGES[name];
89
101
  const prefix = pkg ? npmPrefixOf(install.realPath, pkg, platform) : null;
90
102
  if (pkg && prefix) {
91
- return { file: "npm", args: ["install", "-g", "--prefix", prefix, `${pkg}@latest`], env: {} };
103
+ return {
104
+ file: "npm",
105
+ args: npmGlobalInstallArgv(`${pkg}@latest`, { prefix, allowScripts: NPM_ALLOW_SCRIPTS[name] ?? [] }),
106
+ env: {},
107
+ };
92
108
  }
93
109
  return { file: install.path, args: ["update"], env: { ...(UPDATE_ENV[name] ?? {}) } };
94
110
  }
@@ -9,12 +9,13 @@ import fs from "node:fs";
9
9
  import { createRequire } from "node:module";
10
10
  import path from "node:path";
11
11
  import { planResolvedCommandSpawn } from "../../utils/windows-spawn.js";
12
+ import { HQ_CLI_NPM_REPAIR_COMMAND } from "../../utils/npm-install-flags.js";
12
13
  const require = createRequire(import.meta.url);
13
14
  export class SqliteBindingError extends Error {
14
15
  constructor(cause) {
15
16
  super("better-sqlite3 did not load. npm 11.16 and later skip its install script unless scripts are allowed, so the prebuilt binary was not downloaded. " +
16
17
  "HQ tried to download the prebuild and it still failed. " +
17
- "Fix: npm install -g @indigoai-us/hq-cli --allow-scripts=better-sqlite3");
18
+ `Fix: ${HQ_CLI_NPM_REPAIR_COMMAND}`);
18
19
  this.name = "SqliteBindingError";
19
20
  if (cause !== undefined)
20
21
  this.cause = cause;